答:
Don't worry about performance in this case - this kind of micro-optimization is meaningless, useless, and in short, a waste of time.

The only scenario where one would introduce temporary variables for performance reasons is when the result of a nontrivial calculation is used several times, and you want to avoid performing the calculation repeatedly. For example, in the following code:

```<code>for ($i = 0; $i < strlen($label); ++$i) {
    print $label[$i] . "; ";
}
</code>```

...strlen($label) gets executed on every iteration, which is kind of wasteful, horribly so if your string is very long. In this situation, it pays off to precalculate the string length and store it in a variable:

```<code>$len = strlen($label);
for ($i = 0; $i < $len; ++$i) {
    print $label[$i] . "; ";
}
</code>```

So much for performance.

In a real-world situation, however, the first thing you want to optimize for is not performance, but maintainability, in this case in the form of readability. Depending on the situation, the introduction of intermediate variables can greatly enhance readability, and it is not unusual to find, after splitting up complex computations using this technique, that the code in question can be simplified a lot, making it both easier to read and more efficient.

Title: PHP best practice in return values

Body:
Don't worry about performance in this case - this kind of micro-optimization is meaningless, useless, and in short, a waste of time.

The only scenario where one would introduce temporary variables for performance reasons is when the result of a nontrivial calculation is used several times, and you want to avoid performing the calculation repeatedly. For example, in the following code:

for ($i = 0; $i < strlen($label); ++$i) {
    print $label[$i] . "; ";
}

...strlen($label) gets executed on every iteration, which is kind of wasteful, horribly so if your string is very long. In this situation, it pays off to precalculate the string length and store it in a variable:

$len = strlen($label);
for ($i = 0; $i < $len; ++$i) {
    print $label[$i] . "; ";
}

So much for performance.

In a real-world situation, however, the first thing you want to optimize for is not performance, but maintainability, in this case in the form of readability. Depending on the situation, the introduction of intermediate variables can greatly enhance readability, and it is not unusual to find, after splitting up complex computations using this technique, that the code in question can be simplified a lot, making it both easier to read and more efficient.


问:
I've stopped coding for fun, is this a bad sign?
At some point in time, I just stopped coding for fun.  I used to go to work, finish my assignments and then upon arriving home I'd go and write stuff on the side for fun.  However, I now just go home and try to avoid the computer.  I'd rather read the paper, watch TV, go out to the bar, etc.

Is this a bad sign?  I mean I still try to keep up on the latest trends, hit up the developer forums/blogs/etc but I haven't said, "I want to learn language X - I wonder if I could write app Y in it"

Has this happened to anyone else?

答:
I'd question why are you trying to avoid the computer.  If it is because you are so frustrated that you want to chuck it out the window, then you may want to seek some professional help with either anger issues or career counseling, as each is a different way to solve this problem.

Another way to see this is the maturity you've developed for the field.  Where initially one could see a new language as a shiny new toy to enjoy, you could see the pain of trying to do it and that prevents you from going there, possibly.

ContentLicense: CC BY-SA 2.5


问:
design for interruptable operations
I couldn't find a better topic but here it is;

1) When user clicks a button, code starts t work,

2) When another button is clicked, it would stop doing whatever it does and start to run the second button's code,

3) Or with not user interaction, an electrical power down detected from a connected device, so our software would cancel the current event and start doing the power down procedure.

How is this design mostly applied to code? I mean "stop what you are doing" part?

If you would say events, event handlers etc. how do you bind a condition to the event? and how do you tell the program without using laddered if's to end it's process?

```<code>method1();
if (powerdown) return;
method2();
if (powerdown) return;
</code>```

etc.

答:
If you consider a multi-thread program, it should be possible to implement some control for each thread and its respective operation.

Regarding the "stop what you are doing" part: If you are consuming a resource (connection to a DB, file, etc.) and you stop manipulating its data abruptly you gotta make sure your application is reliable, you must use a .NET transaction API to make the operation atomic and control the operation queue in case the process stops, otherwise you will end up with corrupted data and your application will become inconsistent.
http://www.springframework.net/doc-latest/reference/html/transaction.html

Remember: It's not a good practice to rely on Exceptions for flow-control so, connect a monitoring component to your application and take action whenever you identify that the connected server (as you mentioned in your question) is down.
e.g., http://www.dofactory.com/Patterns/PatternObserver.aspx

ContentLicense: CC BY-SA 3.0

Title: design for interruptable operations


问:
What can I do with urllib?
I grasp that it can fetch internet resources, but I'm not really fully appreciating what that means. I was doing the challenges at pythonchallenge.com, and I got past the one that requires urllib to fetch the page and read the source, but I don't see how this is useful quite yet. And examples are kind of lacking in diversity.

What else can it do, or how can I use this to my advantage?

(Besides building a web browser...)

答:
The internet and the world wide web is much, much bigger than just a bunch of web pages. There is a lot of information held behind web apis. For example, you can get stock quotes, weather, the price of tea in china, and so on.

Urllib, and libraries built on top of it, make it remarkably easy to gain access to this data. Much of it is in the form of JSON, which can easily be converted to native python data structures such as dictionaries and lists.

Title: What can I do with urllib?


问:
What are tangible advantages to proper Unit Tests over Functional Test called unit tests
A project I am working on has a bunch of legacy tests that were not properly mocked out. Because of this the only dependency it has is EasyMock, which doesn't support statics, constructors with arguments, etc. The tests instead rely on database connections and such to "run" the tests. Adding powermock to handle these cases is being shot down as cost prohibitive due to the need to upgrade the existing project to support it (Another discussion).

My questions are, what are the REAL world tangible benifits of proper unit testing I can use to push back? Are there any? Am I just being a stickler by saying that bad unit tests (even if they work) are bad? Is code coverage just as effective?

答:
Unit tests are just a tool used to help a developer deliver reliable code. If you think like your boss thinks, you will be able to convince him if what you are proposing makes sense. However, if you present it as an evangelist on a band wagon, you won't get the resources allocated. You will need to explain to him how he benefits by spending the time and resources retrofitting unit tests to you legacy application.

You mentioned legacy tests - that implies legacy code. Unfortunately, fitting unit tests to code that was not designed to be unit tested is a difficult, time consuming and expensive process. The business case get even harder if you have tests that provide useful results, and all you are going to achieve is (from the business case POV) alternate tests providing the same results. You will need to focus on the cost(time) savings.....

My guess is that you will not be able to present your boss with a robust business case because there is not one.


问:
XMPP— openfire, PHP and python web service
I am planning to integrate real time notifications into a web application that I am currently working on. I have decided to go with XMPP for this and selected openfire server which I thought to be suitable for my needs.

The front end uses the strophe library to fetch the notifications using BOSH from my openfire server. However the notices are the notifications and other messages are to be posted by my application and hence I think this code needs to reside at the backend. Initially I thougt of going with PHP XMPP libraries like XMPHP and JAXL but then I think that this would cause much overhead as each script will have to do the same steps like connection, authentication etc. and I think this would make the PHP end a little slow and unresponsive.

Now I am thinking of creating a middle-ware application acting as a web service that PHP will call and this application will handle the XMPP service. The benefit with this is that this app (a server if you will) will have to connect just once and it will sit there listening on a port. I am also planning to build it in a asynchronous way such that it will first take all the requests from my PHP app and then when there are no more requests; go about doing the notification publishing stuff. I am planninng to create this service in Python using SleekXMPP.

This is just what I planned. I am new to XMPP and this whole web service stuff and would like to take your comments on this regarding issues like memory and CPU usage, advantages, disadvantages, scalability issues, security etc.

PS:-- also if something like this already exists (although I didn't find after a lot of Googling) Please direct me there.

EDIT --- The middle-level service should be doing the following (but not limited to):
1. Publishing notifications for different level of groups and community pages.
2. Notification for single user on some event.
3. User registration (can be done using user service plugin though).

EDIT --- Also it would need to create pub-sub nodes and subscribe and unsubscribe users from these pub-sub nodes.

EDIT -- Working with Twisted-Python to develop the REST API part now(had to chose between XML_RPC and REST) will keep updating this question as I go along.

Also I want to store the notifications and messages in a database (openfire doesn't). Would that be a good choice?

答:
while I like the idea of a server acting as a middleman between your web-app and openfire, because:

it separates the web-app from the notifications.

it makes it possible to scale separately from the web-app.

remaining connected it uses less resources.

there are 2 things I would consider:

using a different language / environment for the connection to openfire can create considerable overhead for maintenance and deploy.

the possibility to use background tasks to push the notifications to openfire (will not slow down your app's response time):
see for example: this php library for a background job-queue

see a related stack overflow discussion here


问:
Are there any surveys on to what degree developers like or hate scrum?
Background:
During a conference an analyst pointed out in a tweet that developers hate scrum.

Myself and another person responded that this was not the case, and started discussing different scenarios on why developers would dislike scrum.

One of the scenarios where that lazy developers are not able to hide in a scrum project. They are constantly challenged by the team to contribute.

This discussion resulted in a blog post and video
http://elsewhat.com/2010/05/20/lazy-developers-hate-agile-and%C2%A0scrum/

I've gotten three comments which I've tried to answer in a neutral way, but they comments do point out that there are some people who loathe scrum (and I am always 100% certain they are not lazy developers).

Question

Have there ever been a survey among developers on to what degree developers like or hate scrum ?

答:
To my experience,
Developers/architects hate scrum a lot. Could be because of below reasons

Lot of product organizations mostly consider business delivery is primary goal and tie every sprint story to a business need. Hence they hijack/compromise the motives of architecture, platform, clean design, code quality in several occasions. Sometimes they don't consider cries of developers. This is what felt by professional developers who are not lazy.

Agile/scrum gives dominance, lenience product owners/product managers a lot on not giving complete details regard to requirement and inturn they expect developers imagine/assume the need to proceed with development. This leads difference in implementation, too many defects, huge pain for developers by burning their midnight oil in lot of times.

In many occasions product owners compromise technical requirements with business goals often ignore developers, architect opinions on product, atform, long term goals of architecture and they end us with short term solutions to proceed which is not a right choice for any product

Eventually you will end up with a product which has defects, design flaws, build rollbacks sometimes, dissatisfaction ratings from user, performance issues, horrible codebase for developer to touch further.

I truely not consider scrum/agile as better methodology in many occasions.


问:
Why C# doesn’t support multiple inheritance?
Even if it could be bad practices, I would say that there is time that it would fulfill its purpose.</p>

答:
Walter Bright is both the creator of D, which does not include MI, and the only person ever to write an entire C++ compiler by himself.  According to him, the reason D lacks MI is that it's too hard to create a system of MI that's simultaneously efficient, simple and useful.  I suspect Java and C# use similar reasoning.  Languages like Perl and Python don't have efficiency as a primary goal, so they have a system that's simple and useful, but hard to implement efficiently.  C++ doesn't seem to have simplicity as a goal, so it created a massively complicated system that almost noone understands.

I think Walter is right on target.  If there exists any language that has an MI system that satisfies all three of these criteria reasonably well, please leave a comment.


问:
Why was GOTO included in PHP 5?
I discovered some time ago that the GOTO control keyword was introduced in PHP 5.3.0.

http://php.net/manual/en/control-structures.goto.php

Why did it happen?

What are the language design goals behind this?

Did the PHP developers community asked for it?

答:
One can write bad code in any language.  Having goto in the language doesn't mean the language is bad.

Consider existing structures in various languages - break, continue, next, last, throw.  Even switch  These are all forms of a computed go to that go from one level of scope to the same or higher level of scope.

The problem with goto is when it enters a deeper level of scope or jumps stack frames.

One will note the Example 3 in the linked document from the question:

```<code><?php
goto loop;
for($i=0,$j=50; $i<100; $i++) {
  while($j--) {
    loop:
  }
}
echo "$i = $i";
?>
</code>```

This will not work because the goto is attempting to jump into a deeper level of scope.

There is nothing wrong with various forms of restricted goto, be the keyword named goto or some other branching name.  The alternatives (ugly conditionals in for loops) may often be worse.  As it is, using goto simplfies the

Personally, I don't like the example given as example #1

```<code><?php
goto a;
echo 'Foo';

a:
echo 'Bar';
?>
</code>```

However, this doesn't cause problems with the language other than the necessity to apply some form corporal learning experience to the developer who intentionally writes code like this.

Title: Why was GOTO included in PHP 5?

Body:
One can write bad code in any language.  Having goto in the language doesn't mean the language is bad.

Consider existing structures in various languages - break, continue, next, last, throw.  Even switch  These are all forms of a computed go to that go from one level of scope to the same or higher level of scope.

The problem with goto is when it enters a deeper level of scope or jumps stack frames.

One will note the Example 3 in the linked document from the question:

<?php
goto loop;
for($i=0,$j=50; $i<100; $i++) {
  while($j--) {
    loop:
  }
}
echo "$i = $i";
?>

This will not work because the goto is attempting to jump into a deeper level of scope.

There is nothing wrong with various forms of restricted goto, be the keyword named goto or some other branching name.  The alternatives (ugly conditionals in for loops) may often be worse.  As it is, using goto simplfies the

Personally, I don't like the example given as example #1

<?php
goto a;
echo 'Foo';

a:
echo 'Bar';
?>

However, this doesn't cause problems with the language other than the necessity to apply some form corporal learning experience to the developer who intentionally writes code like this.


答:
The person responsible gives the reason for adding it in this blog post.

[T]he project I was working on (and may pick back up someday) was a
  workflow based site builder […] for making dynamic websites without
  knowing a programming language. You build up all the meta-information
  about how your site should run, then the site-builder “compiles” that
  into PHP code that’ll run on the actual server.

It can be done without GOTO, but the resulting logic for the
  particularly complex bits of business logic become much simpler with
  it.

In PHP's defense, it only lets you jump to labels within a limited scope, which limits the harm that can be done.

(You might also argue that given the way PHP has apparently absorbed every construct from every programming language ever invented, the addition of goto was simply inevitable)

Title: Why was GOTO included in PHP 5?

Body:
I discovered some time ago that the GOTO control keyword was introduced in PHP 5.3.0.

http://php.net/manual/en/control-structures.goto.php

Why did it happen?

What are the language design goals behind this?

Did the PHP developers community asked for it?

ContentLicense: CC BY-SA 4.0


答:
On a lower level PHP had goto since PHP 4. With PHP 4 the interpreter was redone and the Zend Engine was introduced, which includes a  compiler that compiles down to low-level "opcodes" which are handed over to an executor.

On that level a jump operation is used for all if, switch or any loop statements. With PHP 5.3 it was decided to export that under the name of goto after a long discussion.

The main reasons were:

It can be done without any cost (we already had it internally anyway)

It can help when writing code generators

Sometimes it can help to clean up with error handling code.

The first two items might not need explanation, and the third part is about situations like this:

```<code> function do() {
     $lock = $acquire_lock...)
     if (!do_something()) {
         goto cleanup
     }
     if (!do_more()) {
          goto cleanup;
     }
  cleanup:
  free_lock($lock);
</code>```

Of course you have few such situations in PHP, as PHP has a reference counted garbage collection system which will predictably free such variables and associated resources. Nonetheless such situations exist where developers either duplicated the clean up code multiple times or abuse ddo { } while (0); with break as goto emulation.

To prevent misuse the implementation was limited in a way that you can not jump into loops. So "abuse" in the way of the famous Duff's Device won't be possible.

In the end PHP is being developed to solve problems, it is not fully protecting you from shooting in your own foot, you can abuse many features in way worse ways than this limited goto. So, the conclusion was there are edge cases where it is useful and can solve problems.

Title: Why was GOTO included in PHP 5?

Body:
On a lower level PHP had goto since PHP 4. With PHP 4 the interpreter was redone and the Zend Engine was introduced, which includes a  compiler that compiles down to low-level "opcodes" which are handed over to an executor.

On that level a jump operation is used for all if, switch or any loop statements. With PHP 5.3 it was decided to export that under the name of goto after a long discussion.

The main reasons were:

It can be done without any cost (we already had it internally anyway)

It can help when writing code generators

Sometimes it can help to clean up with error handling code.

The first two items might not need explanation, and the third part is about situations like this:

 function do() {
     $lock = $acquire_lock...)
     if (!do_something()) {
         goto cleanup
     }
     if (!do_more()) {
          goto cleanup;
     }
  cleanup:
  free_lock($lock);

Of course you have few such situations in PHP, as PHP has a reference counted garbage collection system which will predictably free such variables and associated resources. Nonetheless such situations exist where developers either duplicated the clean up code multiple times or abuse ddo { } while (0); with break as goto emulation.

To prevent misuse the implementation was limited in a way that you can not jump into loops. So "abuse" in the way of the famous Duff's Device won't be possible.

In the end PHP is being developed to solve problems, it is not fully protecting you from shooting in your own foot, you can abuse many features in way worse ways than this limited goto. So, the conclusion was there are edge cases where it is useful and can solve problems.


问:
Language parsing to find important words
I'm looking for some input and theory on how to approach a lexical topic.

Let's say I have a collection of strings, which may just be one sentence or potentially multiple sentences.  I'd like to parse these strings to and rip out the most important words, perhaps with a score that denotes how likely the word is to be important.

Let's look at a few examples of what I mean.

Example #1:

"I really want a Keurig, but I can't afford one!"

This is a very basic example, just one sentence.  As a human, I can easily see that "Keurig" is the most important word here.  Also, "afford" is relatively important, though it's clearly not the primary point of the sentence.  The word "I" appears twice, but it is not important at all since it doesn't really tell us any information.  I might expect to see a hash of word/scores something like this:

```<code>"Keurig" => 0.9
"afford" => 0.4
"want"   => 0.2
"really" => 0.1
etc...
</code>```

Example #2:

"Just had one of the best swimming practices of my life.  Hopefully I can maintain my times come the competition.  If only I had remembered to take of my non-waterproof watch."

This example has multiple sentences, so there will be more important words throughout.  Without repeating the point exercise from example #1, I would probably expect to see two or three really important words come out of this: "swimming" (or "swimming practice"), "competition", & "watch" (or "waterproof watch" or "non-waterproof watch" depending on how the hyphen is handled).

Given a couple examples like this, how would you go about doing something similar?  Are there any existing (open source) libraries or algorithms in programming that already do this?

答:
There are definitely people thinking about the problem you describe. João Ventura and Joaquim Ferreira da Silva's Ranking and Extraction of Relevant Single Words in Text (pdf) is a nice introduction to existing ranking techniques as well as suggestions for improvement. All techniques they describe rely on a corpus (lots of text) versus one or two lines of text. Your corpus would have to be the collection of all samples or possibly many corpora of collected samples from specific sources. Keep in mind that single word (unigram) relevance is very much an unsolved problem. As the paper describes:

"...using purely statistical methods, this kind of classification
  isn’t always straightforward or even exact because, although the
  notion of relevance is a concept easy to understand, normally there's
  no consensus about the frontier that separates relevance from
  non-relevance. For instance, words like "Republic" or "London" have
  significative relevance and words like "or" and "since" have no
  relevance at all, but what about words like "read", "terminate" and
  "next"? These kind of words are problematic because usually there’s no
  consensus about their semantic value."

There are many open source natural language processing toolkits. (Be careful. Some tools are free for research but require a commercial license for commercial use.) They'll make your life easier regardless of the approach you choose.

I'm most familiar with the Natural Language Toolkit (NLTK). It's easy to use, well-documented, and is featured in the book, Natural Language Processing with Python (freely available online). As a simple example of what NLTK might do for you, imagine using its part-of-speech tagger. With each word's part-of-speech identified, you might consider proper nouns very important and adjectives less so. Verbs might be important and adverbs less so. It's by no means a state-of-the-art ranking, but you get useful information with little effort. When you're ready to move on to more sophisticated analysis, NLTK's built-in ability to tokenize, tag, chunk, and classify will let you focus on the other details of your solution.


答:
One approach that will yield stable code is to use a state machine. Then it is best to differentiate:

events

processes/tasks in progress

state of your program (i.e. idle, running a task, shutting down)

Here is a very simple, informal example (in pseudo-code):

```<code>enum States = {idle, runningTask, poweringDown, stopped}
enum events = {button1, button2, powerDown, stop}

currentState = States.idle;
currentTask = nil;

// simple state engine. make it a critical section for thread safety
synchronized processEvent(event) {
  switch(currentState) {
    case States.runningTask:
       currentTask.stop();
       currentState = nil;
       currentTask = nil;
       break;
    default:
   }

  switch(event) {
    case events.button1:
         if(currentState != States.idle) break;
         currentTask = task1.start();
         currentState = States.runningTask;
         break;
    case events.button2:
         if(currentState != States.idle) break;
         currentTask = task2.start();
         currentState = States.runningTask;
         break;
    case events.powerDown:
         if(currentState != States.idle) break;
         currentTask = powerdown.start();
         currentState = States.poweringDown;
         break;
    case events.stop:
         if(!powerdown.finished())
           exception("stop received before power down");
         currentTask = nil;
         currentState = stopped;
         break;
    default:
         exception("event unknown");
  }
}

// onButton1Pressed will call processEvent(events.button1)
// onButton2Pressed will call processEvent(events.button2)

// task1, task2, powerdown are assumed to implement some form of thread protocol,
//i.e. start() returns an object referencing the new thread, stop() kills the thread
</code>```

Title: design for interruptable operations

Body:
I couldn't find a better topic but here it is;

1) When user clicks a button, code starts t work,

2) When another button is clicked, it would stop doing whatever it does and start to run the second button's code,

3) Or with not user interaction, an electrical power down detected from a connected device, so our software would cancel the current event and start doing the power down procedure.

How is this design mostly applied to code? I mean "stop what you are doing" part?

If you would say events, event handlers etc. how do you bind a condition to the event? and how do you tell the program without using laddered if's to end it's process?

```<code>method1();
if (powerdown) return;
method2();
if (powerdown) return;
</code>```

etc.

Body:
One approach that will yield stable code is to use a state machine. Then it is best to differentiate:

events

processes/tasks in progress

state of your program (i.e. idle, running a task, shutting down)

Here is a very simple, informal example (in pseudo-code):

enum States = {idle, runningTask, poweringDown, stopped}
enum events = {button1, button2, powerDown, stop}

currentState = States.idle;
currentTask = nil;

// simple state engine. make it a critical section for thread safety
synchronized processEvent(event) {
  switch(currentState) {
    case States.runningTask:
       currentTask.stop();
       currentState = nil;
       currentTask = nil;
       break;
    default:
   }

  switch(event) {
    case events.button1:
         if(currentState != States.idle) break;
         currentTask = task1.start();
         currentState = States.runningTask;
         break;
    case events.button2:
         if(currentState != States.idle) break;
         currentTask = task2.start();
         currentState = States.runningTask;
         break;
    case events.powerDown:
         if(currentState != States.idle) break;
         currentTask = powerdown.start();
         currentState = States.poweringDown;
         break;
    case events.stop:
         if(!powerdown.finished())
           exception("stop received before power down");
         currentTask = nil;
         currentState = stopped;
         break;
    default:
         exception("event unknown");
  }
}

// onButton1Pressed will call processEvent(events.button1)
// onButton2Pressed will call processEvent(events.button2)

// task1, task2, powerdown are assumed to implement some form of thread protocol,
//i.e. start() returns an object referencing the new thread, stop() kills the thread


问:
What is the difference between _Procedural Generation_ and _Random Generation_?
Today, I got into an argument about the term "procedural generation".

My point was that its different from "classic" random generation in that procedural generation is based on a more mathematical, fractal-based, algorithm leading to a more "realistic" distribution and the usual randomness of most languages are based on a pseudo-random-number generator, leading to an "unrealistic", in a way, ugly, distribution. This discussion was made with a heightmap in mind.

The discussion left me somehow unconvinced about my own arguments though, so, is there more to it? Or am I the one who is, in fact, simply wrong?

答:
The main difference between procedural generation and pseudo-random generation is that numbers generated by a procedural generation algorithm (such as a fractal) are supposed to have some preset relations whereas pseudo-random numbers are supposed to simulate truly random processes.

Note -- this answer is based on Wikipedia's definition of procedural generation


问:
What do you optimize for?
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.

答: Since I do installations on multiple types of systems, everything from IBM mainframe to PCs, I first optimize for compatibility, then size, then speed.</p>

Title: What do you optimize for?


问:
Does low latency code sometimes have to be "ugly"?
(This is mainly aimed at those who have specific knowledge of low latency systems, to avoid people just answering with unsubstantiated opinions).

Do you feel there is a trade-off between writing "nice" object orientated code and writing very fast low latency code? For instance, avoiding virtual functions in C++/the overhead of polymorphism etc- re-writing code which looks nasty, but is very fast etc?

It stands to reason- who cares if it looks ugly (so long as its maintainable)- if you need speed, you need speed?

I would be interested to hear from people who have worked in such areas.

答:
Some of the studies I have seen extracts of indicate that clean easy to read code is often faster than more complex hard to read code.  In part, this is due to the way optimizers are designed.  They tend to be much better at optimizing a variable into a register, than doing the same with an intermediate result of a calculation.  Long sequences of assignments using a single operator leading to the final result may be optimized better than a long complicated equation.  Newer optimizers may have reduced the difference between clean and complicated code, but I doubt they have eliminated it.

Other optimizations like loop unrolling can be added in a clean fashion when required.

Any optimization added to improve performance should be accompanied by an appropriate comment.  This should include a statement that it was added as an optimization, preferably with measures of performance before and after.

I have found the 80/20 rule applies to the code I have optimized.  As a rule of thumb I don't optimize anything that isn't taking at least 80% of the time.   I then aim for (and usually achieve) a 10 fold performance increase.  This improves performance about 4 fold.  Most optimizations I have implemented haven't made the code significantly less "beautiful".  Your mileage may vary.


答:
If by ugly, you mean difficult to read/understand at the level where other developers will be re-using it or be needing to understand it, then I would say, elegant, easy-to-read code will almost always ultimately net you a performance gain in the long run in an app that you have to maintain.

Otherwise, sometimes there's enough of a performance win to make it worth putting ugly in a beautiful box with a killer interface on it but in my experience, this is a pretty rare dilemma.

Think about basic work avoidance as you go. Save the arcane tricks for when a performance problem actually presents itself. And if you do have to write something that somebody could only understand through familiarity with the specific optimization, do what you can to at least make the ugly easy to understand from a re-use of your code point of view. Code that performs miserably rarely ever does so because the developers were thinking overly hard about what the next guy was going to inherit, but if frequent changes are the only constant of an app (most web apps in my experience), rigid/inflexible code that's difficult to modify is practically begging for panicked messes to start popping up all over your code base. Clean and lean is better for performance in the long run.

Title: Does low latency code sometimes have to be "ugly"?

Body:
(This is mainly aimed at those who have specific knowledge of low latency systems, to avoid people just answering with unsubstantiated opinions).

Do you feel there is a trade-off between writing "nice" object orientated code and writing very fast low latency code? For instance, avoiding virtual functions in C++/the overhead of polymorphism etc- re-writing code which looks nasty, but is very fast etc?

It stands to reason- who cares if it looks ugly (so long as its maintainable)- if you need speed, you need speed?

I would be interested to hear from people who have worked in such areas.


答:
If you are targeting multithreaded scenario, you can use Tasks (.NET 4.0), or BackgroundWorker(.NET 2.0) that has support for cooperative cancellation.

Of course it requires some handling in the application logic also. This handling is limited to checking cancellation flag, and do cleanup (and return) in case of cancellation.

Supporting cancellation (without signals from other threads like Tasks, BackgroundWorker), is limited to handling error conditions, and doing cleanup/interrupt.

Title: design for interruptable operations


问:
Decrementing/Incrementing loop variable inside for loop. Is this code smell?
I have to read lines from a text file in sequential order. The file is a custom text format that contains sections. If some sections are out of order, I would like to look for the starting of the next valid section and continue processing.

Currently, I have some code that looks like this:

```<code>for (int currentLineIndex=0; currentLineIndex < lines.Count; currentLineIndex++ )
{
    //Process section here
    if( out_of_order_condition )
    {
        currentLineIndex--;//Stay on the same line in the next iteration because this line may be the start of a valid section.
       continue;
    }
}
</code>```

Is this code smell?

UPDATE: I didn't mention this earlier, but the root cause of this kind of code was a complicated switch-case (typical when you're parsing).

I got rid of the incrementing/decrementing variable by using the "goto case" statement.

The structure now looks like this:

```<code>switch(state)
{
   case State.BOF:
       {
           //Process BOF case
       }
   case State.SeenHeader:
       {
           if( out_of_order_condition )
           {
               state = State.BOF;    //Reset the state to some respectable one

               //currentLineIndex--; Removed
               //continue;           Removed

               goto case State.BOF;//Handle this in this iteration itself.
           }
       }
}
</code>```

答: It depends. To be on safer side on multi threaded scenario, use Interlocked.* API rather than using plain operators.</p>


问:
Adding Methods In Addition to an Interface
Let's say I have ThingImpl and IThing. The former is an implementation of the latter, which is an interface.

IThing has 1 method: do(arg1)

Is it considered a hack/bad practice to add a method in addition to do()?

Example: do(arg1, arg2)

答: Assuming that do is still an accurate name (and consistent with the other do method), I don't see any problem with doing this. In fact, it's a pretty common pattern.


答: As Oleksi mentioned, it is a common pattern. But make sure it is not public. If you want to make it public, better add to Interface itself.</p>

Title: Adding Methods In Addition to an Interface

Body:
Let's say I have ThingImpl and IThing. The former is an implementation of the latter, which is an interface.

IThing has 1 method: do(arg1)

Is it considered a hack/bad practice to add a method in addition to do()?

Example: do(arg1, arg2)


问:
How many types of programming languages are there?
Basically, I want to learn lots of programming languages to become a great programmer.  I know only a handful to depth and I was hoping someone could elaborate on how many classes or types of programming languages there are.  Like how you would lump them together if you had to learn them in groups.

Coming from a Java background, I'm familiar with static typing, but I know that in addition to dynamic typing there has to be such variety in available languages that I would love to see a categorical breakdown if possible.

答: I have to add that there are programming languages for specific applications. The one that comes to mind is APT (Automatic Programmed Tool) a language used in manufacturing for machine tools.</p>


答:
I think you may not be fully understanding what the purpose is behind programming to Interfaces. The reason to do it is so that any client code can get an object of type IThing and know what to do with it. So there would be no way for the overloaded method to ever be called by a client whose entire knowledge of the ThingImpl is that it is an IThing.

That said, I frequently consider my Application as a system similar to ordering something from Amazon.com. I order something and an IThing is made in the Factory. The wiring code in the application is quite happy with an IThing, as the UPS truck is with a box. However, when the box get to its destination, I care again that what's in my box is exactly what I ordered (so I'll check the inventory to make sure the content of the box is specifically what I'm expecting). More literally, the endpoint code will check the implementation type of the IThing before attempting to use it.

It sounds like your code actually is the Factory. In cases like this, I'll actually just create two Factories, one that knows how to set the parameter to true, and the other which knows how to set it to false. The Factories will be stored in some sort of hash and called up based on the specifics of whatever I'm creating (for example, I might have a registry of Factories that create Question data objects based on information I get from an XML file, and I'll pull a particular Factory out of the hash based on the question type).


问:
Is Agile the new micromanagement?
This question has been cooking in my head for a while so I wanted to ask those who are following agile/scrum practices in their development environments.

My company has finally ventured into incorporating agile practices and has started out with a team of four developers in an agile group on a trial basis. It has been four months with three iterations, and they continue to do it without going fully agile for the rest of us. This is due to the fact that middle management is entrusted to meet business requirements with quite a bit of ad hoc requests from upper management.

Recently, I talked to the developers who are part of this initiative; they tell me that it's not fun. They are not allowed to talk to other developers.  Their Scrum master enforces this restriction. And they are not allowed to take any non-business-related phone calls in the work area. For example, if I want to talk to my friend, who is in the agile team, just for kicks -- I am not allowed without the approval of the Scrum master; who is sitting right next to the agile team.

The idea of all this (or the agile, in general) is to provide a complete vacuum for agile developers from any interruptions, and to have them put in good 6+ productive hours. Well, guys, I am no agile guru but what I have read Yahoo agile rollout document and similar for other organizations, it gives me a feeling that agile is not cheap. It require resources and budget to instill agile into the teams and correct issue as they arrive to put them back on track.

For starters, it requires training for developers and coaching for managers and etc, etc... The current Scrum master was a manager who took a couple days agile training class paid by the management is now leading this agile team. I have also heard in the meeting that agile manifesto doesn't dictate that agile is not set in stone, and is customized differently for each company. Well, it all sounds good and reasonable.

In conclusion, I always thought the agile was supposed to bring harmony in the development teams which results in happy developers. However, I am getting the very opposite feeling when talking to the developers in the agile team. They are unhappy that they cannot talk about anything but work, sitting quietly all day just working, and they feel it's just another way for management to make them work more.

Tell me please, if this is one of the examples of good practices used for the purpose of selfish advantage for more dollars? Or maybe it's just us, the developers like me and this agile team, which feels that they don't like to work in an environment where they only breathe work while they're at work.

It's a company in the healthcare domain that has offices across the US. It definitely feels like a cowboy style agile, which makes me really not want to go for agile at all, especially at my current company.

All of it has to do with the management being completely cheap. Cutting out expensive coffee for a cheaper version, emphasis on savings and being productive while staying as lean as possible.

My feeling is that someone in the management behind closed doors threw out this idea: agile makes you produce more, so we can show our bosses we're producing more with the same headcount. Or, maybe, it will allow us to reduce headcount if that's the case.

They are having their 5 min daily meeting. But not allowed to chat or talk with someone outside of their team. All focus is on work.

答:
Agile should be the new self-management.  If agile is practiced correctly, many of the decisions are made by a customer and developer working a reasonably scoped user story that is added to the backlog as tasks are identified.

The daily scrum is about communication, not management.  There will be some discussions about priority and load balancing, but the person managed at the scrum is hopefully the scrum master.  AS a developer, I attend, say what I did, what I am going to do, and what help I need.  Then the scrum master should roll into action clearing impediments to my progress.

Agile teams must not feel like day to day work is managed hierarchically.  If decisions are made from afar by someone at the top of a hierarchical organization, it is time for the decentralization of decision making!  For some people and some organizations, this may be a bridge too far.  If the following is not true of your organization:

Live the Agile Manifesto

"We are uncovering better ways of developing software by doing it and
  helping others do it."

Avoid "Meet the new boss, Same as the old boss."  Originate Agile from within the team as much as possible.  Sometimes this happens by picking a coalition of the willing to be on a trial project using Agile.  If you can form your Agile team from volunteers or invited members who have a track record for good teamwork, they can work it out.  Use a small team on a short project, maybe for an in-house or highly accessible customer.

Embrace the change. Perhaps you can take some training, but maybe your budget is tight and the money just isn't there.  Other opportunities can provide improvement as well.  Do some reading, have members of the team learn what they can about Agile and teach each other.  You may be able to find new or existing staff qualified to model and lead in Agile adoption.

OwnerDisplayName: Smith James

Title: Is Agile the new micromanagement?


问:
Is there any reason not to go directly from client-side Javascript to a database?

Possible Duplicate:

  Writing Web “server less” applications

So, let's say I'm going to build a Stack Exchange clone and I decide to use something like CouchDB as my backend store. If I use their built-in authentication and database-level authorization, is there any reason not to allow the client-side Javascript to write directly to the publicly available CouchDB server? Since this is basically a CRUD application and the business logic consists of "Only the author can edit their post" I don't see much of a need to have a layer between the client-side stuff and the database. I would simply use validation on the CouchDB side to make sure someone isn't putting in garbage data and make sure that permissions are set properly so that users can only read their own _user data. The rendering would be done client-side by something like AngularJS. In essence you could just have a CouchDB server and a bunch of "static" pages and you're good to go. You wouldn't need any kind of server-side processing, just something that could serve up the HTML pages.

Opening my database up to the world seems wrong, but in this scenario I can't think of why as long as permissions are set properly. It goes against my instinct as a web developer, but I can't think of a good reason. So, why is this a bad idea?

EDIT: Looks like there is a similar discussion here: Writing Web "server less" applications

EDIT: Awesome discussion so far, and I appreciate everyone's feedback! I feel like I should add a few generic assumptions instead of calling out CouchDB and AngularJS specifically. So let's assume that:

The database can authenticate users directly from its hidden store

All database communication would happen over SSL

Data validation can (but maybe shouldn't?) be handled by the database

The only authorization we care about other than admin functions is someone only being allowed to edit their own post

We're perfectly fine with everyone being able to read all data (EXCEPT user records which may contain password hashes)

Administrative functions would be restricted by database authorization

No one can add themselves to an administrator role

The database is relatively easy to scale

There is little to no true business logic; this is a basic CRUD app

答:
First of all thanks for the OUT OF THE BOX question.... :)

But what i would suggest is; Always try to maintain a segregation between your 3 layers. which are Presentation/Business and Database or DAO because that will be the best practice in those kinds of requirements and setups where there will be lots of changes every day.

In simple worlds your Presentation layer should not know about Database layer i.e. Format of some date type fields might be different from presentation layer and database layer so that user can have a freedom to select suitable format of the date as per his/her needs.

And Business Logic must act like a coupling between presentation layer and database/Dao layer like casting of the fields, some business validations, etc should be handled on Business Layer rather than in Javascript section as per your question.

This segregation will provide you great ease and comport during complex scenarios, functionality-es and even complex validations.
The best advantage is: you can have different technologies to implement these layers and can be changed as per the business needs or scope.

Thanks


问:
Writing Web "server less" applications

TL;DR

What are the prospects of writing applications which are completely based on a REST database server (CouchDB) and web applications which directly access the DB instead of having a web server in between?

I recently started looking up some NoSQL databases. MongoDB seems to be a popular choices. I also liked the project.

But I personally liked the REST interface of CouchDB. So what I wanted to know is if there was the possibility of applications (maybe cached apps in web browser, a chrome extension etc.) which could just just query the database directly with no requirement of a webserver in between. All the computational logic would reside in the client application and the database will do what it does, CRUD. Since mostly (I don't know which doesn't) client frameworks support REST queries, it could be a good way of writing applications well optimized for the respective framework. These applications though won't be doing complicated computation, but still provide enough functionality which could replace lots of conventional applications.

Are there existing resources and projects which would help me move towards writing such applications and also the scope and moving towards developing in this way?

Are there any technical/security issues with this?

This post will help me decide to look into project like CouchDB (and maybe Dive into Erlang later) or stay with the conventional frameworks (like Django) and SQL databases.

Update

A specific point of such apps I had in mind is creation of offline applications just by replicating CouchDB data on the client.

答:
Even if you have a server layer to validate user read/write access to data, you would still risk someone manipulating your client side code in order to submit invalid data.

Any business constraint you may want to ensure should be validated server side.
For example:

dates within valid ranges

valid names

block update to objects in a given state (like to avoid placing orders for items out of stock)

and any other business constraint you can think of.

All of these could be easily bypassed if you just have write permissions and all of your logic is client side.

Title: Writing Web "server less" applications


问:
Is it a bad idea to stray from CSS selector syntax in a JavaScript selector engine?
I'm designing a JavaScript selector engine, and I'm currently focused on parsing the selector string. Specifically, combinators.

The CSS3 combinators I know of are:

> (children)

space (descendants)

+ (next sibling)

~ (all next siblings)

Which is fine for how CSS works (how style rules are applied). However, I'm now realizing (now that I'm examining this paradigm more closely) that this seems a bit limiting in a JavaScript setting.

Below I've created an alternative list of combinators. What I would like to know is:

Do any of the current selector engines stray from standard CSS selection methods? (I'm familiar with Sizzle and Sly, but none of the others)

Do you see any reason why any of the combinators I've listed wouldn't work well?

Do you think having more selector string options (more combinators, more filters, etc) is beneficial or are just a waste/confusing/dumb/etc?

Thanks all in advance for your thoughts!

> (children)

>> (descendants) (also, space would still work)

+ (next sibling)

++ (all next siblings) (also, tilde would still work)

- (previous sibling)

-- (all previous siblings)

* (previous and next siblings)

** (all siblings)

^ (parent)

Example 1: div ^ span - get all spans with a div child

Example 2: div ** span - get all span siblings of div

Example 3: .lastListItem -- li - all li previous to the li with class .lastListItem

Example 4: #thing ^ div ** .error - all items with class .error that are siblings of #thing's parent (assuming #thing's parent is a div)

p.s. Oh, and I also thought of having a placeholder character that could stand in for any simple selector. So, Example 4 might look like this (with an underscore as a placeholder):

Example 4 alt: #thing ^ _ ** .error - all items with class ".error" that are siblings of #thing's parent (no matter what kind of element #thing's parent is)

答:
Advantages of CSS selectors:

Everybody knows them already. They serve 99.95% of use-case scenarios and xpath selectors fill in where they don't.

They're perfectly performant in most supported browsers nowadays. Even IE8 has a native querySelectorAll method (but still no getElementsByClassName method oddly enough). querySelectorAll actually uses the CSS engine in most cases so perf can be a little surprising, but it's still going to be tricky to beat a native method with string examination followed by logic.

It's okay to reinvent the wheel. I encourage such behavior and !@#$ anybody who says otherwise. Unless I'm paying you and it's not Friday, but that Friday thing and paying you is pure fantasy on my part.

But if you're asking me if I'm going to use your selector engine enhancements, I'm probably not. Between knowing the core DOM API, jQuery and now querySelectorAll, I haven't run into an element or elements I couldn't grab without a brief one-liner in a very long time. Most of your examples are suggesting a need for code that relies overly much on patterns of HTML structure which to me is a recipe for brittle code that's difficult to read or simply requires one more method call in the core stuff or jQuery which is a lot less effort and more legible than trying to remember selectors that aren't actually CSS or X-Path.


问:
What is the difference between development and R&D?
I was asked by a colleague to explain clearly the difference between ordinary development and research and development (R&D) and was unable to do it. After reading Wikipedia, I still don't have the precise answer.

According to Wikipedia (slightly modified):

There are two primary models:

In one model, the primary function is to develop new products;

in the other model, the primary function is to discover and create new knowledge about scientific and technological topics for the purpose of uncovering and enabling development of valuable new products, processes, and services.

The first model is confusing. Does it mean that development (not R&D) consists exclusively in adding new features to a product, solving bugs and doing maintenance? What if something which was previously developed as a new feature becomes a separate product?

The second model is less confusing, but still, how to qualify whether something is new knowledge or existent knowledge which is just rediscovered?

Later, Wikipedia adds that ordinary development is different from R&D because of its:

nearly immediate profit or immediate improvement.

It's still not clear enough. How to qualify "nearly immediate profit"? What if a task has an immediate profit but requires heavy research? Or if it is basic but has uncertain profit, like the enforcement of a common style over the codebase?

For example, does it belong to development or R&D to:

Develop an engine which abstracts the access to the database, simplifying and shortening enormously the code of other applications (existent or ones which will be written in future) which should access to the database?

Establish a new service-oriented architecture for the entire organization of company resources, in order to move from a bunch of separate and autonomous applications to a set of well-organized, interconnected web services, like what is used by Amazon?

Design a new communication protocol to allow faster replication of data between two data centers of the company?

Conceive a new type of software testing while working on a specific product, knowing that this type of testing will improve/simplify the testing process?

Prove that Functional programming is more appropriate than OOP for a specific application, based on evidence, logic and previous experience?

Enhance the existent application by adding gestures on tactile screens, after doing studies and testing that shows that those gestures improve the productivity of the users by a ratio of at least 1.4 for a precise set of tasks?

Find a way to strongly enhance the Power usage effectiveness (PUE) of a data center?

Create a Domain-Specific Language (DSL)?

In short, how could I determine whether I'm doing R&D while working on something?

答: R&D is experimenting with ideas that may never become a product. Where, Software Development is working on a product/service desired to become a product.</p>


问:
What mistakes do your users make, and how can you update your application to handle them?
In fact this question is about cautions to be taken to enhance quality user experience and reduce avoidable support calls.</p>

答:
I once got a customer support call because my app just disappeared.  Turned out they opened another app on top of it.

... I decided not to ensure that didn't happen again, since it was the users computer illiteracy that caused the problem, not the app.  Anything I could have done to fix it would have lead to a poor user experience for others.


答:
It Depends

If you are working on a real-time embedded video processing system then you optimize for processing speed.  If you are working on a word processor you optimize for development time.

However, in all cases your code must work and it must be maintainable.

Title: What do you optimize for?

Body:
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.


问:
Freelancing - Share the source code?

Possible Duplicate:

Hand over source code to customer

I have developed a couple of form based windows application in vb.net for a client and they all work well and he paid me through a freelance site. I have handed over the executable and the setup to the client and all was well. Now the client wants the source code for the application. Is there a general practice on sharing the source code with the client?

Please note - the client never mentioned he needs the source code and he is now asking for it after a week after the app was completed and he made the payment.

I don't mind sharing the source code, but I am not sure if I should. This probably means the client would not hire me again and the bigger question is the source code really his property?

This question may have been asked a few times, but I cannot still draw a conclusion on what is right.

update

To answer some of the questions:

The source code was not mentioned at all. There was no exclusive contract signed except for the usual agreement of the freelance site.

I am not sure if software development comes under work for hire and is it valid for users outside of the US?

The reason for not sharing the source code was this was a very small project and I got paid for a mere few hours. So if I have an option then definitely I would want to keep the source code to myself as that gives a possibility of the client coming back. The application works flawlessly and the code is solid. Also, the task that the client wanted to achieve was very challenging and I would not like other programmers (competitors) to know how I achieved it.

So unless I get the confirmation that the source code is purely the property of the client, I would not be willing to share it.

答: I'd argue that it depends, as others have said, on the contract in place primarily. Check that first. That will be the key determining factor. If it doesn't specifically state that all of the work, including IP and source code belongs to the client, then check the rules of your country/state. In Australia, for example, in a lot of fields, such as this, unless the IP is spe</p>

Title: Freelancing - Share the source code?


答:
I see two problems:

1. Tight Coupling: Change your DB option? Well, now you gotta change all your client-side code too. Trust me. We don't need more problems on the client-side.

2. TMI Security Issue: Reveals way too much about how stuff works. Auth might still be an obstacle but finding an exploit is a Hell of a lot easier when you know exactly what's happening on the server-side.

A very-very-thin middle-tier might be a better way to go.

Title: Is there any reason not to go directly from client-side Javascript to a database?

Body:
Possible Duplicate:

  Writing Web “server less” applications

So, let's say I'm going to build a Stack Exchange clone and I decide to use something like CouchDB as my backend store. If I use their built-in authentication and database-level authorization, is there any reason not to allow the client-side Javascript to write directly to the publicly available CouchDB server? Since this is basically a CRUD application and the business logic consists of "Only the author can edit their post" I don't see much of a need to have a layer between the client-side stuff and the database. I would simply use validation on the CouchDB side to make sure someone isn't putting in garbage data and make sure that permissions are set properly so that users can only read their own _user data. The rendering would be done client-side by something like AngularJS. In essence you could just have a CouchDB server and a bunch of "static" pages and you're good to go. You wouldn't need any kind of server-side processing, just something that could serve up the HTML pages.

Opening my database up to the world seems wrong, but in this scenario I can't think of why as long as permissions are set properly. It goes against my instinct as a web developer, but I can't think of a good reason. So, why is this a bad idea?

EDIT: Looks like there is a similar discussion here: Writing Web "server less" applications

EDIT: Awesome discussion so far, and I appreciate everyone's feedback! I feel like I should add a few generic assumptions instead of calling out CouchDB and AngularJS specifically. So let's assume that:

The database can authenticate users directly from its hidden store

All database communication would happen over SSL

Data validation can (but maybe shouldn't?) be handled by the database

The only authorization we care about other than admin functions is someone only being allowed to edit their own post

We're perfectly fine with everyone being able to read all data (EXCEPT user records which may contain password hashes)

Administrative functions would be restricted by database authorization

No one can add themselves to an administrator role

The database is relatively easy to scale

There is little to no true business logic; this is a basic CRUD app


问:
Question regarding code readability
I would like to know, is it considered a common practice to use constructions like  |=, &&, ||, != altogether in the single line of code?

E.g.

hasErrors |= vi2!=null && vi2.hasErrors() || vi.hasErrors();

What can be done to make the code more readable?

The programming language is Java, if it matters.

答:
Personally, I'd consider either

```<code>hasErrors = hasErrors || (vi2!=null && vi2.hasErrors()) || vi.hasErrors();
</code>```

or

```<code>hasErrors = ...;
hasErrors |= (vi2!=null && vi2.hasErrors());
hasErrors |= vi.hasErrors();
</code>```

more readable, i.e., I feel that it takes me slightly less time to read and understand the meaning.

Note, however, that the three options are not semantically equivalent: In Java, |= does not short-circuit. Thus, if hasErrors() is a costly operation and you do not need its side effects, the first of my options is probably the most efficient.

Title: Question regarding code readability

Body:
Personally, I'd consider either

hasErrors = hasErrors || (vi2!=null && vi2.hasErrors()) || vi.hasErrors();

or

hasErrors = ...;
hasErrors |= (vi2!=null && vi2.hasErrors());
hasErrors |= vi.hasErrors();

more readable, i.e., I feel that it takes me slightly less time to read and understand the meaning.

Note, however, that the three options are not semantically equivalent: In Java, |= does not short-circuit. Thus, if hasErrors() is a costly operation and you do not need its side effects, the first of my options is probably the most efficient.


问:
What will happen if I don't follow robots.txt while crawling?
I am new to web crawling and I am testing my crawlers. I have been doings tests on various sites for testing. I forgot about robots.txt file  during my tests.

I just want to know what will happen if I don't follow the robots.txt file and what is the safe way of doing the crawling?

答:
The Robot Exclusion Standard is purely advisory, it's completely up to you if you follow it or not, and if you aren't doing something nasty chances are that nothing will happen if you choose to ignore it.

That said, when I catch crawlers not respecting robot.txt in the various websites I support, I go out of my way to block them, regardless of whether they are troublesome or not. Even legit crawlers may bring a site to a halt with too many requests to resources that aren't designed to handle crawling, I'd strongly advise you to reconsider and adjust your crawler to fully respect robots.txt.


答:
There are no legal repercussions that I'm aware of. If a web master notices you crawling pages that they told you not to crawl, they might contact you and tell you to stop, or even block your IP address from visiting, but that's a rare occurrence. It's possible that one day new laws will be created that add legal sanctions, but I don't think this will become a very big factor. So far, the internet culture used to prefer the technical way of solving things with "rough consensus and running code" rather than asking lawmakers to step in. It would also questionable whether any law could work very well given the international nature of IP connections.

(In fact, my own country is in the process of creating new legislation specifically targeted at Google for re-publishing snippets of online news! The newspapers could easily bar google from spidering them via robots.txt, but that's not what they want - they want to be crawled, because that brings page hits and ad money, they just want Goggle to pay them royalties on top! So you see, sometimes even serious, money-grubbing businesses are more upset for not crawling them than for crawling them.)

Title: What will happen if I don't follow robots.txt while crawling?

Body:
I am new to web crawling and I am testing my crawlers. I have been doings tests on various sites for testing. I forgot about robots.txt file  during my tests.

I just want to know what will happen if I don't follow the robots.txt file and what is the safe way of doing the crawling?


问:
How to execute a Ruby file in Java, capable of calling functions from the Java program and receiving primitive-type results?
I do not fully understand what am I asking (lol!), well, in the sense of if it is even possible, that is. If it isn't, sorry.

Suppose I have a Java program. It has a Main and a JavaCalculator class. JavaCalculator has some basic functions like

```<code>public int sum(int a,int b) {
   return a + b
}
</code>```

Now suppose I have a ruby file. Called MyProgram.rb.

MyProgram.rb may contain anything you could expect from a ruby program. Let us assume it contains the following:

```<code>class RubyMain
  def initialize
    print "The sum of 5 with 3 is #{sum(5,3)}"
  end
  def sum(a,b)
    # <---------- Something will happen here
  end
end

rubyMain = RubyMain.new
</code>```

Good. Now then, you might already suspect what I want to do:

I want to run my Java program

I want it to execute the Ruby file MyProgram.rb

When the Ruby program executes, it will create an instance of JavaCalculator, execute the sum function it has, get the value, and then print it.

The ruby file has been executed successfully.

The Java program closes.

Note: The "create an instance of JavaCalculator" is not entirely necessary. I would be satisfied with just running a sum function from, say, the Main class.

My question: is such possible? Can I run a Java program which internally executes a Ruby file which is capable of commanding the Java program to do certain things and get results? In the above example, the Ruby file asks the Java program to do a sum for it and give the result.

This may sound ridiculous. I am new in this kind of thing (if it is possible, that is).

WHY AM I ASKING THIS?

I have a Java program, which is some kind of game engine. However, my target audience is a bunch of Ruby coders. I don't want to have them learn Java at all. So I figured that perhaps the Java program could simply offer the functionality (capacity to create windows, display sprites, play sounds...) and then, my audience can simply code with Ruby the logic, which basically justs asks my Java engine to do things like displaying sprites or playing sounds.

That's when I though about asking this.

答:
What you're probably really after is JRuby --> http://jruby.org/

JRuby is a fully featured, compliant Ruby implementation on the Java Virtual Machine.  According to some Rubyists, it also happens to be the fastest (assuming you're running on a Java 7 compatible VM). JRuby can call into Java libraries and take return values from those calls, in short you can have the best of both worlds.


答:
IMO you can introduce more variables ,

```
 hasVi2Errors = vi2!=null && vi2.hasErrors();
 hasViErrors = vi.hasErrors();
 hasErrors = hasErrors || hasVi2Errors || hasViErrors;
```

Advantage is following through is easy, as  in each condition all are ORs or all are ANDs. Also if in future you need to add more condition like vi!= NULL, you can change only one line, by keeping the solution still readable.

Title: Question regarding code readability

Body:
I would like to know, is it considered a common practice to use constructions like  |=, &&, ||, != altogether in the single line of code?

E.g.

hasErrors |= vi2!=null && vi2.hasErrors() || vi.hasErrors();

What can be done to make the code more readable?

The programming language is Java, if it matters.

Body:
IMO you can introduce more variables ,

 hasVi2Errors = vi2!=null && vi2.hasErrors();
 hasViErrors = vi.hasErrors();
 hasErrors = hasErrors || hasVi2Errors || hasViErrors;

Advantage is following through is easy, as  in each condition all are ORs or all are ANDs. Also if in future you need to add more condition like vi!= NULL, you can change only one line, by keeping the solution still readable.


答:
most sites don't have any repercussions

however there are some sites that have crawler traps, links hidden for the normal user but plainly visible for crawlers

these traps can IP block your crawler or do anything really to try and thwart the crawler


答:
If it is short expressions, it is okay to put a few statements like those in one line (or even break in the next lines).

However, I'd rather create a method for that purpose, e.g.

```<code>private boolean hasErrors() {
    return hasErrors || vi2!=null && vi2.hasErrors() || vi.hasErrors();
}
</code>```

Then a call would look like if(hasErrors()) {...}. It is easy to read and easy to spot where to change the code, if necessary. Furthermore, it is reusable and easily testable in unit-tests. (Especially the latter point is very charming to me.)

Title: Question regarding code readability

Body:
If it is short expressions, it is okay to put a few statements like those in one line (or even break in the next lines).

However, I'd rather create a method for that purpose, e.g.

private boolean hasErrors() {
    return hasErrors || vi2!=null && vi2.hasErrors() || vi.hasErrors();
}

Then a call would look like if(hasErrors()) {...}. It is easy to read and easy to spot where to change the code, if necessary. Furthermore, it is reusable and easily testable in unit-tests. (Especially the latter point is very charming to me.)


问:
Mary Poppendieck's Books on Lean Software Development: Which One Can You Recommend?
Has anyone read all three of Mary Poppendieck's books on Lean Software Development?  She and her husband Tom wrote:

in 2003: Lean Software Development

in 2006: Implementing Lean Software Development

in 2009: Leading Lean Software Development

Mary and Tom Poppendieck are highly regarded lean experts, so I should have probably read one of their books, but I haven't read any of them.

Which one should I start with?

答:
I read the first two, and I must say these are the most influencal book on the subject (agile) I've ever read. And I read almost everything that has been written on the subject.

Buy and read them!

Start with the first one.


问:
How does a binary delta update work?
Both Android and iOS seem to support their application having a binary delta update. But how does it work? I build a binary program, neither of the distribution sites have the source code - how does the update process know what is changed?</p>

答:
Just as you can create a patch for a text (source) file, you can create a patch for a binary file as well.

You are effectively just noting what changed between two files (that's called delta encoding).

For example, if the app contains many resources, then those don't usually change for smaller updates, and only the executable code itself needs to be transferred.

Title: How does a binary delta update work?


问:
When to use abstract classes instead of interfaces with extension methods in C#?
"Abstract class" and "interface" are similar concepts, with interface being the more abstract of the two. One differentiating factor is that abstract classes provide method implementations for derived classes when needed. In C#, however, this differentiating factor has been reduced by the recent introduction of extension methods, which enable implementations to be provided for interface methods. Another differentiating factor is that a class can inherit only one abstract class (i.e., there is no multiple inheritance), but it can implement multiple interfaces. This makes interfaces less restrictive and more flexible. So, in C#, when should we use abstract classes instead of interfaces with extension methods?

A notable example of the interface + extension method model is LINQ, where query functionality is provided for any type that implements IEnumerable via a multitude of extension methods.

答:
I think that in C# multiple inheritance is not supported and that's why concept of interface is introduced in C#.

In case of abstract classes, multiple inheritance is not supported either. So it is easy to decide on wether to use abstract classes or interfaces.


问:
Looking for the better way to combine deep architecture refactoring with feature based development

Problem statement:

Given:

TFS as Source Control

Heavy desktop client application with tons of legacy code with bad or
almost absent architecture design.

Clients constantly requiring new features with sound quality, fast

delivery and constantly complaining on user unfriendly UI.

Problem:

Application undoubtedly requires deep refactoring. This process inevitably makes application unstable and dedicated stabilization phase is needed.

We've tried:

Refactoring in master with periodical merges from master (MB) to feature branch (FB). (my mistake)
Result: Many unstable branches.

What we are advised:

Link to the article (pdf)

Create additional branch for refactoring (RB) periodically synchronizing it with MB via merge from MB to RB. After RB is stabilized we substitute master with RB and create new branch for further refactoring. This is the plan. But here I expect the real hell of merging MB to RB after merging any FB to MB.

The main advantage:  Stable master most of the time.

Are there any better alternatives to the procees?

答:
I had a similar situation in the past. What I did:

assess the current state of the project; in most situation the architecture (or lack of it) is the main problem => re-think it

usually there are working features, the problem being the high coupling between the various parts of the project; I assessed which are the working features and I reused them, but in my own architecture

talk to the customer; I don't know what your manager says, but I think it's important to talk to the customer and be frank; he needs to know you are working on the quality of his product. I made an agreement for a release plan:

in the phase of merging the 2 solutions (make the architecture + reuse features from old project) the only things that were released (new features) were made on the old product; however, new releases contained only important bug fixes. So very few releases were made on the old product. Hence the changed things were easily merged into the new solution.

the first new release (release of the new product) contained only what the old product contained (no new features); after stabilizing it (the stabilization did not take long) I worked with a single project

I think you cannot escape from a (reasonably short) period of sporadic releases. It's important that you can agree on this with your customer.


问:
Is there a formula for this?
TL/DR: Any way to work out if known numbers between a known start and ending figure should be positive or negative numbers?

I am developing an application in PHP which can import and read PDFs. The PDFs are financial ones such as bank statements with records of transactions in and out of a bank account. I only have PDFs to work with, no other formats such as CSV unfortunately.

I convert the PDF to HTML using pdftohtml and start parsing the data, the intended end result is an array of transactions. So far I have it working smoothly collecting dates, descriptions and balance. Converting the XML instead doesn't help.

There are other pieces of transcriptional data such as debit or credit amounts. In the PDF, the credit amount is in one column and the debit amount is in another column so it is quite clear in the PDF. However, when converted to HTML, the formatting is lost and therefor I don't know if the amount was a credit or debit amount.

So, my question is, given a starting balance and an ending balance and several known figures in between, is it possible for a programme to work out if those known figures in between are credit or debit amounts?

I imagine there could potentially be several combinations of those known values to reach the ending balance so I'd like to apply a formula to return the correct credit/debit sequence only if its the only possible solution. If there are several ways of adding/subtracting the known values to reach the end balance, I can ask the user to look at it manually but I'd like to keep this to a minimum if possible.

Possible to do, do you think? Thank you in advance for any help.

答:
I can't see how that would be possible. Consider this:

```<code>Starting balance $100
$10 credit
$5 debit
$5 debit
Closing balance $100
</code>```

And this:

```<code>Starting balance $100
$10 debit
$5 credit
$5 credit
Closing balance $100
</code>```

How could you distinguish between those two cases?

Title: Is there a formula for this?

Body:
I can't see how that would be possible. Consider this:

Starting balance $100
$10 credit
$5 debit
$5 debit
Closing balance $100

And this:

Starting balance $100
$10 debit
$5 credit
$5 credit
Closing balance $100

How could you distinguish between those two cases?


问:
Maintenance wise, is `else while` without intervening braces considered safe?
Is else while without intervening braces considered "safe" maintenance wise?

Writing if-else code without braces like below...

```<code>if (blah)
    foo();
else
    bar();
</code>```

...carries a risk because the lack of braces make it very easy to change the meaning of the code inadvertently.

However, is below also risky?

```<code>if (blah)
{
    ...
}
else while (!bloop())
{
    bar();
}
</code>```

Or is else while without intervening braces considered "safe"?

答:
Perhaps it is because I learnt my trade (way back when) using the Jackson Entity Structure Diagram method, but I subscribe to the view that the only correct unbraced term after an if or an else is a subsequent if (ie allowing an else if ladder)

Anything else (no pun intended) leaves potential for misunderstanding and/or maintenance issues. That is the central aspect of the OPs idea being "unsafe".

I'd also be very cagey about including the while() on the same line as the else - whether braced or not.  It doesn't read right to me... the lack of any extra indentation masks that it is the else clause. And lack of clarity makes for misunderstandings (see above).

So in the example I would strongly advise/recommend (and insist, in my team) on:

```<code>if ( blah )
{
    ...
}
else
{
    while ( !bloop() )
    {
        bar();
    }
}
</code>```

Of course, I would also expect to see suitable comments too.

-- Edit --

Recently Apple suffered from an SSL vulnerability, caused by a poor maintenance fix - that added a second line to an un-braced single line.  So let's put to bed the idea that unbraced single lines are OK?

Body:
Perhaps it is because I learnt my trade (way back when) using the Jackson Entity Structure Diagram method, but I subscribe to the view that the only correct unbraced term after an if or an else is a subsequent if (ie allowing an else if ladder)

Anything else (no pun intended) leaves potential for misunderstanding and/or maintenance issues. That is the central aspect of the OPs idea being "unsafe".

I'd also be very cagey about including the while() on the same line as the else - whether braced or not.  It doesn't read right to me... the lack of any extra indentation masks that it is the else clause. And lack of clarity makes for misunderstandings (see above).

So in the example I would strongly advise/recommend (and insist, in my team) on:

if ( blah )
{
    ...
}
else
{
    while ( !bloop() )
    {
        bar();
    }
}

Of course, I would also expect to see suitable comments too.

-- Edit --

Recently Apple suffered from an SSL vulnerability, caused by a poor maintenance fix - that added a second line to an un-braced single line.  So let's put to bed the idea that unbraced single lines are OK?


答: I have all three and I find them complimentary so it's hard to say which one. If I had to pick a single one though then I'd go for the most recent. It covers pretty much all of the material in the first two but goes into more detail in how to implement lean methodology in practice.</p>

Title: Mary Poppendieck's Books on Lean Software Development: Which One Can You Recommend?

Body:
Has anyone read all three of Mary Poppendieck's books on Lean Software Development?  She and her husband Tom wrote:

in 2003: Lean Software Development

in 2006: Implementing Lean Software Development

in 2009: Leading Lean Software Development

Mary and Tom Poppendieck are highly regarded lean experts, so I should have probably read one of their books, but I haven't read any of them.

Which one should I start with?


答:
In my experience this is common. As stated this should be agreed in advanced, and written in the contract. But he bought your programming time, and the product should be his\hers.

For future contracts: The source code is your insurance. So give out an executable, for testing and seeing that you have done what you where asked to. And just after the payment, you give out the code. That way the client sees that you have done the job, but s\he can't extend it in the future without paying you. (And all requirement change sooner or later)

Title: Freelancing - Share the source code?

Body:
Possible Duplicate:

Hand over source code to customer

I have developed a couple of form based windows application in vb.net for a client and they all work well and he paid me through a freelance site. I have handed over the executable and the setup to the client and all was well. Now the client wants the source code for the application. Is there a general practice on sharing the source code with the client?

Please note - the client never mentioned he needs the source code and he is now asking for it after a week after the app was completed and he made the payment.

I don't mind sharing the source code, but I am not sure if I should. This probably means the client would not hire me again and the bigger question is the source code really his property?

This question may have been asked a few times, but I cannot still draw a conclusion on what is right.

update

To answer some of the questions:

The source code was not mentioned at all. There was no exclusive contract signed except for the usual agreement of the freelance site.

I am not sure if software development comes under work for hire and is it valid for users outside of the US?

The reason for not sharing the source code was this was a very small project and I got paid for a mere few hours. So if I have an option then definitely I would want to keep the source code to myself as that gives a possibility of the client coming back. The application works flawlessly and the code is solid. Also, the task that the client wanted to achieve was very challenging and I would not like other programmers (competitors) to know how I achieved it.

So unless I get the confirmation that the source code is purely the property of the client, I would not be willing to share it.


答:
If there are only a few values between the starting and the ending figure, you could use a brute force algorithm (try out all the combinations of pluses and minuses). I doubt there's a much more efficient way of doing this, since it's not enough to just find one solution - you need to check if it's the only solution.
You could probably use some tricks to make the whole process a bit faster, but that still won't help you if you have a lot of numbers in between.

That solution, however, seems inelegant... Maybe you should concentrate on finding a way of preserving the debit/credit information when converting data from PDF to HTML. What do your output files look like? Isn't there a pattern (like "debit values are in odd positions and credit values are in even positions" or something similar)?

Title: Is there a formula for this?

Body:
TL/DR: Any way to work out if known numbers between a known start and ending figure should be positive or negative numbers?

I am developing an application in PHP which can import and read PDFs. The PDFs are financial ones such as bank statements with records of transactions in and out of a bank account. I only have PDFs to work with, no other formats such as CSV unfortunately.

I convert the PDF to HTML using pdftohtml and start parsing the data, the intended end result is an array of transactions. So far I have it working smoothly collecting dates, descriptions and balance. Converting the XML instead doesn't help.

There are other pieces of transcriptional data such as debit or credit amounts. In the PDF, the credit amount is in one column and the debit amount is in another column so it is quite clear in the PDF. However, when converted to HTML, the formatting is lost and therefor I don't know if the amount was a credit or debit amount.

So, my question is, given a starting balance and an ending balance and several known figures in between, is it possible for a programme to work out if those known figures in between are credit or debit amounts?

I imagine there could potentially be several combinations of those known values to reach the ending balance so I'd like to apply a formula to return the correct credit/debit sequence only if its the only possible solution. If there are several ways of adding/subtracting the known values to reach the end balance, I can ask the user to look at it manually but I'd like to keep this to a minimum if possible.

Possible to do, do you think? Thank you in advance for any help.


问:
What are Web runtime environments and programming languages
I've been looking into the details behind these two different categories:

Web runtime environments

Web application programming languages

I believe I have the correct information and have phrased it correctly but I am unsure. I have been searching for a while but only find snippets of information or what I can see as useless information (I could be wrong).

Here are my descriptions so far:

Web runtime environments -

A Run-time environment implements part of the core behaviour of any computer language and allows it to be modified via an API or embedded domain-specific language.
A web runtime environment is similar except it uses web based languages such as Java-script which utilises the core behaviour a computer language. Another example of a Run-time environment web language is JsLibs which is a standable JavaScript development runtime environment for using JavaScript as a general all round scripting language.
JavaScript is often used to create responsive interfaces which improve the user experience and provide dynamic functionality without having to wait for the server to react and direct to another page.

Web application programming languages -

A web application program language is something that mimics a traditional desktop application within a web page. For example, using PHP you can create forms and tables which use a database similar to that of Microsoft Excel.

Some of the other languages for web application programming are:

Ajax

Perl

Ruby

Here are some of the resources used:

http://en.wikipedia.org/wiki/Web_application_development

http://code.google.com/p/jslibs/

I would like some confirmation that the descriptions I have created are correct as I am still slightly unsure as to whether I have hit the nail on the head.

答:
At least your part about the programming language isn't very correct. While what you describe is one (of many) options, describing a web programming language as something "that mimics a traditional desktop application" is leaving out far too much (and the frontend part that makes the web page itself run is mostly done with JavaScript).

Most programming languages used for the Web where initially not even developed for this purpose (PHP maybe the only exception). Ajax isn't a programming language at all, Perl, Ruby and Python are scripting languages and used for many purposes, including traditional desktop applications.

Their purpose if used as programming languages for web app backends is to receive requests from web sites, process the parameters that came with that request and render a response or send files. Often as a web page with css, html, javascript, but also by providing data in form of other formats like json or XML

So things are quite a bit more complex here.


答:
It might be fine if it stays simple like that although personally I don't like it and my preference is to use braces even for the simplest if/else code blocks. It's just tidier for me.

However, where this gets messy is when you have nested if/else loops some with braces some without. A While loop in the middle of all that spaghetti! I've worked with code that bad and it's a nightmare to debug and to understand. This follows on from the first point it's fine when it stays simple and you're happy with it, but then other programmers come along and add things to it, probably an if else within the while loop. If it's written clean in the first place then there's less chance of this happening.

The point is to make stuff clear so that other programmers can see at a glance what's right and wrong. Write code so that the pattern looks right and doesn't jar.

The flip side of this is that maybe I could see some people claiming that in certain instances this reads well. If I've got the resource I need do this processing else while I'm waiting for something do this.  Even then to me there's still no difference in nesting the while loop inside the else block.

Title: Maintenance wise, is `else while` without intervening braces considered safe?

Body:
Is else while without intervening braces considered "safe" maintenance wise?

Writing if-else code without braces like below...

```<code>if (blah)
    foo();
else
    bar();
</code>```

...carries a risk because the lack of braces make it very easy to change the meaning of the code inadvertently.

However, is below also risky?

```<code>if (blah)
{
    ...
}
else while (!bloop())
{
    bar();
}
</code>```

Or is else while without intervening braces considered "safe"?


问:
Generating Deep Arrays: Shallow to Deep, Deep to Shallow or Bad idea?
I'm working on an array structure that will be used as the data source for a report template in a web app.

The data comes from relatively complex SQL queries that return one or many rows as one dimensional associative arrays. In the case of many, they are turned into two dimensional indexed array.

The data is complex and in some cases there is a lot of it.  To save trips to the database (which are extremely expensive in this scenario) I'm attempting to get all of the basic arrays  (1 and 2 dimension raw database data) and put them, conditionally, into a single, five level deep array.  Organizing the data in PHP seems like a better idea than by using where statements in the SQL.

Array Structure

```<code>    Array of years(
            year => array of types(
                            types => array of information(
                                                total => value,
                                                table => array of data(
                                                                index => db array
                                                                    )
                                                        )
                                )
                )
</code>```

My first question is, is this a bad idea.  Are arrays like this appropriate for this situation?

If this would work, how should I go about populating it?  My initial thought was shallow to deep, but the more I work on this, the more I realize that it'd be very difficult to abstract out the conditionals that determine where each item goes in the array.  So it seems that starting from the most deeply nested data may be the approach I should take.

If this is array abuse, what alternatives exist?

Edit

I went ahead with this approach, learning and changing things as I went.  But I ended up with a similar end array.  What I learned in regards to the shallow to deep conundrum was this.

I went into the process thinking of the outer arrays as the largest of a set of cups, containing multitudes of smaller cups which in turn contained another multitude of smaller cup until the last set which in my mind was water (this being the indexed array of database values).  Arrays are not cups...

The idea fell apart when I started legitimately hand drawing out the array structures and found that the base of these arrays, the water filled tiny cups I had envisioned, represented a heck of a lot more data than those big cups.  This lead me to see these deeply nested arrays as towers, with the indexed data representing a base of sorts, tapering up to the tip, which was the containing array.

From there, I figured out that the best way for me to process the data was to gather the bottom data, plug it into it's next layer and then go up the tower plugging each layer into it's next layer.

I'm not sure if I'm right, but I do feel like I understand arrays more now than I did before.

And I'm definitely still not sure if this is the best solution.

答:
How do you size your inner arrays? I guess you don't know in advance the size for each of them.

I see three possible solutions:

If the database is not changed often, but rather read, you can index your tables (internally or with Lucene). It will bring more performance.

Use a B-Tree, because it's also friendly with respect to hard disk "swapping" (I guess you don't want to keep everything in memory).

a combination of 1 and 2.


答:
That reminds me this code:

```<code>if ( ... ) try {
..
} catch (Exception e) {
..
} else {
...
}
</code>```

Every time you are combining two types of blocks, forgetting braces and not increasing indentation, you are creating code very difficult to understand and maintain.

Body:
That reminds me this code:

if ( ... ) try {
..
} catch (Exception e) {
..
} else {
...
}

Every time you are combining two types of blocks, forgetting braces and not increasing indentation, you are creating code very difficult to understand and maintain.


问:
What is the difference between a Program Manager and a Project Manager?
Is a Program Manager a person who manages mutiple projects (under a single program) which are in turn managed by Project Managers?

Or is a Program Manager a person as defined by Joel Spolsky here.

NOTE: I am not referring to this.

答:
The way I've seen it done ( may be fairly common in aerospace.. might be just my experience)

Program manager manages the program

A program has projects. (Often for specific customers)

So the program manager has to take a longer term view, guide things to be more strategic.
"We're going to need that later". "Can't cut that corner". "Have to ship today, project must dovetail with other project that hasn't been announced to rest of company yet"

The project manager worries about THIS project.

I've seen the Program manager as basically the Project manager's boss.

It REALLY helps if they don't fight.