答:
Since you asked why C# did it this way, it's best to ask the C# creators. Anders Hejlsberg, the lead architect for C#, answered why they chose not to go with virtual by default (as in Java) in an interview, pertinent snippets are below.

Keep in mind that Java has virtual by default with the final keyword to mark a method as non-virtual. Still two concepts to learn, but many folks do not know about the final keyword or don't use it proactively. C# forces one to use virtual and new/override to consciously make those decisions.

There are several reasons. One is performance. We can observe that as
people write code in Java, they forget to mark their methods final.
Therefore, those methods are virtual. Because they're virtual, they
don't perform as well. There's just performance overhead associated
with being a virtual method. That's one issue.

A more important issue is versioning. There are two schools of thought
about virtual methods. The academic school of thought says,
"Everything should be virtual, because I might want to override it
someday." The pragmatic school of thought, which comes from building
real applications that run in the real world, says, "We've got to be
real careful about what we make virtual."

When we make something virtual in a platform, we're making an awful
lot of promises about how it evolves in the future. For a non-virtual
method, we promise that when you call this method, x and y will
happen. When we publish a virtual method in an API, we not only
promise that when you call this method, x and y will happen. We also
promise that when you override this method, we will call it in this
particular sequence with regard to these other ones and the state will
be in this and that invariant.

Every time you say virtual in an API, you are creating a call back
hook. As an OS or API framework designer, you've got to be real
careful about that. You don't want users overriding and hooking at any
arbitrary point in an API, because you cannot necessarily make those
promises. And people may not fully understand the promises they are
making when they make something virtual.

The interview has more discussion about how developers think about class inheritance design, and how that led to their decision.

Now to the following question:

I'm not able to understand why in the world I'm going to add a method
in my DerivedClass with same name and same signature as BaseClass and
define a new behaviour but at the run-time polymorphism, the BaseClass
method will be invoked! (which is not overriding but logically it
should be).

This would be when a derived class wants to declare that it does not abide by the contract of the base class, but has a method with the same name. (For anyone who doesn't know the difference between new and override in C#, see this Microsoft Docs page).

A very practical scenario is this:

You created an API, which has a class called Vehicle.

I started using your API and derived Vehicle.

Your Vehicle class did not have any method PerformEngineCheck().

In my Car class, I add a method PerformEngineCheck().

You released a new version of your API and added a PerformEngineCheck().

I cannot rename my method because my clients are dependent on my API, and it would break them.

So when I recompile against your new API, C# warns me of this issue, e.g.

If the base PerformEngineCheck() was not virtual:

 app2.cs(15,17): warning CS0108: 'Car.PerformEngineCheck()' hides inherited member 'Vehicle.PerformEngineCheck()'.
 Use the new keyword if hiding was intended.
```
<p>And if the base <code>PerformEngineCheck()</code> was <code>virtual</code>:</p>
 <pre class="lang-none prettyprint-override"><code> app2.cs(15,17): warning CS0114: 'Car.PerformEngineCheck()' hides inherited member 'Vehicle.PerformEngineCheck()'.
 To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
</code>```

Now, I must explicitly make a decision whether my class is actually extending the base class' contract, or if it is a different contract but happens to be the same name.

By making it new, I do not break my clients if the functionality of the base method was different from the derived method. Any code that referenced Vehicle will not see Car.PerformEngineCheck() called, but code that had a reference to Car will continue to see the same functionality that I had offered in PerformEngineCheck().

A similar example is when another method in the base class might be calling PerformEngineCheck() (esp. in the newer version), how does one prevent it from calling the PerformEngineCheck() of the derived class? In Java, that decision would rest with the base class, but it does not know anything about the derived class. In C#, that decision rests both on the base class (via the virtual keyword), and on the derived class (via the new and override keywords).

Of course, the errors that the compiler throws also provide a useful tool for the programmers to not unexpectedly make errors (i.e. either override or provide new functionality without realizing so.)

Like Anders said, real world forces us into such issues which, if we were to start from scratch, we would never want to get into.

EDIT: Added an example of where new would have to be used for ensuring interface compatibility.

EDIT: While going through the comments, I also came across a write-up by Eric Lippert (then one of the members of C# design committee) on other example scenarios (mentioned by Brian).

PART 2: Based on updated question

But in case of C# if SpaceShip does not override the Vehicle class'
accelerate and use new then the logic of my code will be broken. Isn't
that a disadvantage?

Who decides whether SpaceShip is actually overriding the Vehicle.accelerate() or if it's different? It has to be the SpaceShip developer. So if SpaceShip developer decides that they are not keeping the contract of the base class, then your call to Vehicle.accelerate() should not go to SpaceShip.accelerate(), or should it? That is when they will mark it as new. However, if they decide that it does indeed keep the contract, then they will in fact mark it override. In either case, your code will behave correctly by calling the correct method based on the contract. How can your code decide whether SpaceShip.accelerate() is actually overriding Vehicle.accelerate() or if it is a name collision? (See my example above).

However, in the case of implicit inheritance, even if SpaceShip.accelerate() did not keep the contract of Vehicle.accelerate(), the method call would still go to SpaceShip.accelerate().

Body:
Since you asked why C# did it this way, it's best to ask the C# creators. Anders Hejlsberg, the lead architect for C#, answered why they chose not to go with virtual by default (as in Java) in an interview, pertinent snippets are below.

Keep in mind that Java has virtual by default with the final keyword to mark a method as non-virtual. Still two concepts to learn, but many folks do not know about the final keyword or don't use it proactively. C# forces one to use virtual and new/override to consciously make those decisions.

There are several reasons. One is performance. We can observe that as
people write code in Java, they forget to mark their methods final.
Therefore, those methods are virtual. Because they're virtual, they
don't perform as well. There's just performance overhead associated
with being a virtual method. That's one issue.

A more important issue is versioning. There are two schools of thought
about virtual methods. The academic school of thought says,
"Everything should be virtual, because I might want to override it
someday." The pragmatic school of thought, which comes from building
real applications that run in the real world, says, "We've got to be
real careful about what we make virtual."

When we make something virtual in a platform, we're making an awful
lot of promises about how it evolves in the future. For a non-virtual
method, we promise that when you call this method, x and y will
happen. When we publish a virtual method in an API, we not only
promise that when you call this method, x and y will happen. We also
promise that when you override this method, we will call it in this
particular sequence with regard to these other ones and the state will
be in this and that invariant.

Every time you say virtual in an API, you are creating a call back
hook. As an OS or API framework designer, you've got to be real
careful about that. You don't want users overriding and hooking at any
arbitrary point in an API, because you cannot necessarily make those
promises. And people may not fully understand the promises they are
making when they make something virtual.

The interview has more discussion about how developers think about class inheritance design, and how that led to their decision.

Now to the following question:

I'm not able to understand why in the world I'm going to add a method
in my DerivedClass with same name and same signature as BaseClass and
define a new behaviour but at the run-time polymorphism, the BaseClass
method will be invoked! (which is not overriding but logically it
should be).

This would be when a derived class wants to declare that it does not abide by the contract of the base class, but has a method with the same name. (For anyone who doesn't know the difference between new and override in C#, see this Microsoft Docs page).

A very practical scenario is this:

You created an API, which has a class called Vehicle.

I started using your API and derived Vehicle.

Your Vehicle class did not have any method PerformEngineCheck().

In my Car class, I add a method PerformEngineCheck().

You released a new version of your API and added a PerformEngineCheck().

I cannot rename my method because my clients are dependent on my API, and it would break them.

So when I recompile against your new API, C# warns me of this issue, e.g.

If the base PerformEngineCheck() was not virtual:

 app2.cs(15,17): warning CS0108: 'Car.PerformEngineCheck()' hides inherited member 'Vehicle.PerformEngineCheck()'.
 Use the new keyword if hiding was intended.

And if the base PerformEngineCheck() was virtual:

 app2.cs(15,17): warning CS0114: 'Car.PerformEngineCheck()' hides inherited member 'Vehicle.PerformEngineCheck()'.
 To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.

Now, I must explicitly make a decision whether my class is actually extending the base class' contract, or if it is a different contract but happens to be the same name.

By making it new, I do not break my clients if the functionality of the base method was different from the derived method. Any code that referenced Vehicle will not see Car.PerformEngineCheck() called, but code that had a reference to Car will continue to see the same functionality that I had offered in PerformEngineCheck().

A similar example is when another method in the base class might be calling PerformEngineCheck() (esp. in the newer version), how does one prevent it from calling the PerformEngineCheck() of the derived class? In Java, that decision would rest with the base class, but it does not know anything about the derived class. In C#, that decision rests both on the base class (via the virtual keyword), and on the derived class (via the new and override keywords).

Of course, the errors that the compiler throws also provide a useful tool for the programmers to not unexpectedly make errors (i.e. either override or provide new functionality without realizing so.)

Like Anders said, real world forces us into such issues which, if we were to start from scratch, we would never want to get into.

EDIT: Added an example of where new would have to be used for ensuring interface compatibility.

EDIT: While going through the comments, I also came across a write-up by Eric Lippert (then one of the members of C# design committee) on other example scenarios (mentioned by Brian).

PART 2: Based on updated question

But in case of C# if SpaceShip does not override the Vehicle class'
accelerate and use new then the logic of my code will be broken. Isn't
that a disadvantage?

Who decides whether SpaceShip is actually overriding the Vehicle.accelerate() or if it's different? It has to be the SpaceShip developer. So if SpaceShip developer decides that they are not keeping the contract of the base class, then your call to Vehicle.accelerate() should not go to SpaceShip.accelerate(), or should it? That is when they will mark it as new. However, if they decide that it does indeed keep the contract, then they will in fact mark it override. In either case, your code will behave correctly by calling the correct method based on the contract. How can your code decide whether SpaceShip.accelerate() is actually overriding Vehicle.accelerate() or if it is a name collision? (See my example above).

However, in the case of implicit inheritance, even if SpaceShip.accelerate() did not keep the contract of Vehicle.accelerate(), the method call would still go to SpaceShip.accelerate().


问:
Why are interfaces useful?
I have been studying and coding in C# for some time now. But still, I can't figure the usefulness of Interfaces. They bring too little to the table. Other than providing the signatures of function, they do nothing. If I can remember the names and signature of the functions which are needed to be implemented, there is no need for them. They are there just to make sure that the said functions(in the interface) are implemented in the inheriting class.

C# is a great language, but sometimes it gives you the feeling that first Microsoft creates the problem (not allowing multiple inheritance) and then provides the solution, which is rather a tedious one.

That's my understanding which is based on limited coding experience. What's your take on interfaces? How often you make uses of them and what makes you do so?

答:
Interfaces lend to plugin-style modularity by providing a mechanism for classes to understand (and subscribe to) certain kinds of messages that your system delivers.  I'll elaborate.

In your application, you decide that whenever a form is loaded or reloaded you want all of the things it hosts to be cleared.  You define an IClear interface which implements Clear.  Additionally, you decide that whenever the user hits the save button that the form should attempt to persist its state.  Thus, everything that abides by ISave receives a message to persist its state.  Of course, practically speaking, most interfaces handle several messages.

What sets interfaces apart is that common behavior can be achieved without inheritance.  The class that implement a given interface simply understands how to behave when issued a command (a command message) or how to respond when queried (a query message).  Essentially, the classes in your application understand the messages your application provides.  This makes it easier to construct a modular system into which things can be plugged.

In most languages there are mechanisms (like LINQ) for querying things that abide by an interface.  This will usually help you eliminate conditional logic because you won't have to tell dissimilar things (that are not necessary derived of the same inheritance chain) how to behave similarly (according to a particular message).  Instead, you gather everything that understands a certain message (abides by an interface) and publish the message.

For example, you could replace...

```<code>Me.PublishDate.Clear()
Me.Subject.Clear()
Me.Body.Clear()
</code>```

...with:

```<code>For Each ctl As IClear In Me.Controls.OfType(Of IClear)()
    ctl.Clear()
Next
</code>```

Which effectively sounds a lot like:

Hear ye, Hear ye!  Would everyone who understands clearing, please Clear now!

In this way, we can programmatically avoid telling each and every thing to clear itself.  And when clearable items are added in the future they simply respond without any additional code.

ContentLicense: CC BY-SA 3.0

Title: Why are interfaces useful?

Body:
Interfaces lend to plugin-style modularity by providing a mechanism for classes to understand (and subscribe to) certain kinds of messages that your system delivers.  I'll elaborate.

In your application, you decide that whenever a form is loaded or reloaded you want all of the things it hosts to be cleared.  You define an IClear interface which implements Clear.  Additionally, you decide that whenever the user hits the save button that the form should attempt to persist its state.  Thus, everything that abides by ISave receives a message to persist its state.  Of course, practically speaking, most interfaces handle several messages.

What sets interfaces apart is that common behavior can be achieved without inheritance.  The class that implement a given interface simply understands how to behave when issued a command (a command message) or how to respond when queried (a query message).  Essentially, the classes in your application understand the messages your application provides.  This makes it easier to construct a modular system into which things can be plugged.

In most languages there are mechanisms (like LINQ) for querying things that abide by an interface.  This will usually help you eliminate conditional logic because you won't have to tell dissimilar things (that are not necessary derived of the same inheritance chain) how to behave similarly (according to a particular message).  Instead, you gather everything that understands a certain message (abides by an interface) and publish the message.

For example, you could replace...

Me.PublishDate.Clear()
Me.Subject.Clear()
Me.Body.Clear()

...with:

For Each ctl As IClear In Me.Controls.OfType(Of IClear)()
    ctl.Clear()
Next

Which effectively sounds a lot like:

Hear ye, Hear ye!  Would everyone who understands clearing, please Clear now!

In this way, we can programmatically avoid telling each and every thing to clear itself.  And when clearable items are added in the future they simply respond without any additional code.


问:
How to avoid downcasting?
My question is about a special case of the super class Animal.

My Animal can moveForward() and eat().

Seal extends Animal.

Dog extends Animal.

And there's a special creature that also extends Animal called Human.

Human implements also a method speak() (not implemented by Animal).

In an implementation of an abstract method which accepts Animal I would like to use the speak() method. That seems not possible without doing a downcast. Jeremy Miller wrote in his article that a downcast smells.

What would be a solution to avoid downcasting in this situation?

答:
In an implementation of an abstract method which accepts Animals I would like to use the speak() method.

You have a few choices:

Use reflection to call speak if it exists.  Advantage: no dependency on Human.  Disadvantage: there is now have a hidden dependency on the name "speak".

Introduce a new interface Speaker and downcast to the interface.  This is more flexible than depending on a specific concrete type.  It has the disadvantage that you have to modify Human to implement Speaker.  This won't work if you can't modify Human

Downcast to Human.  This has the disadvantage that you will have to modify the code whenever you want another subclass to speak.  Ideally you want to extend applications by adding code without repeatedly going back and changing old code.

Title: How to avoid downcasting?


问:
Mental Models or Real-World-Metaphors for Functional Programming
Does anyone have a good mental model or metaphor for functional programming which references something in the real world?

Object Oriented programing intuitively makes sense to me. There are things that have properties and sometimes they also can do stuff or perform calculations on their properties (methods). (Ex: Car, Shape, Cat).

I bear functional programming no ill will whatsoever and I am not interested in a debate about the virtues of the two. I just need a metaphor or mental model to work with as I have with Object Oriented programming.

What are some good mental models or real world metaphors for programming in a functional paradigm? There is something about functions composed of functions processing functions which leaves one without a firm place to stand and cogitate.

答:
Sentences are more functional than object-oriented, assuming you break them down more or less like the following...

```<code>The brown cow is in the meadow across the deep river.
</code>```

So we need to find the head phrases and then the rest:

```<code>The cow (brown)
the meadow (across)
the river (deep)
</code>```

In one go:

```<code>sentence: The cow ((the meadow (the river (deep)) (across)) brown)
</code>```

Parse tree:

```<code>|                     sentence
|                      /
|                  The cow
|                 /       \
|            the meadow   brown
|            /         \
|      the river      across
|              \
|              deep
</code>```

Parsimony infects functional thinking;

Hats off to Gottlieb Frege 1890s, Alan Turing (entschiedungsprobleme) 1930s, Noam Chomsky (1960s).

Body:
Sentences are more functional than object-oriented, assuming you break them down more or less like the following...

The brown cow is in the meadow across the deep river.

So we need to find the head phrases and then the rest:

The cow (brown)
the meadow (across)
the river (deep)

In one go:

sentence: The cow ((the meadow (the river (deep)) (across)) brown)

Parse tree:

|                     sentence
|                      /
|                  The cow
|                 /       \
|            the meadow   brown
|            /         \
|      the river      across
|              \
|              deep

Parsimony infects functional thinking;

Hats off to Gottlieb Frege 1890s, Alan Turing (entschiedungsprobleme) 1930s, Noam Chomsky (1960s).


问:
Working with a large, messy object
I have been handed a very cluttered, "One Ring" object (one object to rule them all). The OR class has 40 fields. These fields map to 16 different objects (the OR has all the fields from the 16 objects concatenated together. Some of the fields are common to all objects, some are unique to individual objects [all of the 16 objects are descended from a common parent]). The OR points to a catch-all table in a denormalized SQL database. I've been asked to write an adapter for this that will take random instances of the 16 objects, map the fields from a given object to an instance of the OR, and send it on its way. Oy.

Changing the back end or the code is not an option (I tried).

As I'm sure is no surprise, this beast is a nasty thing to manage. I would love to hear some thoughts about ways to help make working with this a bit more manageable. I'm primarily concerned with code maintenance: comprehension and readability. I know whatever gets implemented will be far from perfect, because I'm basically trying to make garbage look pretty. That said, for now, I have to live with it, so I'm trying to make my side of the train wreck a little bit more livable.

答:
This is an example of a facade pattern, which may provide some starting points for your research.  I've also seen it called an anti-corruption layer.

Basically, you create your dream API, the one you would create if starting from scratch today, but implement it by making calls to the current horrible back end.  Then you can slowly move calling code to your new API, and when everything is moved, you can much more easily replace the back end.

This is sort of the rock climber's approach.  You get a safety in place before you make the next move.

Title: Working with a large, messy object


问:
Choosing a functional programming language
I have read a lot of threads about functional programming languages lately (almost in the past year, in fact). I would really like to pick one and learn it thoroughly.

Last [course] semester, I have been introduced to Scheme. I loved it. Loved the extreme simplicity of syntax, the homoiconicity principle, the macros (hygienic and non-hygienic), the n-arity of procedures, etc.

The problem with Scheme is it's an academic language. I don't think it is really used in production environments. I don't believe either that it is particularly good to have on our resume. So, I have been looking around for alternatives. There are many of them and they somehow all seem to have a similar level of popularity.

Some thoughts about some other functional languages I have considered yet:

Clojure: It sounds great because it can access the Java world, it is oriented towards scalability and concurrency, but isn't the Java world on an edge right now? I already know Java pretty well, but would it be wise to add even more energy on depending on the JVM?

Haskell: Looks like a very appreciated language, but from what I have read, it's also more of an academic language.

Lisp: It's been around since forever. It seems to have most of what I like from Scheme. It has a big community. For what I [think I] know, it is probably the most widely used functional programming language in industry(?).

F#: Didn't really consider it. I'm not a big fan of MS stuff. I don't have the money to pay for their softwares (I could have them free from university alliances, but I'm more inclined to go with community-driven solutions). Though... I guess it would be the best career-oriented choice.

Tonight, I'm leaning towards Lisp. One week ago, it was Haskell. Before that it was Clojure. In the past year, I was doing some Scheme for fun, not pushing it for the reason you know. Now I would like to get serious (about learning one, about doing real projects with it, about maybe eventually professionally working with it). My problem is I would need to learn them all in depth before being able to choose one.

答:
It looks like you've done your homework, so you probably already know this, but Scheme is a dialect of Lisp just like Common Lisp is. If you like a lot of things about Scheme, but don't like its academic nature, try Common Lisp. According to the TIOBE index, it's the 13th most popular language vs Scheme at position 26.

Few of the languages you've mentioned appear on the job descriptions I've seen recently, though that might just be my small sample set. I personally will be learning Haskell, even though I don't expect to use that language directly in my job. The concepts of functional programming are more valuable to me for future program designs than the direct marketability of the language itself.

ContentLicense: CC BY-SA 2.5


问:
How to get an image or rectangle to detect collision with another image
Can someone please explain to me how to detect collision with another image?  The tutorial I was watching explained how to detect if a collision occurs between two rectangles but I would like to use two images instead.  Please see the code below.

```<code>public void paintComponent(Graphics g){
//g.drawImage(yellowBall, xCoor, yCoor, this);
Rectangle r1 = new Rectangle((boardXSize/2), (boardYSize/2),50, 50);
Rectangle r2 = new Rectangle(200, (250),50, 50);
g.setColor(Color.red);
g.fillRect(r1.x, r1.y, r1.width, r1.height);
g.setColor(Color.blue);
g.fillRect(r2.x, r2.y, r2.width, r2.height);

if(r1.intersects(r2)){
        System.out.println("Collision Detected");
    }
repaint();

}
</code>```

How can I detect if r1 intersects yellowBall instead of r2?  Please keep responses at the beginner level but of course, any assistance is greatly appreciated.  Thanks!!

答:
When you use rectangles to detect collisions, it is assumed that the rectangle contains the object you're testing for. The more closely the rectangle encloses the object, the more accurate the collision detection is. Any part of the object outside the rectangle doesn't get tested for collision.

So your real question may be, "how do i draw a rectangle around my circle?"

In your case, the ball presumably starts at (xCoor,yCoor) and extends out from there according to the size of the image.


答:
To continue the approach begun by tylerl, this is typically done in two stages.

The first is to create a "bounding box" that surrounds each object, and test whether any two boxes intersect. Testing if boxes intersect is quick.

The second stage is employed when we know the boxes intersect. If they don't intersect, then we've finished. To test whether the two objects intersect is in general harder, but you have chosen one of the "not too hard" cases.

If you had two circles, you would just calculate the distance between their centers. Are your geometry skills good for that?

But you have a slightly harder case, a rectangle and a circle. Using geometry, how can we determine that part of the rectangle overlaps?

Title: How to get an image or rectangle to detect collision with another image

Body:
Can someone please explain to me how to detect collision with another image?  The tutorial I was watching explained how to detect if a collision occurs between two rectangles but I would like to use two images instead.  Please see the code below.

```<code>public void paintComponent(Graphics g){
//g.drawImage(yellowBall, xCoor, yCoor, this);
Rectangle r1 = new Rectangle((boardXSize/2), (boardYSize/2),50, 50);
Rectangle r2 = new Rectangle(200, (250),50, 50);
g.setColor(Color.red);
g.fillRect(r1.x, r1.y, r1.width, r1.height);
g.setColor(Color.blue);
g.fillRect(r2.x, r2.y, r2.width, r2.height);

if(r1.intersects(r2)){
        System.out.println("Collision Detected");
    }
repaint();

}
</code>```

How can I detect if r1 intersects yellowBall instead of r2?  Please keep responses at the beginner level but of course, any assistance is greatly appreciated.  Thanks!!


问:
The destination of cout messages in a GUI program
I've been building some classes and functions in a static library which has the familiar printing of text messages to stdout:

```<code>cout << "Hello World!" << endl;
</code>```

I've been developing this library for use in a console application but I'm considering also trying to make a GUI version, because it will be both useful and highly educational (for me).

I wonder how is it possible to make output in a library sent to both stdout and GUI controls (like a status bar or a popup window). Since such messages are all sent (in my case anyway) to one destination (cout) could some sort of redirection be possible?

I've always presumed something like this may be possible as people often release command line and GUI versions of their programs.

答:
cout always writes to the standard output stream (stdout).  If you want the output to be redirected elsewhere (e.g. a graphical window) you will have to pipe the output to another program or thread responsible for handling the graphical interface.  There are many ways this can be done but it depends on the operating system somewhat.

By default, on Linux you can observe the stdout of both console and graphical programs just by running it from a terminal.  In fact, there's really no clear-cut distinction between "console" and "graphical" programs in Linux.

On Windows it's rather different: console and graphical programs are distinct*.  Graphical programs do not have a terminal allocated by default, so stdout messages usually end up in oblivion.  There is a little bit of trickery required to allocate a terminal for graphical programs (so that they behave similar to Linux).

(I can't comment on Macs as I don't use them.)

You can do redirections externally via the shell.  Here I assume a Bourne-like shell.**  Say you want to run a program my-simulation and feed its output to another program my-display, which presumably reads from the standard input (stdin).  If you run the program as is, the output will be dumped into the terminal as usual:

```<code>./my-simulation
</code>```

You can establish a pipe by running the following in the shell:

```<code>./my-simulation | ./my-display
</code>```

Or if you want to write to a file instead,

```<code>./my-simulation >my-output-file.txt
</code>```

Of course, these can all be done in C/C++, but with more work.  If you want stdout to be redirected to a file, you can use freopen from the standard library.  Redirecting stdout to another process is slightly more difficult as you need to use platform-specific API to deal with processes and piping file descriptors.

[*] In Windows lingo, graphical programs are called Windows applications.  You can find more about the various differences between these two kinds of programs on the MSDN.

[**] You can also do something similar with Command Prompt on Windows, but with a slightly different syntax.

Body:
cout always writes to the standard output stream (stdout).  If you want the output to be redirected elsewhere (e.g. a graphical window) you will have to pipe the output to another program or thread responsible for handling the graphical interface.  There are many ways this can be done but it depends on the operating system somewhat.

By default, on Linux you can observe the stdout of both console and graphical programs just by running it from a terminal.  In fact, there's really no clear-cut distinction between "console" and "graphical" programs in Linux.

On Windows it's rather different: console and graphical programs are distinct*.  Graphical programs do not have a terminal allocated by default, so stdout messages usually end up in oblivion.  There is a little bit of trickery required to allocate a terminal for graphical programs (so that they behave similar to Linux).

(I can't comment on Macs as I don't use them.)

You can do redirections externally via the shell.  Here I assume a Bourne-like shell.**  Say you want to run a program my-simulation and feed its output to another program my-display, which presumably reads from the standard input (stdin).  If you run the program as is, the output will be dumped into the terminal as usual:

./my-simulation

You can establish a pipe by running the following in the shell:

./my-simulation | ./my-display

Or if you want to write to a file instead,

./my-simulation >my-output-file.txt

Of course, these can all be done in C/C++, but with more work.  If you want stdout to be redirected to a file, you can use freopen from the standard library.  Redirecting stdout to another process is slightly more difficult as you need to use platform-specific API to deal with processes and piping file descriptors.

[*] In Windows lingo, graphical programs are called Windows applications.  You can find more about the various differences between these two kinds of programs on the MSDN.

[**] You can also do something similar with Command Prompt on Windows, but with a slightly different syntax.


答:
Since you want a practical   language:

Notice that Haskell and Lisp are used more than the others in industry, although there has been some recent interest in Clojure and F#.

But look what happens when we add Scheme to the mix:

Hmm, doesn't look so much like an academic language now, does it?

Actually, the above graph is probably a lie; the word "scheme" can appear in help wanted ads in other contexts besides programming languages. :)

So here is another graph that is probably (a little) more representative:

If you want to explore a really kick-ass dialect of Scheme, have a look at Racket.

Title: Choosing a functional programming language

Body:
I have read a lot of threads about functional programming languages lately (almost in the past year, in fact). I would really like to pick one and learn it thoroughly.

Last [course] semester, I have been introduced to Scheme. I loved it. Loved the extreme simplicity of syntax, the homoiconicity principle, the macros (hygienic and non-hygienic), the n-arity of procedures, etc.

The problem with Scheme is it's an academic language. I don't think it is really used in production environments. I don't believe either that it is particularly good to have on our resume. So, I have been looking around for alternatives. There are many of them and they somehow all seem to have a similar level of popularity.

Some thoughts about some other functional languages I have considered yet:

Clojure: It sounds great because it can access the Java world, it is oriented towards scalability and concurrency, but isn't the Java world on an edge right now? I already know Java pretty well, but would it be wise to add even more energy on depending on the JVM?

Haskell: Looks like a very appreciated language, but from what I have read, it's also more of an academic language.

Lisp: It's been around since forever. It seems to have most of what I like from Scheme. It has a big community. For what I [think I] know, it is probably the most widely used functional programming language in industry(?).

F#: Didn't really consider it. I'm not a big fan of MS stuff. I don't have the money to pay for their softwares (I could have them free from university alliances, but I'm more inclined to go with community-driven solutions). Though... I guess it would be the best career-oriented choice.

Tonight, I'm leaning towards Lisp. One week ago, it was Haskell. Before that it was Clojure. In the past year, I was doing some Scheme for fun, not pushing it for the reason you know. Now I would like to get serious (about learning one, about doing real projects with it, about maybe eventually professionally working with it). My problem is I would need to learn them all in depth before being able to choose one.


答:
If you are good with trigonometry here is my suggestion on collision detection for a ball and a rectangle:

find out the distance between the 2 centers. from here on i will call this the "connection"

if the distance is greater than ball.radius + rect.diagonal/2 then they don't intersect

if the distance is smaller than either ball.radius or rect.height/2 then they are guaranteed to intersect.

else use trigonometry to calculate the connection segment from the rectangle's center to its perimeter. if ball.radius + segment < connection then they don't intersect, if it is = then they touch each other, and if > then they intersect

This should work with any shape actually, as long as it is on a 2D plane. in 3D things will get much more complex.

Also this algorithm will always give you an almost perfect (i.e. computing round up errors, which would be minimal) solution but it will not be very fast, so if you are writing something like a game, it's better off to just create a collision circle using diagonal/2 as radius around the rectangle, it will be much faster but inaccurate.


答: What I would do is output what you want into an osstream and with this osstream i can use it to display the output on whatever front end i want, be it console or window message, etc.</p>

Title: The destination of cout messages in a GUI program

Body:
I've been building some classes and functions in a static library which has the familiar printing of text messages to stdout:

```<code>cout << "Hello World!" << endl;
</code>```

I've been developing this library for use in a console application but I'm considering also trying to make a GUI version, because it will be both useful and highly educational (for me).

I wonder how is it possible to make output in a library sent to both stdout and GUI controls (like a status bar or a popup window). Since such messages are all sent (in my case anyway) to one destination (cout) could some sort of redirection be possible?

I've always presumed something like this may be possible as people often release command line and GUI versions of their programs.


问:
iOS App Store Developers - What is the 'copyright name' of an app?
I understand that whenever you upload a new app, you can set the copyright name for the app.

Where is this name displayed?

Is this name displayed underneath the name of the app when searching in the app store? Or is that the seller name that you specify when you upload your first app?

答:
I think you can think of "trademark", which serves to identify a particular iPhone app or any service. You can register a TRADEMARK for your name.
But unless you pay to register it then you have no rights to it. So according to me for all iOS app developer rather mobile app developer must think of trademark for copyright name of an app.
Thanks</p>


问:
How to catch DllNotFoundException in C#?
this question in my opinion straightforward.

How can I catch an DllNotFoundException in C# as it is just an attribute to some methods use like this:

```<code>[DllImport("NativeLib.dll")]
private static extern void print_line(string str);
</code>```

When are these functions being invoked ? As I instance the class containing the methods ( sounds odd to me as it's being "static" )? Or as I want to use the methods?

答:
In c# static constructors for a class don't run until you use the class for the first time.  So if you want to catch the DllNotFoundException you need to do it the first time the class is used.  The most convenient way to do this is probably to encapsulate the external function pointer inside a (temporary) nested class, like so, so the external DLL is not loaded until the specific call is made:

```<code>public class MyOuterClass
{
    class ExternalDllSubClass
    {
        [DllImport("BananaquitFluffernutterOrWhatever.dll")]
        private static extern void print_line(string str);

        internal static void PrintLine (string str) {
            print_line(str);
        }
    }

    public void PrintLine(string str)
    {
        try
        {
            ExternalDllSubClass.PrintLine(str);
        }
        catch (DllNotFoundException e)
        {
            Debug.WriteLine(e.ToString());
        }
    }
</code>```

Then just set a break at the beginning of the outer function.  (Or catch the DllNotFoundException exception in Visual Studio using the exception assistant.)

For more, see C# static constructors are called on demand, not at startup.

Body:
In c# static constructors for a class don't run until you use the class for the first time.  So if you want to catch the DllNotFoundException you need to do it the first time the class is used.  The most convenient way to do this is probably to encapsulate the external function pointer inside a (temporary) nested class, like so, so the external DLL is not loaded until the specific call is made:

public class MyOuterClass
{
    class ExternalDllSubClass
    {
        [DllImport("BananaquitFluffernutterOrWhatever.dll")]
        private static extern void print_line(string str);

        internal static void PrintLine (string str) {
            print_line(str);
        }
    }

    public void PrintLine(string str)
    {
        try
        {
            ExternalDllSubClass.PrintLine(str);
        }
        catch (DllNotFoundException e)
        {
            Debug.WriteLine(e.ToString());
        }
    }

Then just set a break at the beginning of the outer function.  (Or catch the DllNotFoundException exception in Visual Studio using the exception assistant.)

For more, see C# static constructors are called on demand, not at startup.

ContentLicense: CC BY-SA 4.0


问:
What approach to use to query multiple XML files?
I'll be receiving tens of thousands of XML files, which will continue to grow with new files over time. I need to be able to query these files as a whole (like SQL querying all the records in a database). What technologies and/or approaches should I be looking at for this problem?

I feel like I should be looking into XQuery. I'm not that familiar with it, though.

UPDATE 1:

Example queries I might run:

Return all the product code, product name, product description from all XML files in /folder 1/ where the supplier id = x and store id = y

Return all the product code and product price from all XML files in /folder 2/ where the supplier id = x and store id = y

Maybe join the results of the two queries above, joining on product code

As there may be multiple results per product code for the two queries above, only get the most recent values based on some tag / attribute in the XML

UPDATE 2:

It seems like this article suggests that XQuery can be used: http://www.ibm.com/developerworks/xml/library/x-xquerymaven/index.html?ca=. As I am implementing a LAMP solution, I think there might be XQuery libraries available to PHP. Does this mean that I don't need an XML database to query loads of XML files?

答:
If the nature of all your queries allows sequential processing of your XML files, you can do this without an XML database, using either xpath/xslt or XQuery. For example:

Return all the product code, product name, product description from    all XML files in /folder 1/ where the supplier id = x and store id = y

Return all the product code and product price from all XML files in    /folder 2/ where the supplier id = x and store id = y

These are a very simple xpath expression for any decent xslt processor. You just have to loop over the specific files, load each of them into memory, run an xpath query and collect the results from each file (which xpath does not for you). XQuery seems to allow to collect the results, but see below.

Maybe join the results of the two queries above, joining on product code

This is not easily possible with xpath only (at least not very efficient). From the article you linked to, one can see an example how a join is done by XQuery - without a database - but it needs all XML files to be loaded into main memory (which is quite unrealistic when you have ten thousands of them). If you got all results from the two first two queries, however, you can "join" them by using your host language (in your case PHP), but you have to "program it manually". A decent XML database however should be capable of solving these problem for you - without loading all files into memory, by proper indexing.

So this all boils down to the question how many queries you expect, how many of them allow sequential processing, and how many don't. If you expect less than 5 different queries, I would probably not use a database for it but try to program every non-sequential requirement manually. If you expect more than 100 different queries, and you cannot even foresee how they will look like, then the use of a database is probably appropriate (but YMMV). In the end you have to find out for yourself what suits your needs best.


答:
I dove into Haskell for a while, but the conclusion I came to was that it was a little too academic. It was very hard to do anything practical. In a pure functional language, things like IO just don't quite fit into the model, so you have to deal with monads. I determined I would have to put in a tremendous amount of time to be just barely competent, so I moved on.

I did Scheme in college. Might sound trivial, but all the parens really are distracting/annoying. Hard to go back to that after using languages like Python.

Recently I have been exploring F#. It is functional, but can also be imperative and object-oriented when you want to. This, along with being able to use any .NET libraries, makes it possible to easily mix your pure functional parts with more practical things like GUIs, IO and networking. You can get a standalone version of F#.

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=effc5bc4-c3df-4172-ad1c-bc62935861c5&displaylang=en


问:
How do I find the JavaScript that is invoked when I click on a button or a link in a web-page (part of a data mining project)?
I tried to use the 'inspect element' of the firebug addon for Firefox but it doesn't give me any link to the javascript.

For example I got this from the firebug add-on:

    text of the link

```

But there is no link to the actual javascript or anything that I can use to directly go to the said link.

How do I accomplish this? I need this as part of a personal data mining project that I am doing.

答:
Using chrome/chromium, adding breakpoints on an event is a piece of cake:

Right click the element, select "inspect element"

The console pops open, on the right side, there's a tabbed window, select the "Event Listeners" tab

Select the desired event, in this case click

You should see a list of event listeners, and a link to the js code that binds those listeners.

click on the bound listeners, to learn more about them

Use the links to navigate to the listener you're interested in

Right click on the line number where you want to set your breakpoint

Select "Add Breakpoint" or "Add Conditional Breakpoint..."

For conditional breakpoints: type an expression that best suits your needs

Screenshots and more details can all be found here, though. The documentation is also interactive: for each feature, there's a link or button you can use to set a breakpoint on. Try a couple of them out, and get a feel for it. It's really a great tool for debugging client-side JS code.


问:
When should the programmer's spoken language be used during development?
I'm an Italian developer, but I have a good understanding of English.

Sometimes, when developing an application targeted for an Italian audience, I wonder whether it is correct to use the Italian language in my code or not.
By "Italian language in my code" I mean the names of methods, classes, comments, variables and so on.

For example, when I write code like this:

```<code>/* Attenzione: metodo esageratamente complicato */
public double calcolaImposteDeiServizi() { ... }
</code>```

Do I break any sacred law of programming because I didn't write that code as follows?

```<code>/* Caution: overly complicated method */
public double calculateTaxesOfServices() { ... }
</code>```

I remember a project I worked on some time ago. It was about calculating VAT/taxes/bonuses. Some of this code was dealing with concepts that existed only in the Italian economy at that moment.

I preferred to write that project using only Italian names for methods, otherwise it would clearly have become a mess understanding that VAT was Italian's IVA and so on.

By using this example, should there be some kind of rule for deciding whenever to use your language or not in code?

Did any highly authoritative programmer ever said something about this issue?

How do you make this kind of decision in your projects?

答:
It depends on the company you are working for. Many companies will ask for English only source code, since it has more value this way (you can outsource features to other countries with lower support costs). Some will accept local language for specific reasons:

in the business layer, you may find it hard to translate business specific terms. Using English may bring some trouble when modeling the domain layer because each developer has to create his own vocabulary, unless a standard is defined and used for the team

the company is not planning to outsource its development work


问:
How could your company's learning/development department best serve you?
I'll preface my question with a disclaimer - I am not an engineer, I'm just someone who works with them full-time, in a learning and development capacity.

Given that, one of the comments I get regularly from the engineers I'm tasked with developing is that they feel that they're having solutions (both technical and non-technical) for development "pushed" at them vs. anyone from my field consulting with them to determine what they really need.

So my question is - if you could give your company a list of the top 3-5 things they could do - in a classroom, or elsewhere - to develop meaningful skills that would help you be a better engineer, a better employee, and one more likely to STAY with the company for the long haul, what would make the cut and why?

Thanks in advance for your responses.

答:
Subsidize/sponsor conference attendance.  Make sure devs have the opportunity for paid time off and expenses to attend tech conferences in their field -- a minimum of once per year.

Community development time Let devs spend a few work hours per month on open source projects, so they can stay in touch with the development community and on top of the latest tech.

Learning lunches This is when the company buys food and sets aside an extra-long lunch period for devs to eat together and take turns presenting on tech topics.  Once or twice per month is ideal.

Build a tech library.  A corporate Safari subscription is a good start, but don't fail to also include classics like The Art of Computer Programming.

The thing about being a dev is that if you are really good at your job, the lag time between relevant tech being created, and that tech making it in to standard corporate learning avenues, makes those traditional methods fairly useless.

It's more effective to provide excellent reference resources, and most importantly, opportunities to learn directly from other devs.


问:
Should "tests" be kept out of the main merge pipeline?
We all know sometimes a e.g. merge can go wrong.

If our [unit / integration] tests are in the same repository as the merge, is there then a weakness there that if the tests have merged incorrectly and do not appear in the final code then "we don't know what we don't know".

Should the unit test project then instead be a complete separate item?

In many ways I'd say no as it could litter a master branch with feature tests which are not yet relevant.

In compiled languages then the compilation will fail if the test's reliant code is missing, so will help to a certain degree. But perhaps a non-compiled language is better as it would highly specific missing items when running the test.

Does anyone have a workflow which it is possible to know which features may of merged incorrectly?

答:
Unit tests are code as everything else. So if you merge your code, and your unit tests depend on the version or revision of the non-testing code (which is normally the case), you should always merge your tests together with everything else. This includes the resolving of any merge conflicts, if they occur.

If the merge conflicts of your test suite are not resolved, you loose the ability to compile and run it (or in a non-compiled language: the test suite may bring wrong results or crash at run time) - is that really worth the hassle? Delaying the resolving of a merge conflict is never helpful, the longer you wait, the harder it gets. Test code is therefore not different from any other kind of code. And if resolving the merge conflicts of your tests needs so much effort that you consider omitting the resolve as a serious option, there is something very, very wrong with your workflow.


答:
This is a very good question.

In general, I prefer to keep things in English, because it is more or less the de-facto standard for software development.

However, I also believe in creating domain models that represent the actual business, and the domain model should be described in terms that make sense to the business stakeholders. And if the business is not natively English, then creating an English domain model violates this principle. And what is then in reality happening is that you, the developers, invent translations which may or may not be correct.

And there are most likely terms in your business that does not translate into English.

One such example is the concept of "Sygedagpenge" in Denmark. It's a system where people with a job can get public benefits if they over a long time period are not able to fulfill that job because of a medical condition,. This word cannot be translated into any language because the system is purely Danish. Other countries probably have similar systems, but it's not the same system.

So don't try to translate very country specific domain terms*. Whether or not you then write the entire domain model/business code in the native language of the business, or if you translate as much to English as possible, only keeping the untranslatable words in the native language of the business is up to you**.

But creating the entire domain model in the native language of the business will help you, the developers, to better speak the business language with the business stakeholders.

But personally I would keep all non-business code in English, e.g. infrastructure and gui code.

* Given that you say that you work with taxes, vat, etc. I guess that you do have some country specific terms, as you are probably dealing with rules dictated by legislation in your country.

** The system I am currently working on, most of the domain model is in English, but we have a few concepts that cannot be translated, so we have kept those in Danish. I think this approach is working pretty well in our case. But that doesn't mean that I would prefer that approach for the next project.

Title: When should the programmer's spoken language be used during development?

Body:
I'm an Italian developer, but I have a good understanding of English.

Sometimes, when developing an application targeted for an Italian audience, I wonder whether it is correct to use the Italian language in my code or not.
By "Italian language in my code" I mean the names of methods, classes, comments, variables and so on.

For example, when I write code like this:

```<code>/* Attenzione: metodo esageratamente complicato */
public double calcolaImposteDeiServizi() { ... }
</code>```

Do I break any sacred law of programming because I didn't write that code as follows?

```<code>/* Caution: overly complicated method */
public double calculateTaxesOfServices() { ... }
</code>```

I remember a project I worked on some time ago. It was about calculating VAT/taxes/bonuses. Some of this code was dealing with concepts that existed only in the Italian economy at that moment.

I preferred to write that project using only Italian names for methods, otherwise it would clearly have become a mess understanding that VAT was Italian's IVA and so on.

By using this example, should there be some kind of rule for deciding whenever to use your language or not in code?

Did any highly authoritative programmer ever said something about this issue?

How do you make this kind of decision in your projects?


问:
Enforcing organizational standards for software in Scrum
Organizations, especially organizations with a recognized brand, have various standards for software. This includes things like security, usability, code quality and readability, UI design, test automation and so forth. In our organization we have a lead for each of these areas. Each lead is a very experienced individual and is trusted by management. Each lead is responsible for the software to meet the standards in the lead's area of expertise.

The Scrum Guide says: "Development teams are self-organizing. No one (not even the Scrum Master) tells the Development Team how to turn Product Backlog into Increments of potentially releasable functionality;"

My question is how can an organization trust teams to produce a product that meets the various standards mentioned above, if the leads (trusted by the organization) have no ability to enforce the quality in each of the areas?

答:
The typical place where such quality standards are enforced is in the "Definition of Done" that the team uses. The "Definition of Done" is essentially a checklist that you go through to see if all the necessary work on the story has been completed and has been done to the quality standard that the team has agreed to maintain.

If the teams already have experience with applying those standards to their work, then it should not cause any burden to require that the software conforms to all those standards in a verifiable way at the end of a sprint.

If the team doesn't have experience with applying those standards, you might want to introduce them one or two at a time.

In essence, when using Scrum, the entire team becomes responsible for applying those standards. The current leads in those areas would get more a role of an advisor and reviewer, advising the teams on how to apply the standard and verifying that it was done properly.


问:
calculate complexity of LinkedHashSet
I have an ArrayList<LinkedHashSet<String>> setOfStrings for example this arraylist internally is composed like:

```<code>positionX[hello,car,three,hotel,beach]
positionY[.....]
...
</code>```

I want to find car inside this data-structure, so I did it

```<code>for (Iterator<LinkedHashSet<String>> iterator = setOfStrings.iterator(); iterator.hasNext();) {
    LinkedHashSet<String> subSet = iterator.next();
    if (subSet.contains("hotel"))
        System.out.println("found");
}
</code>```

The for iterate over the entire arrayList and the complexity in the worst-case is O(n), but I'm confused on the complexity of the method contains() of set. In according of javadocs this method is executed in constant time, but I've heard that in certain cases the complexity might become O(n). Saying that, I'm not sure about the complexity of this snippet algorithm.

Can someone provide me an explanation of that?

答:
For hashing operations like the contains() you have above, the worst case complexity is big O of n. This happens when there are n instances with the same hash value and the hashing implementation is chaining. This also happens when n instances have the same hash-value sequence and the implementation is open-addressing. Both of these cases are unlikely, but nevertheless contains() is big O of (n) and small O of (n) and thus is theta of (n).

In practice, people often care about average running time complexity, and average running time complexity of contains() running on a large enough sequence of input is indeed amortized into about constant.

Title: calculate complexity of LinkedHashSet


问:
What happens if you're unable to solve a problem?
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?

答:
I follow the Polya princinple:

"If there is a problem you can't solve, then there is an easier problem you can't solve: find it."

George Polya

The beauty of the principle is that at some point there will be a problem that is small enough and that you will be able to solve which, hopefully if you did things right, will allow you to bootstrap a solution to the original problem. This principle has not failed me yet.


问:
Reconciling the Boy Scout Rule and Opportunistic Refactoring with code reviews
I am a great believer in the Boy Scout Rule:

Always check a module in cleaner than when you checked it out." No
  matter who the original author was, what if we always made some
  effort, no matter how small, to improve the module. What would be the
  result? I think if we all followed that simple rule, we'd see the end
  of the relentless deterioration of our software systems. Instead, our
  systems would gradually get better and better as they evolved. We'd
  also see teams caring for the system as a whole, rather than just
  individuals caring for their own small little part.

I am also a great believer in the related idea of Opportunistic Refactoring:

Although there are places for some scheduled refactoring efforts, I
  prefer to encourage refactoring as an opportunistic activity, done
  whenever and wherever code needs to cleaned up - by whoever.
  What this means is that at any time someone sees some code that isn't
  as clear as it should be, they should take the opportunity to fix it
  right there and then - or at least within a few minutes

Particularly note the following excerpt from the refactoring article:

I'm wary of any development practices that cause friction for
  opportunistic refactoring ... My sense is that most teams don't do
  enough refactoring, so it's important to pay attention to anything
  that is discouraging people from doing it. To help flush this out be
  aware of any time you feel discouraged from doing a small refactoring,
  one that you're sure will only take a minute or two. Any such barrier
  is a smell that should prompt a conversation. So make a note of the
  discouragement and bring it up with the team. At the very least it
  should be discussed during your next retrospective.

Where I work, there is one development practice that causes heavy friction - Code Review (CR). Whenever I change anything that's not in the scope of my "assignment" I'm being rebuked by my reviewers that I'm making the change harder to review. This is especially true when refactoring is involved, since it makes "line by line" diff comparison difficult. This approach is the standard here, which means opportunistic refactoring is seldom done, and only "planned" refactoring (which is usually too little, too late) takes place, if at all.

I claim that the benefits are worth it, and that 3 reviewers will work a little harder (to actually understand the code before and after, rather than look at the narrow scope of which lines changed - the review itself would be better due to that alone) so that the next 100 developers reading and maintaining the code will benefit. When I present this argument my reviewers, they say they have no problem with my refactoring, as long as it's not in the same CR. However I claim this is a myth:

(1) Most of the times you only realize what and how you want to refactor when you're in the midst of your assignment. As Martin Fowler puts it:

As you add the functionality, you realize that some code you're adding
  contains some duplication with some existing code, so you need to
  refactor the existing code to clean things up... You may get something
  working, but realize that it would be better if the interaction with
  existing classes was changed. Take that opportunity to do that before
  you consider yourself done.

(2) Nobody is going to look favorably at you releasing "refactoring" CRs you were not supposed to do. A CR has a certain overhead and your manager doesn't want you to "waste your time" on refactoring. When it's bundled with the change you're supposed to do, this issue is minimized.

The issue is exacerbated by Resharper, as each new file I add to the change (and I can't know in advance exactly which files would end up changed) is usually littered with errors and suggestions - most of which are spot on and totally deserve fixing.

The end result is that I see horrible code, and I just leave it there. Ironically, I feel that fixing such code not only will not improve my standings, but actually lower them and paint me as the "unfocused" guy who wastes time fixing things nobody cares about instead of doing his job. I feel bad about it because I truly despise bad code and can't stand watching it, let alone call it from my methods!

Any thoughts on how I can remedy this situation ?

答:
If you can split the requested change and the unrequested refactor into (a lot of) separate commits, as noted by @Useless, @Telastyn and others, then that is the best you can do. You will still be working on a single CR, without the administrative overhead of creating a "refactoring" one. Just keep your commits small and focused.

Instead of giving you some advices in how to do it, I prefer to point you to a much bigger explanation (in fact, a book) from a specialist. This way, you will be able to learn a lot more. Read Working Effectively with Legacy Code (by Michael Feathers). This book can teach you how to do the refactoring, interleaved with the functional changes.

The topics covered include:

Understanding the mechanics of software change: adding features,
fixing bugs, improving design, optimizing performance

Getting legacy code into a test harness

Writing tests that protect you against introducing new problems

Techniques that can be used with any language or platform—with
examples in Java, C++, C, and C#

Accurately identifying where code changes need to be made

Coping with legacy systems that aren't object-oriented

Handling applications that don't seem to have any structure

This book also includes a catalog of twenty-four dependency-breaking techniques that help you work with program elements in isolation and make safer changes.


答:
The lead is there to lead, not dictate or enforce.  If he is trusted and respected by his fellow developers why wouldn't they listen to him?  And if the lead can't trust his fellow developers, then there's a deeper problem.

These teams should have working agreements and an agreed upon definition of done. These are the things that help enforce quality and process within the team.

Picture a scrum / agile environment where someone could just walk in and say, "This is how I want it done! Do it this way!".  Now, I'm not saying that this doesn't happen, but it shouldn't.  This is why the guide states what it does.

The guide isn't taking away anything from the lead, and it is infact fostering a better environment based around teamwork.  The lead's ability to "enforce" is based upon trust and respect of his teammates.  Otherwise, what good is it?

Scrum is also not just a hard set of rules; YMMV.

Title: Enforcing organizational standards for software in Scrum

Body:
Organizations, especially organizations with a recognized brand, have various standards for software. This includes things like security, usability, code quality and readability, UI design, test automation and so forth. In our organization we have a lead for each of these areas. Each lead is a very experienced individual and is trusted by management. Each lead is responsible for the software to meet the standards in the lead's area of expertise.

The Scrum Guide says: "Development teams are self-organizing. No one (not even the Scrum Master) tells the Development Team how to turn Product Backlog into Increments of potentially releasable functionality;"

My question is how can an organization trust teams to produce a product that meets the various standards mentioned above, if the leads (trusted by the organization) have no ability to enforce the quality in each of the areas?


问:
What, why or when it is better to choose a queuing tool vs database task table?
I would like to know what, why or when it is better to choose a queuing tool and what, why or when it is better to choose database task table? I don't understand the difference of sending my tasks in a queuing tool or in a database table that will be read and act as a queue. Is there some properties that queuing tools has that database cannot do?

Read my question as "what are the benefit or what are the arguments to choose a queuing tool solution". My question is not about what language, technology, or project one should take up next.

Thank you,

答: The short answer is queues are optimized for what they do while databases are not.  Some actually consider the use of a database as a queue an anti-pattern.  Much has been said that I won't repeat here.  A common thought is that while it seems trivial to turn a database into a queue, you eventually end up having to solve all of the problems the queue designers have already solved for you.</p>


答:
I prefer English with some little exceptions.

Why English:

If you communicate with other developers its easier for them to understand your code. For example, copy & paste Italian code to stackexchange.com is time-consuming if you have to translate it before publishing.

Many technical terms are in English. So translating this terms from English into country specific names is more complex than to use ready-to-use English terms.

If you have a country specific domain model ask English native speakers for corresponding English words for your domain. It's very likely that somebody used this terms before or there may exist very descriptive and expressive English translations as well. Moreover you can verify your English business terms as well as your domain model, because English natives speakers often ask for background information that you first often don't consider yourself.

If you want to search over your codebase (file search, member search, search & replace ...) its easier to realize, if you have a consistent language. Imagine you search for classes that have to do with taxing: its more easy to search for the two nouns tax and VAT than to find out the waste number of corresponding Italian, Japanese or Danish nouns.

If your project grows up and you have to involve external developers, save them the pain to translate your code.

Some compilers or tools don't like special characters. So it's better to use the minimal set of English letters.

Improves your own English ;-)

When not:

If you have very special country specific terms or personal nouns, its better to use the personal noun, because its most likely that English native speakers wouldn't translate it as well, think of street names or some public holidays for example.

Comments I always write in the language that the main audience[1] speaks, because the intent of the code should be the code itself. The intent of the comments is that the main audience can understand the intent of the code more easily. So if the main audience speaks Russian, write the comment in Russian. Moreover coding in English and writing native comments gives a better and consistent understanding of code for the main project members.

My decision rule:

for Code

Imagine you will write a book, that you write for mass consumers: If you would use the native word then use the native word in your code as well. If you would translate it into expressive English term so that your English readers can feel the meaning, so also use the English translation consistently in your code base.

for Comments

Write comments for the audience[1] like a reviewer a review in the language that the audience can feel.

[1] Audience aren't users! With audience are meant developers, reviewers, maintainers and persons who have to handle the code!


答:
I hate internal training. The best thing internal training can do is pay for external training of my choice. There is exceptional external training out there far better than any internal training could ever hope to be. Paying for external training will both benefit the company with more skilled employees and contribute to increased retention as external training is generally considered to be a perk.

Per comment:  The absolute best training I ever attended was the Architect's Master Class.  Period, full stop, there is none better.  I also attended Guerrilla COM when it was taught by Don Box and Guerrilla .NET when it was taught by Mike Woodring and Keith Brown.  Believe me, you will get more out of spending a week with Juval Lowey than you will out of a year of internal training.

Title: How could your company's learning/development department best serve you?

Body:
I'll preface my question with a disclaimer - I am not an engineer, I'm just someone who works with them full-time, in a learning and development capacity.

Given that, one of the comments I get regularly from the engineers I'm tasked with developing is that they feel that they're having solutions (both technical and non-technical) for development "pushed" at them vs. anyone from my field consulting with them to determine what they really need.

So my question is - if you could give your company a list of the top 3-5 things they could do - in a classroom, or elsewhere - to develop meaningful skills that would help you be a better engineer, a better employee, and one more likely to STAY with the company for the long haul, what would make the cut and why?

Thanks in advance for your responses.


问:
problem on calculating Big O complexity
i have this function on which i have to calculate the time complexity with the Big O notation:

```<code>public void print(ArrayList<String> operations, ArrayList<LinkedHashSet<String>> setOfStrings) {
    int numberOfStrings = 0;
    int numberOfLetters = 0;
    String toPrint = operations.get(1);
    for (Iterator<LinkedHashSet<String>> iteratorSets = setOfStrings.iterator(); iteratorSets.hasNext();) {
        LinkedHashSet<String> subSet = iteratorSets.next();
        if (subSet.contains(toPrint)) {
        for (Iterator<String> iterator = subSet.iterator(); iterator.hasNext();) {
            numberOfLetters = numberOfLetters + iterator.next().length();
        }
        numberOfStrings = subSet.size();
        break;
        }
    }
}
</code>```

the method does this operation:

For example, if have as operation print foo, I have to do these steps,first of all, I have to find where foo is:

Inside setOfStrings, I can have this situation:

```<code>        position 1 : [car, tree, hotel]
        ...
        position n : [lemon, coffee, tea, potato, foo]
</code>```

When I find the string foo, I have to save the number of strings inside that position and the number of letters of each string, so in this case, I will save:

```<code>   5(number of strings) 23(sum of number of letters)
</code>```

some considerations:

For the arrayList of operations, I get always a specific position, so I don't iterate.  It is always O(1).

For the ArrayList<LinkedHashSet<String>> , I have to iterate, so the complexity in the worst case is O(n)

the operation  if (subSet.contains(toPrint)), it will be O(1),because hashSet has mapped all objects inside it.

the iteration inside the hashset made with for (Iterator<LinkedHashSet<String>> iteratorSets = setOfStrings.iterator(); iteratorSets.hasNext();) , it will be O(m),because i have to  iterate inside the entire hashset to sum the letters of each words

so in conclusion i think the time complexity of this algorithm is(O(n)*O(m))

are these considerations all corrects?
thanks.

答:
It is a bit more complicated than that.  The worst-case complexity is O(M * N), and the best-case complexity is O(N).

There are two worst-case scenarios:

when every subset contains the toPrint String, or

when the subsets contain strings that all has to the same value.

(The second one is extremely unlikely, unless someone deliberately populates the data structure with data with that property.  But it is still a case that needs to be considered in a thorough complexity analysis.)

The best-case scenario is when strings in the subsets hash "nicely" AND the probability of the contains test returning true tends to zero.

Finally, N is the size of setOfStrings, and M is the average size of a subset.

Title: problem on calculating Big O complexity


问:
Managing client-side and server-side validations in one place
I'm 100% on board with the case that one should definitely use both client-side and server-side data validations.

However, in the frameworks and environments I've worked in, the approaches I've seen have never been DRY. Most of the time there's no plan or pattern - validations are written in the model spec, and validations are written in the form on the view. (Note: Most of my first-hand experience is with Rails, Sinatra, and PHP w/ jQuery)

Mulling it over, it seems like it would not be difficult to create a generator which, given a set of validations (e.g. model name, field(s), condition), could produce both the necessary client-side and server-side material. Alternately, such a tool could take the server-side validations (such as the validates code in an ActiveRecord model) and generate client-side validations (such as jQuery plugins, which would then be applied to the form.

Obviously, the above is just a "hey I had this idea" musing, and not a formal proposal. This sort of thing is surely more difficult than it seemed when the idea hit me.

That brings me to the question: How would you approach designing a "write once, run on server and client" technique for data validation?

Related subtopics: Do tools like that exist for any particular frameworks or client-server technologies? What are major gotchas or challenges with trying to maintain only one set of validations?

答:
One consideration that often limits solutions is the network round trip.  The client is supposed to validate the user data without sending a message over the network.  In other words, when the user hits the submit button, the client is supposed to validate the data locally.

First, let's assume that we do not have this limitation.  We could communicate with a network endpoint that is good at articulating validation issues.  For example, when you submit your new User record to it, rather than responding with a vanilla HTTP error code, it could return a detailed JSON response itemizing the issues and the client would smartly update the display to reflect the problems it encountered.  The endpoint plays the role of a validation gateway.

It's DRY but not without drawbacks.  First, it depends on the network roundtrip taxing our server with validations that could have been handled client side.  Second, the design anticipates that all CRUD operations will occur via our endpoints, but what about when developers and processes bypass our data access layer by going directly against the database?

Let's revisit our solution to overcome these drawbacks.  Instead let's store and communicate our validations as metadata:

```<code>{field: 'username', type: 'required'}
{field: 'username', type: 'unique'} //requires a network roundtrip
{field: 'password', type: 'length', min: 10, max: 50}
{field: 'password', type: 'contains', characters: ['upper', 'special', 'letter', 'number']}
</code>```

Both the client and the server would have some mechanism (e.g. an engine) for interpreting and applying this data.  (Some call this the free monad as it separates the declarative portion from its interpreter.)  In JavaScript we could map each piece of information to working functions.  To boot, we can teach any layer of our architecture, including our database, to enforce validations consistently.

Body:
One consideration that often limits solutions is the network round trip.  The client is supposed to validate the user data without sending a message over the network.  In other words, when the user hits the submit button, the client is supposed to validate the data locally.

First, let's assume that we do not have this limitation.  We could communicate with a network endpoint that is good at articulating validation issues.  For example, when you submit your new User record to it, rather than responding with a vanilla HTTP error code, it could return a detailed JSON response itemizing the issues and the client would smartly update the display to reflect the problems it encountered.  The endpoint plays the role of a validation gateway.

It's DRY but not without drawbacks.  First, it depends on the network roundtrip taxing our server with validations that could have been handled client side.  Second, the design anticipates that all CRUD operations will occur via our endpoints, but what about when developers and processes bypass our data access layer by going directly against the database?

Let's revisit our solution to overcome these drawbacks.  Instead let's store and communicate our validations as metadata:

{field: 'username', type: 'required'}
{field: 'username', type: 'unique'} //requires a network roundtrip
{field: 'password', type: 'length', min: 10, max: 50}
{field: 'password', type: 'contains', characters: ['upper', 'special', 'letter', 'number']}

Both the client and the server would have some mechanism (e.g. an engine) for interpreting and applying this data.  (Some call this the free monad as it separates the declarative portion from its interpreter.)  In JavaScript we could map each piece of information to working functions.  To boot, we can teach any layer of our architecture, including our database, to enforce validations consistently.


答:
I would personally always use English.

English is a de facto reference language for development (among others).

The third party liraries or web service API are written in English. I feel that mixing language in that case is a bit ugly and confusing.

English is also spoken worldwide so it is generally chosen by persons speaking different language to communicate. This point is the most important for me because I live in a country with three official languages and many foreigners working as developers. It is by consequence quite common that members of the dev teams speak different languages. Furthermore I often worked on projects developed or going to be maintained abroad.

If you intend to create libraries, web services..., it is obvious that API and documention in English are required if you want it to be used worldwide..

As mentioned in other answers, there are some restrictions, of course, such as specific terms that are hard to translate in English, but it remains quite exceptional and shouldn't make you prefer another language.


问:
Why don't we store the syntax tree instead of the source code?
We have a lot of programming languages. Every language is parsed and syntax checked before being translated into code so an abstract syntax tree (AST) is built.

We have this abstract syntax tree, why don't we store this syntax tree instead of the source code (or next to the source code)?

By using an AST instead of the source code. Every programmer in a team can serialize this tree to any language they want (with the appropriate context free grammar) and parse back to AST when they are finished. So this would eliminate the debate about the coding style questions (where to put the { and }, where to put whitespace, indentation, etc.)

What are the pros and cons of this approach?

答:
You've been reading my mind.

When I took a compilers course, a few years ago, I discovered that if you take an AST and serialize it, with prefix notation instead of the usual infix notation, and use parentheses to delimit entire statements, you get Lisp.  While I'd learned about Scheme (a dialect of Lisp) in my undergrad studies, I'd never really gained an appreciation for it.  I definitely gained an appreciation for Lisp and its dialects, as a result of that course.

Problems with what you propose:

it's hard/slow to compose an AST in a graphical environment.  After all, most of us can type faster than we can move a mouse.  And yet, an emerging question is "how do you write program code with a tablet?" Typing on a tablet is slow/cumbersome, compared to a keyboard/laptop with a hardware keyboard.  If you could create an AST by dragging and dropping components from a palette onto a canvas on a large, touchscreen device programming on a tablet could become a real thing.

few/none of our existing tools support this.  We have decades of development wrapped up in creating increasingly-complex IDEs and increasingly-intelligent editors.  We have all these tools for reformatting text, comparing text, searching text.  Where are the tools which can do the equivalent of a regular expression search across a tree? Or a diff of two trees? All of these things are easily done with text.  But they can only compare the words.  Change a variable name, such that the words are different but the semantic meaning is the same, and those diff tools run into trouble.  Such tools, developed to operate on ASTs instead of text, would allow you to get closer to comparing the semantic meaning. That would be a Good Thing.

while turning program source code into an AST is relatively well-understood (we have compilers and interpreters, don't we?), turning an AST into program code is not-so-well-understood.  Multiplying two prime numbers to get a large, composite number is relatively straightforward but factoring a large, composite number back into primes is much more difficult; that's where we are with parsing vs decompiling ASTs.  That's where the differences between languages becomes an issue.  Even within a particular language, there are multiple ways to decompile an AST.  Iterating through a collection of objects and getting some kind of result, for example.  Use a for loop, iterating through an array? That would be compact and fast, but there are limitations.  Use an Iterator of some kind, operating on a Collection? That Collection could be variable-sized, which adds flexibility at the (possible) expense of speed.  Map/Reduce? More complex, but implicitly parallelizable.  And that's just for Java, depending on your preferences.

In time, the development effort will be expended and we will be developing using touchscreens and ASTs.  Typing will become less of a necessity.  I see that as a logical progression from where we are, looking at how we use computers, today,  That will solve #1.

We are already working with trees.  Lisp is merely serialized ASTs.  XML (and HTML, by extension) is just a serialized tree.  To do searching, we already have a couple prototypes: XPath and CSS (for XML and HTML, respectively).  When graphical tools are created that allow us to create CSS-style selectors and modifiers, we will have solved part of #2.  When those selectors can be extended to support regexes, we'll be closer.  Still looking for a good graphical diff tool for comparing two XML or HTML docs.  As people develop those tools, #2 will be can be solved.  People are already working on such things; they just aren't there, yet.

The only way I can see to be able to decompile those ASTs to programming language text would be something goal-seeking.  If I'm modifying existing code, the goal might be achieved by an algorithm which makes my modified code as similar as possible to the starting code (minimal textual diff).  If I'm writing code from scratch, the goal might be the smallest, tightest code (likely a for loop).  Or it might be code which parallelizes as efficiently as possible (likely a map/reduce or something involving CSP).  So, the same AST could result in significantly different code, even in the same language, based on how the goals were set.  Developing such a system would solve #3.  It would be computationally complex, meaning we'd probably need some kind of client-server arrangement, allowing your handheld tablet to offload a lot of heavy lifting to some cloud-based server.


答:
I do some programming myself (although I'm primarily a sys-admin) and we've got a large software development team here on site.

We have a clear consensus among the people here:

In general the programming language itself has its basis in English.

Using non-English names for methods, functions, variables, etc. is therefore, in our opinion, to be avoided to prevent the author AND the reader to having to switch back and forth between 2 languages.

Mentally juggling 2 languages is in general not good for overall understanding and tiresome too.

The added benefit is that getting another programmer working on the code is easier as just about any programmer can be assumed to have a working knowledge of English. (Note: Working knowledge doesn't equal "good". But usually it is good enough to get by.)

Writing the comments in another language is also to be avoided, for exactly the same reasons.

The ONLY exception to this the is naming objects, functions, variables that have a very specific meaning in the context of the program and the language of the target audience.

The example already mentioned of a tax that only exists in Italy is a very good example to illustrate this: It makes no sense to try to translate the Italian name of that tax into another language. To really emphasize this is specific to Italy the Italian name stands out and makes sure, at some later point in time, no programmer is going to confuse it with another (more general) tax also mentioned somewhere in the program.


答:
I'd say you should do whatever works best for the people who are going to be looking at your code. The purpose of method names, variable names and comments is to make the INTENT of your program clear.

If you can reasonably expect that the only people who will be reading the code will be Italian speakers, the why the heck make them try to puzzle out English translations? Furthermore, if English is a second language for you, then trying to translate everything is likely to lead to less clear comments and names than if you'd stayed with your native language.

If, on the other hand, those who come after are NOT expected to be native speakers, then English is probably a good choice as a second language.


问:
Do you have your own 'misc utils' library? What part are you most proud of?
I know that many of us maintain our own little personal library with tools and utilities that we use often.

I've had mine since I was 16 years old so it has grown to quite a considerable size. Some of the stuff I've written has since been added to the framework. I wrote my own little implementation of expression trees for use with genetic algorithms long before LINQ, which I quite like and was proud of at the time - of course its pretty useless now. But recently I have been going through it and upgrading to .NET 4.0 and re-kindled an interest.

So I'm curious as to what you use your library for. Maybe we could get some cool ideas going for useful little snippets and share them amongst ourselves.

So my questions are:

Do you have a miscellaneous utility library?

Which part are you most proud of and why?

Give an example of code if you like :-)

答:
Scala standard library lacks some most commonly used higher order functions.

Two such functions that I need most often:

```<code>// #1: unfold
def unfold[T, R](init: T)(f: T => Option[(R, T)]): List[R] = f(init) match {
  case None => Nil
  case Some(r, v) => r :: unfold(v)(f)
}

// #2: zipWith
def zipWith[A, B, C](xs: List[A], ys: List[B])(f: (A, B) => C): List[C] = {
  (xs, ys).zipped.map(f)
}
</code>```

Body:
Scala standard library lacks some most commonly used higher order functions.

Two such functions that I need most often:

// #1: unfold
def unfold[T, R](init: T)(f: T => Option[(R, T)]): List[R] = f(init) match {
  case None => Nil
  case Some(r, v) => r :: unfold(v)(f)
}

// #2: zipWith
def zipWith[A, B, C](xs: List[A], ys: List[B])(f: (A, B) => C): List[C] = {
  (xs, ys).zipped.map(f)
}


答:
My rule of thumb is to describe what the method does to a rubber duck in English. If I have to use a Hebrew word because there is no English equivalent, then the method name is in transliterated Hebrew. If I can describe what the method does in English, then the method name is English. Try to keep English as the default, and Italian as the rare exception.

Just don't do half-Italian, half-English method names. That confuses everybody, including yourself when you go to maintain it six months from now!


问:
Is it beneficial to study past the basics of a core language when the primary goal is to rely on its framework?
Please keep in mind this is not another 'How much [insert programming language here] should I know before moving onto [insert framework here]?' What I'd like to know is how beneficial is it to learn the those advanced concepts of a programming language when your intention is to heavily rely on its framework the majority of the time. So for example I've began to use jQuery and first took the time out to really grasp the core concepts of Javascript. Additionally I have a few beyond the basics books (Secrets of a Javascript Ninja for instance) on the shelf that really delve into the language. As I skim through the pages though I find that a fair bit of it doesn't carry over to jQuery being that my main intention is DOM manipulation.

The same can be said for Ruby and RoR. Will these books make me a better programmer overall? Probably. Can these topics help me become that much better with its framework? That's what I'm having a hard time understanding.

答:
Of course. The question is "is that benefit worth the time investment?". I would argue that it always is, but it certainly depends on you and your environment since they will impact the benefit (how much your environment will gain from your knowledge) versus the cost (how long it takes you to learn, and how well you absorb knowledge).

Why would I argue it's beneficial? Because you won't always be in the framework. Even the most comprehensive framework is still a part of a larger ecosystem. You can't make jQuery calls alone. You need to know how to bind your script into the page, how it runs, how it interacts with the stuff you want to do. That may be "basics" in your book, but I've always found that deeper knowledge helped me make code quicker, and certainly debug problems faster. Framework or not.

Beyond that, the real world has a nasty habit of intruding on programmers. Sure, your task today may be to do some DOM manipulation, but tomorrow you might need to wire up some SWFObject. Having a good foundation will let you adjust more easily to changing environments.

And lastly, even though you may only want to do DOM manipulation, very few programmers work alone anymore. Your peers will likely do more advanced things with the programming language. You'll need to be able to read that code, or at the very least, not screw it up.


答:
Previously I did a 2-month QA internship at a software company in the USA branch, but HQ was in Japan.

All of the functions and variables were written in English (though this is easier for Japanese people since they're taught English as a second language), but all of the comments and documentation were in Japanese. When we started to build on top of certain modules, we would append comments in English. It would look something like:

```<code>/*
日本語 comment
--------
English comment
*/
void doSomething() { }
</code>```

If working in an environment where everyone speaks one language, feel free to use that language. If working in an environment where two or more languages are used, it's best to use whichever language is most universally accepted by all parties, which usually ends up being English, but can be different.

Body:
Previously I did a 2-month QA internship at a software company in the USA branch, but HQ was in Japan.

All of the functions and variables were written in English (though this is easier for Japanese people since they're taught English as a second language), but all of the comments and documentation were in Japanese. When we started to build on top of certain modules, we would append comments in English. It would look something like:

/*
日本語 comment
--------
English comment
*/
void doSomething() { }

If working in an environment where everyone speaks one language, feel free to use that language. If working in an environment where two or more languages are used, it's best to use whichever language is most universally accepted by all parties, which usually ends up being English, but can be different.


问:
Are there more efficient ways to search for help/documentation than Google/SO/...?
Google sometimes come up with irrelevant links, not everything is available on SO, there are cases where the local documentation is also annoying to look through... Are there other efficient ways you use to search?</p>

答:
For programming issues I tend to look at bookmark websites using tags for example - http://www.delicious.com/tag/programming

Another resource to check out are books, sometimes a good book about a topic can give you just what you are looking for. So Google Book Search is a good way to identify the books that might be of help.