答:
If you have control over both sides, then I'd have a web service that all client sites post their price changes to.  If price changes aren't discrete (that is, if nobody just updates prices, they re-publish whole items/catalogs/whatever) then you'll have to parse whatever updates are offered to get the pricing information.  Or you could invert the structure, and have each client site offer some kind of "get latest prices" service that your central server could poll on a schedule.  Worst case, you can use a "screen scraping" approach and crawl the site, extracting prices whenever you find a product/service you want to track.

It sounds like you've only got a few distinct things to keep track of (site, "item" [whatever's got a price] and price), so almost any data store would work.  A simple relational DB (MySQL or Derby), a key-value store (like MongoDB or Cassandra), or even a spreadsheet.  I think it really depends on what you want to do with the prices once you have them.

Title: Getting and maintaining data from a large number of sources on the web

Body:
For the sake of an exercice I want to aggregate price listings with prices coming from a series of web sites in a structured form (XML, JSON...). If I have control on both sides how can I go about making price updates the most efficient possible?

Edit: To clarify, I'm looking for a more efficient approach then having a script or application pull in price lists in their entirety from all sources for updates.


问:
Do CDNs (such as MSFT and Google) act on the referrer header sent by clients?
Will my site be automatically indexed, or search ranking affected based on my use (or non use) of the Google/MSFT CDN?

My clients will be sending them the referrer header which I may or may not want included in search results.

答:
If you don't want your URLs indexed in search engines then use a robots.txt file.

If you don't want your URLs accessible by a random person who knows it exists, then use authentication.

If you don't want a random person to know that your URL exists, then don't put it on the Internet. If it's on the Internet then you have to consider that anyone could find it.

ContentLicense: CC BY-SA 3.0


问:
What is a good non-technical example of a cumulative error?
I'm working on a report which needs to explain in non-technical terms the effects of a cumulative error, and why it is of importance to use absolute calculations.

Definition of 'cumulative error' from dictionary.com:

an error that gradually increases in degree or significance during a
  series of measurements or calculations; an error that grows during
  observation

Ideally I could give a real world example so they grasp the concept of it without knowing about the specifics.

The first one I though of is 'Chinese whispers' which is pretty well known, but I wouldn't exactly classify it as 'real world'. Does anybody know of better examples?

答:
If you want something that shows accretion of errors and appears technical, then measure small things.  This is not as good as the whisper game (sometimes called the telephone game).  The whisper game is the best illustration.

Bring in a dozen small dice -- different sizes preferred.

Everyone measure 1 die.

Everyone accepts a measurement from the person on their left, adds the size of their dice and reports it to the person on their right.

The last person reports the accumulated length.

As a quality check, line the dice up and measure the entire span of dice.  See how close you are.

The problem with any measurement-based demonstration is that everyone argues that more accuracy is possible with some kind of more stringent quality controls. Non-scientists have a false belief in repeatability of measurements and the idea that you can "somehow" control all the error-inducing degrees of freedom.

Whispering shows that there are something which cannot be controlled.

Measuring merely opens you up for discussion of how to measure even more accurately.   It reduces the range of the accumulated error, but doesn't eliminate the error itself.


问:
Is it possible to write application-level logic in an XML or plain text format?
For example, a system where the developer does not need to write source code any more, instead they can using XML or some defined text to construct the application-level logic.</p>

答:
Making XML into a programming language reminds me of the many failed attempts in the aviation world to take a small automobile, add wings, tail, and propeller in order to make a flying car.

You wind up with an unsafe airplane and a crappy car.

XML is a great way to transfer data between disparate systems.  Trying to make it into a programming language is really going to be an exercise in frustration and futility.


问:
Why is it so difficult to make C less prone to buffer overflows?
I'm doing a course in college, where one of the labs is to perform buffer overflow exploits on code they give us. This ranges from simple exploits like changing the return address for a function on a stack to return to a different function, all the way up to code that changes a programs register/memory state but then returns to the function that you called, meaning that the function you called is completely oblivious to the exploit.

I did some research into this, and these kinds of exploits are used pretty much everywhere even now, in things like running homebrew on the Wii, and the untethered jailbreak for iOS 4.3.1

My question is why is this problem so difficult to fix? It's obvious this is one major exploit used to hack hundreds of things, but seems like it would be pretty easy to fix by simply
truncating any input past the allowed length, and simply sanitizing all input that you take.

EDIT: Another perspective that I'd like answers to consider - why do the creators of C not fix these issues by reimplementing the libraries?

答:
The problem isn't with the C language.

IMO, the single major obstacle to overcome is that C is just plain taught badly.  Decades of bad practice and wrong information have been institutionalized in reference manuals and lecture notes, poisoning the minds of each new generation of programmers from the beginning.  Students are given a brief description of "easy" I/O functions like gets1 or scanf and then left to their own devices.  They aren't told where or how those tools can fail, or how to prevent those failures.  They aren't told about using fgets and strtol/strtod because those are considered "advanced" tools.  Then they're unleashed on the professional world to wreak their havoc.  Not that many of the more experienced programmers know any better, because they received the same brain-damaged education.  It's maddening.  I see so many questions here and on Stack Overflow and on other sites where it's clear that the person asking the question is being taught by someone who simply doesn't know what they're talking about, and of course you can't just say "your professor is wrong," because he's a Professor and you're just some guy on the Internet.

And then you have the crowd that disdains any answer beginning with, "well, according to the language standard..." because they're working in the real world and according to them the standard doesn't apply to the real world.  I can deal with someone who just has a bad education, but anyone who insists on being ignorant is just a blight on the industry.

There would be no buffer overflow problems if the language were taught correctly with an emphasis on writing secure code.  It's not "hard", it's not "advanced", it's just being careful.

Yes, this has been a rant.

1 Which, thankfully, has finally been yanked from the language specification, although it will lurk in 40 years' worth of legacy code forever.


答:
"For want of a nail, a shoe was lost"...

"For Want of a Nail" is a proverbial rhyme showing that small actions can result in large consequences.

For Want of a Nail

For want of a nail the shoe was lost.

For want of a shoe the horse was lost.

For want of a horse the rider was lost.

For want of a rider the message was lost.

For want of a message the battle was lost.

For want of a battle the kingdom was lost.

And all for the want of a horseshoe nail.

Title: What is a good non-technical example of a cumulative error?

Body:
I'm working on a report which needs to explain in non-technical terms the effects of a cumulative error, and why it is of importance to use absolute calculations.

Definition of 'cumulative error' from dictionary.com:

an error that gradually increases in degree or significance during a
  series of measurements or calculations; an error that grows during
  observation

Ideally I could give a real world example so they grasp the concept of it without knowing about the specifics.

The first one I though of is 'Chinese whispers' which is pretty well known, but I wouldn't exactly classify it as 'real world'. Does anybody know of better examples?


问:
Does an iterator have a non-destructive implied contract?
Let's say I'm designing a custom data structure like a stack or a queue (for example - could be some other arbitrary ordered collection that has the logical equivalent of push and pop methods - ie destructive accessor methods).

If you were implementing an iterator (in .NET, specifically IEnumerable<T>) over this collection that popped on each iteration, would that be breaking IEnumerable<T>'s implied contract?

Does IEnumerable<T> have this implied contract?

eg:

```<code>public IEnumerator<T> GetEnumerator()
{
    if (this.list.Count > 0)
        yield return this.Pop();
    else
        yield break;
}
</code>```

答:
I believe a destructive Enumerator violates the Principle of Least Astonishment. As a contrived example, imagine a business object library that offers generic convenience functions. I innocently write a function that updates a collection of business objects:

```<code>static void UpdateStatus<T>(IEnumerable<T> collection) where T : IBusinessObject
{
    foreach (var item in collection)
    {
        item.Status = BusinessObjectStatus.Foo;
    }
}
</code>```

Another developer who knows nothing about my implementation or your implementation innocently decides to use both. It's likely they'll be surprised by the result:

```<code>//developer uses your type without thinking about the details
var collection = GetYourEnumerableType<SomeBusinessObject>();

//developer uses my function without thinking about the details
UpdateStatus<SomeBusinessObject>(collection);
</code>```

Even if the developer is aware of the destructive enumeration, they may not think about the repercussions when handing the collection to a black-box function. As the author of UpdateStatus, I'm probably not going to consider destructive enumeration in my design.

However, it is only an implied contract. .NET collections, including Stack<T>, enforce an explicit contract with their InvalidOperationException - "Collection was modified after the enumerator was instantiated". You could argue that a true professional has a caveat emptor attitude toward any code that is not their own. The surprise of a destructive enumerator would be discovered with minimal testing.

Body:
I believe a destructive Enumerator violates the Principle of Least Astonishment. As a contrived example, imagine a business object library that offers generic convenience functions. I innocently write a function that updates a collection of business objects:

static void UpdateStatus<T>(IEnumerable<T> collection) where T : IBusinessObject
{
    foreach (var item in collection)
    {
        item.Status = BusinessObjectStatus.Foo;
    }
}

Another developer who knows nothing about my implementation or your implementation innocently decides to use both. It's likely they'll be surprised by the result:

//developer uses your type without thinking about the details
var collection = GetYourEnumerableType<SomeBusinessObject>();

//developer uses my function without thinking about the details
UpdateStatus<SomeBusinessObject>(collection);

Even if the developer is aware of the destructive enumeration, they may not think about the repercussions when handing the collection to a black-box function. As the author of UpdateStatus, I'm probably not going to consider destructive enumeration in my design.

However, it is only an implied contract. .NET collections, including Stack<T>, enforce an explicit contract with their InvalidOperationException - "Collection was modified after the enumerator was instantiated". You could argue that a true professional has a caveat emptor attitude toward any code that is not their own. The surprise of a destructive enumerator would be discovered with minimal testing.


答:
Do you know why we use the Gregorian calendar today in most of the western parts of the world? It is because its predecessor, the Julian calendar, made a cumulative error over the years. Read this Wikipedia article for the details:

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


答:
Few years ago we had a customer that wanted to use existing surveillance cameras to keep track of how many people are in the building at any given time.

Our company had object counting video analytics algorithm but it was only 98% accurate. Generally, it would be used to estimate traffic flow patterns, not keep track of precise counts.

So this customer had an acceptance test to run the algorithm for one day.  At the beginning of the day, the building is almost empty (few security guards, some night people). 24 hours later it is also supposed to be almost empty. During the day several thousand people enter and exit.  They came back and said that our algorithm had astronomical percent error because whatever counting error accumulated during the day, they simply divided that by expected number of people which was very low.


问:
IRC Bot permission structure, best approach?
I'm making an IRC bot in PHP. And I've come to the point when I need to determine how would user permissions/accesses would look in the database (and in the application in general).

Here are the requirements:

There are global and local permissions, global are for all channels, while local are channel specfiic.

There are permissions such as "root", "bot_admin" "glob_op" "op on #channel", in this example, each is weaker than the last (root is strongest, meaning that no one can take actions against root).

I haven't completely decided on exactly how many permissions are there, and the bot will be extensible, so there needs to be an option of expanding.

Some approaches I had in mind:

Assign each permission level a number (1, 2, 4, 8, 16) and add them together to form the access level of a specific user (even adding all of the numbers until n-1, they would still be lower than n). As for expanding, I could leave gaps (1, 16, 256, etc) and fill it in later. I don't think it's a very good one, as it would be hard to maintain and read later on, even if I use constants to make it more readable.

Have each permission in its own boolean column. That seems just silly, and there's no easy way of determining the power relations between each role.

So what say you? Have a better approach I can take?

答:
I like not relying on the schema of the database too much. It makes later changes harder.

I would have one Table

```<code>users: <user-id> <user name>
</code>```

another Table

```<code>local-permissions: <user-id> <channel(-id)> <permission>
</code>```

and yet another Table:

```<code>global-permissions: <user-id> <permission>
</code>```

I would use a String column for permission, if you want you can use a database-check for allowed values. It's easier to read and write if you're manipulating the database directly (which you will at some point).

Since you want multiple permissions, put multiple rows in the tables and then figure out the hierarchy in the application.

If you want to make it more visible which permissions a particular user has, you can also go for just one row/entry and separate them by space in the column like that: "op kick ban" (be fault-tolerant in the application for that!).

It doesn't seem pretty, but as i said, i'd rather have the schema/data-interpretation in the application then in the database.

Body:
I like not relying on the schema of the database too much. It makes later changes harder.

I would have one Table

users: <user-id> <user name>

another Table

local-permissions: <user-id> <channel(-id)> <permission>

and yet another Table:

global-permissions: <user-id> <permission>

I would use a String column for permission, if you want you can use a database-check for allowed values. It's easier to read and write if you're manipulating the database directly (which you will at some point).

Since you want multiple permissions, put multiple rows in the tables and then figure out the hierarchy in the application.

If you want to make it more visible which permissions a particular user has, you can also go for just one row/entry and separate them by space in the column like that: "op kick ban" (be fault-tolerant in the application for that!).

It doesn't seem pretty, but as i said, i'd rather have the schema/data-interpretation in the application then in the database.


问:
Simple explanation of the Unix sockets
I can search and I've already looked at the wikipedia entry and in some other places, but even though I have some programming experience, I don't really grasp the concept. Can you treat me like a 10 year old and give me a clear explanation on socket communication?</p>

答:
Unix sockets are a bidirectional socket - just like an IP based socket, which you are probably familiar with, and kind of similar to a pipe, which you are probably familiar with.

They have a small set of interesting properties:

They are in the domain of "the local host" only - you can't access them over the network, only on the local machine.

You can create them in "stream" mode, where they just pass data like a pipe as a stream of bytes.

You can create them in "datagram" mode, where they retain boundaries between send operations.  This allows you to retain framing without building your own framing protocol on top of a byte stream.

They use the filesystem, or on Linux, an "abstract namespace", as their "address"

You may be able to impersonate the other end, securely identify the connecting software, or pass file handles over the socket, depending on your OS.

Essentially, they are the equivalent of any other socket - they have slightly more interesting properties than pipes, but are not radically different otherwise.  They do typically have higher IPC latency than a pipe does, and often larger buffers - though you may be able to tune that, and it depends on the platform.

The final interesting property to remember is that they use the filesystem as their namespace - so are like a named pipe, rather than an anonymous pipe, in that software with no previous relationship can communicate.  (Abstract namespace sockets are the same, but the "file" path doesn't have to exist.)

There isn't anything deeper than that - they don't have any super-secret hidden property that makes them radically different from a typical pipe, or a TCP connection to localhost.

Title: Simple explanation of the Unix sockets


问:
How can I sell my boss on Python+Django instead of PHP+a different framework?
My boss has tasked me with a re-write of our intranet website. The existing system is very old PHP that doesn't use a framework. My preference is strongly to do the rewrite in Python and Django but my boss does not like Python syntax (he is also a developer). I'm on the opposite end... I don't like developing in PHP and my PHP experience is extremely limited but I've done a lot of work in Python. My boss is aware of my experience but still wants me to sell him on Python.

Some of the things he mentioned he does not like about Python:

indentation is the only marking for the begin/end of a code block (he loves his curly braces)

documentation issues (I told him python documentation is great)

IDE support is limited (mentioned PyCharm and Wing IDE, not sure which is better)

he's had compatibility issues moving between older versions of python

He may be the only other pair of eyes on the new code. How can I convince him that Python is a better choice? Is Ruby a potential middle ground?

答:
Well, the IDE issue is easy to address. Eclipse with the Aptana 3 plugin is a fine Django IDE. It even has syntax highlighting for Django templates.

Backward and forward compatibility issues are of course not unique to Python or Django. If this is a concern, however, then you might consider Web2Py instead of Django. Web2Py makes it a goal to always maintain backward compatibility, and has since its release in 2007. It still works with Python 2.5 (which was released in 2006) too.

Documentation for Python's standard and third party libraries are indeed usually great. I really can't address your boss's problems with it until I know where the problems are coming from.


答:
How can I convince him that Python is a better choice?

You can't.  All of your boss's complaints are trivial matters of personal preference.

He loves his curly braces. Python uses significant whitespace, which not everyone agrees with. However this is personal preference.

You can show that everyone does indentation correctly. You can find people who will tell you that they can't indent properly.  Even though all of their code is indented correctly.

In PHP you're going to indent correctly anyway.

Documentation issues?  What can this even mean?  If you boss perceives Python documentation as less good than PHP, this, too is a lost cause.  It's just perception.

You can show the entire Python library documentation set.  They can then say it's too big.  Or the wrong color.  Or the wrong font.  There are always new "documentation issues".

IDE support is limited?  Yep.  If they've decided it's limited; you'll have a hard time.

You can show Eclipse or Komodo.  Even if you show how Eclipse works, your boss will (eventually) notice that an IDE for a  dynamic language doesn't do code completion well and complain.

He's had compatibility issues moving between older versions of python. There are issues with Python 3, but 2.7 should be around for more then enough time.

Even if you get the specific example of incompatibility, you can't go very far down this road.  They'll merely say that the Python 3 lack of backward compatibility is a deal-breaker.

Every language, platform and operating system has compatibility issues from time-to-time.  You can find (and document) a dozen PHP compatibility issues (starting with the PHP5 issue) and that won't convince anyone who's in favor of PHP and not in favor of Python.

If your boss doesn't like Python, nothing will change their mind except an epic failure using PHP.  And it has to be an epic failure that stems -- directly -- from the use of PHP.

Consider this actual quote from an actual question.

I've already dabbled into Python and bought books, but I found its syntax too abstract (too much like pseudocode) and too strict.

Python is both too flexible and too strict. At the same time.

Is Ruby a potential middle ground?

Middle Ground?  The idea doesn't make sense.  It's all or nothing for a particular technology.  Finding something like Ruby that neither of you like is awful.

If you really don't like PHP, consider finding another job where you don't have to use it.

Title: How can I sell my boss on Python+Django instead of PHP+a different framework?

Body:
My boss has tasked me with a re-write of our intranet website. The existing system is very old PHP that doesn't use a framework. My preference is strongly to do the rewrite in Python and Django but my boss does not like Python syntax (he is also a developer). I'm on the opposite end... I don't like developing in PHP and my PHP experience is extremely limited but I've done a lot of work in Python. My boss is aware of my experience but still wants me to sell him on Python.

Some of the things he mentioned he does not like about Python:

indentation is the only marking for the begin/end of a code block (he loves his curly braces)

documentation issues (I told him python documentation is great)

IDE support is limited (mentioned PyCharm and Wing IDE, not sure which is better)

he's had compatibility issues moving between older versions of python

He may be the only other pair of eyes on the new code. How can I convince him that Python is a better choice? Is Ruby a potential middle ground?


问:
Why was dependency injection pattern not included in the Gang of four?
Why was the dependency injection pattern not incluided in the gang of four? Did GOF pre-date widespread automated testing? Is dependency injection now considered a core pattern?</p>

答:
I was Editor of Software Development magazine when the Gang of Four book came out and I can say with total confidence that unit-testing was not a widespread practice in 1994, when Design Patterns was originally published.

In 1994, C++ was the most commonly used object-oriented language, and most people programming it were coming from a C background. One of the "thinking in objects" things that people simply didn't have is the idea of hundreds or thousands of entry points into your program. You thought about the main(). If you worked on a large project, you might have a (usually quite elaborate) makefile to create a module-based program. But "unit-testing"? Starting a process, building the necessary memory context, executing it, and tearing it down, on a per method basis? That was very radical.

Java made multiple-entry-point programming more obvious. By the time of the original Dot-Com boom, unit-testing was a well-known technique, but it was really JUnit (circa 2001?) that caused it to catch fire and become a universal practice.

Although Strategy and the general concept of programming to an interface were part of GoF and the mid-90s zeitgeist, the idea of injection came quite late to the party (circa '03-'05?). Honestly, my gray hairs are still quite dubious about that aspect of DI ("Get off my lawn, you darn configuration files!").


问:
When is it not appropriate to use the dependency injection pattern?
Since learning (and loving) automated testing I have found myself using the dependency injection pattern in almost every project. Is it always appropriate to use this pattern when working with automated testing? Are there any situations were you should avoid using dependency injection?</p>

答:
An alternative to Dependency Injection is using a Service Locator.  A Service Locator is easier to understand, debug, and makes constructing an object simpler especially if you aren't using a DI framework.  Service Locators are a good pattern for managing external static dependencies, for instance a database that you would otherwise have to pass into every object in your data access layer.

When refactoring legacy code, it is often easier to refactor to a Service Locator than to Dependency Injection.  All you do is replace instantiations with service lookups and then fake out the service in your unit test.

However, there are some downsides to the Service Locator.  Knowing the depandancies of a class is more difficult because the dependencies are hidden in the class's implementation, not in constructors or setters.  And creating two objects that rely on different implementations of the same service is difficult or impossible.

TLDR: If your class has static dependencies or you are refactoring legacy code, a Service Locator is arguably better than DI.


答:
One of the most interesting coding challenges given to me for an interview was to create a functional queue. The requirement was that each call to enqueue would create a new queue that containted the old queue and the new item at the tail. Dequeue would also return a new queue and the dequeued item as an out param.

Creating an IEnumerator from this implementation would be nondestructive. And let me tell you implementing a Functional Queue that performs well is a lot more difficult than implementing a performant Functional Stack (stack Push/Pop both work on the Tail, for a Queue Enqueue works on the tail, dequeue works on the head).

My point being...it's trivial to create a nondestructive Stack Enumerator by implementing your own Pointer mechanism (StackNode<T>) and using functional semantics in the Enumerator.

```<code>public class Stack<T> implements IEnumerator<T>
{
  private class StackNode<T>
  {
    private readonly T _data;
    private readonly StackNode<T> _next;
    public StackNode(T data, StackNode<T> next)
    {
       _data=data;
       _next=next;
    }
    public <T> Data{get {return _data;}}
    public StackNode<T> Next{get {return _Next;}}
  }

  private StackNode<T> _head;

  public void Push(T item)
  {
    _head =new StackNode<T>(item,_head);
  }

  public T Pop()
  {
    //Add in handling for a null head (i.e. fresh stack)
    var temp=_head.Data;
    _head=_head.Next;
    return temp;
  }

  ///Here's the fun part
  public IEnumerator<T> GetEnumerator()
  {
    //make a copy.
    var current=_head;
    while(current!=null)
    {
       yield return current.Data;
       current=_head.Next;
    }
  }
}
</code>```

Some things to note. A call to push or pop before the statement current=_head; completes would give you a different stack for enumeration than if there were no multithreading (you might want to use a ReaderWriterLock to safeguard against this). I made the fields in StackNode readonly but of course if T is a mutable object, you can change its values. If you were to create a Stack constructor that took a StackNode as a parameter (and set head to that passed in node). Two stacks constructed in this way will not impact each other (with the exception of a mutable T as I mentioned). You can Push and Pop all you want in one stack, the other will not change.

And that my friend is how you do non-destructive enumeration of a Stack.

Title: Does an iterator have a non-destructive implied contract?

Body:
Let's say I'm designing a custom data structure like a stack or a queue (for example - could be some other arbitrary ordered collection that has the logical equivalent of push and pop methods - ie destructive accessor methods).

If you were implementing an iterator (in .NET, specifically IEnumerable<T>) over this collection that popped on each iteration, would that be breaking IEnumerable<T>'s implied contract?

Does IEnumerable<T> have this implied contract?

eg:

```<code>public IEnumerator<T> GetEnumerator()
{
    if (this.list.Count > 0)
        yield return this.Pop();
    else
        yield break;
}
</code>```

Body:
One of the most interesting coding challenges given to me for an interview was to create a functional queue. The requirement was that each call to enqueue would create a new queue that containted the old queue and the new item at the tail. Dequeue would also return a new queue and the dequeued item as an out param.

Creating an IEnumerator from this implementation would be nondestructive. And let me tell you implementing a Functional Queue that performs well is a lot more difficult than implementing a performant Functional Stack (stack Push/Pop both work on the Tail, for a Queue Enqueue works on the tail, dequeue works on the head).

My point being...it's trivial to create a nondestructive Stack Enumerator by implementing your own Pointer mechanism (StackNode<T>) and using functional semantics in the Enumerator.

public class Stack<T> implements IEnumerator<T>
{
  private class StackNode<T>
  {
    private readonly T _data;
    private readonly StackNode<T> _next;
    public StackNode(T data, StackNode<T> next)
    {
       _data=data;
       _next=next;
    }
    public <T> Data{get {return _data;}}
    public StackNode<T> Next{get {return _Next;}}
  }

  private StackNode<T> _head;

  public void Push(T item)
  {
    _head =new StackNode<T>(item,_head);
  }

  public T Pop()
  {
    //Add in handling for a null head (i.e. fresh stack)
    var temp=_head.Data;
    _head=_head.Next;
    return temp;
  }

  ///Here's the fun part
  public IEnumerator<T> GetEnumerator()
  {
    //make a copy.
    var current=_head;
    while(current!=null)
    {
       yield return current.Data;
       current=_head.Next;
    }
  }
}

Some things to note. A call to push or pop before the statement current=_head; completes would give you a different stack for enumeration than if there were no multithreading (you might want to use a ReaderWriterLock to safeguard against this). I made the fields in StackNode readonly but of course if T is a mutable object, you can change its values. If you were to create a Stack constructor that took a StackNode as a parameter (and set head to that passed in node). Two stacks constructed in this way will not impact each other (with the exception of a mutable T as I mentioned). You can Push and Pop all you want in one stack, the other will not change.

And that my friend is how you do non-destructive enumeration of a Stack.


问:
How to improve programming environment for optimal productivity?
As a beginner programmer I find myself spending hours and sometimes even days on my desk reading code, writing code, focusing, getting headaches and whatnot.

I've documented myself on computer health and such, purchased an ergonomic keyboard & mouse, however since I wish to take a career in programming, this question keeps coming in my mind.

We all know programming is a tough job especially from a health point of view. Programmers spend hours and sometimes don't even sleep, they develop health problems and eating disorders because they have to get the job done. My example could be purely unique.

The question however is not necessarily for health as it is for productivity. I've read articles which said therapy music could help your brain think sharper and be more productive. The real question is, as the title suggests (hint hint): how to improve programming environment for optimal productivity? Are there any specific rules I should be following when programming to help me focus and keep my mind sharp so I develop better code?

答:
Don't kill yourself "to get the job done." Nothing will reduce your productivity more than burnout. Eight to ten hours a day of programming is about the maximum that a normal person can do before hitting the point of diminishing returns.

Take breaks. This may seem counter-intuitive, but you really need to get up and move about occasionally to avoid falling into a stupor. Stepping away from a particularly tough problem will often give you the key to solving it. Moderate-to-vigorous exercise will also freshen-up your brain.

See number 1. Again and again.


问:
Trying to do some Obfuscation, How should I approach this particular case?
I currently have an assignment that is really pushing my limits so I need some help on how to approach this.

We have a set of 25 results

We are using a jquery plugin to vertically scroll through these 25 results, the container displays five results at a time.

When viewing the source code of the page, you can see the html for all 25 results. Obviously the jquery plugin is what is making them visible or not.

The task is to make it so that only five of the result set are displaying at any time during a source code viewing. All the rest of the results must come from javascript or some other technique.

So I somehow have to either:

Send a pool of 25 results to JS and have it generate the div info on the fly
OR

Some type of timed script that grabs five results at a time and displays them. But this all has to continuously scroll vertically so that is a consideration also.

So I am trying to get my head around how I should approach this: One idea I had was to run an ajax call every five or ten seconds that has a php script generate five new results, then display them in the appropriate div. This is slow and would basically mean a page that is constantly sending out ajax calls. the random results are coming from a php script that is parsing an xml feed.

I am really just looking for a roadmap or some conceptual directions on how this could be approached.

答:
This is not a Obfuscation issue. Obfuscation is when you let the user see the code but try to make it difficult to understand.

I think your option 1 works best.

Don't load any of the results to the Page using server side code that generates HTML.
Make an AJAX Call to dynamically get and add the results to the page at run time.
Since you are Uning JQuery See jQuery.ajax()

NOTE: There is no way to allow a Good hacker to viewing your results on screen while eliminating his ability to programtically get the results.


问:
In javascript and other languages which lack a compiler, is unit testing a good method to ensure correct syntax and variable naming?
I've been working on a medium sized web application that makes very heavy use of javascript.  I tend to introduce common errors per 10 lines of code with either an unknown variable name or function name from another module\namespace or forgetting a return and other common errors.

I'm noticing I'm getting quite a lot of feedback in fixing these errors as a side effect of my qunit testing.  Is unit testing a typical way to make up for a compiler in dynamic languages?

答:
First of all I would run JSLint over your code religiously. you should be able to get your editor or IDE to do it for you, use Flymake mode in Emacs. That will catch things like typos when you miss type a variable name.

Having good tests will also of course help. I have used qUnit to write tests in Javascript and have been pretty happy with it. Jasmine also is supposed to be pretty good.

As an aside this has to do with dynamic typing not a lack of a compiler, there are a number of languages that are compiled but are still weekly typed (Scheme and Erlang come to mind)


问:
How do you handle constantly changing database dimensions?
For the last two months or so I have been looking for solutions or practices to handle release management within databases.  I'm looking for what people view as the best process for handling this.

We have 3 environments for our databases:

Development

User Acceptance Testing (UAT)

Production

The problem is sometimes we are making changes to several things within our development database and come time to deploy, some of the features may not be ready to be released to UAT.

Recently we have started using Red Gate SQL Source control for storing all of our entities (with regular commits).

I was thinking of going based off of changesets (i.e. say everything from changeset X and back is now being pushed to UAT) however, this means that people are only checking their code into source control just before we do a deploy which can get confusing (especially since people are forgetful).  Another issue with going with the changeset approach is if there is a bug in a stored procedure that needs to be fixed, the changeset number would end up being out of scope of our max changeset for the revision therefore making it so that if we need to recreate the database off of a maximum changeset, we would be pushing the bug out again.

Any suggestions on a process?

Thanks

答:
Following up with the suggestion of using migrations...perhaps use an O/RM that supports Migrations like Ruby on Rails and Entity Framework 4.3 The problem with both approaches however is that a migration is all or nothing. You can't (usually) select which Migrations are applied like you can in terms of change sets.

Another viable option (if you're on the microsoft stack, you never mentioned the platform) is to manage your SQL with the Visual Studio Database tools. It has built in refactoring (rename/remove columns, etc.) and does verification of the model. If for example, a stored proc references a column that's no longer there, it will inform you.

OwnerDisplayName: judda


问:
How can I quantify the amount of technical debt that exists in a project?
Does anyone know if there is some kind of tool to put a number on technical debt of a code base, as a kind of code metric?  If not, is anyone aware of an algorithm or set of heuristics for it?

If neither of those things exists so far, I'd be interested in ideas for how to get started with such a thing.  That is, how can I quantify the technical debt incurred by a method, a class, a namespace, an assembly, etc.

I'm most interested in analyzing and assessing a C# code base, but please feel free to chime in for other languages as well, particularly if the concepts are language transcendent.

答:
I think the question is how much would it cost to "buy back" your technical debt--that is, how much work is it to fix it?  Well, it's up to the team to figure that out.

During sprint planning, I ask the team to estimate the complexity of fixing technical debt items in the same way they would estimate the complexity of a user story.  At that point, it's a negotiating game between the team an the product owner to determine which technical debt is high enough priority to be done in the current sprint (displacing actual user stories) and what can wait.

If you're not doing scrum, I'd stick to my premise--technical debt should be measured by the cost of the remedy.


问:
Does commentary style affect how readers understand code?
This question has been obsessing me for the past 2 months.

A while ago a friend who is a great programmer gave me some example codes, and for the first time I've noticed a unique style of organizing comments. He took some effort to design comments in a way that would make me more comfortable with the code itself. For example:

```<code>/////////////////////////////////////////////                                                   //                                             //
//  This code prints a basic "Hello world" //
// message to the console screen. You can  //
// change the text in the brackets.        //
//                                         //
/////////////////////////////////////////////

#include <iostream>

int main() {
  cout << "Hello world";

}
</code>```

when he could have simply written

```<code>/* This code prints a basic "Hello world" message to the console, change text in brackets */

 #include <iostream>

int main() {
  cout << "Hello world";

}
</code>```

This kind of example only on a bigger scale. I find this a little unproductive in professional situations but in a learning situation, it seems ideal.

The question here is, if comment style affects how the reader understands code. In my personal opinion option #1 is prettier to the eye and easier to follow than #2. Does the way you comment on code affect ones ability to comprehend your code, or is it just wasted time and space?

答:
The example you give is a bit extreme, but yes, comments have a very important function.

The writer of the code has a mental model of what it needs to do.
The comments serve to

communicate to the reader what that mental model is, and

express the mapping between the mental model and how the code implements it.

That way, if requirements change, it is more likely that the corresponding changes to the code can be made correctly, either by the original author or anyone who comes along later.

It is also good to try to write the code in such a way that it explains itself,
but that is seldom 100% successful, so the comments are necessary.


答:
Yes

The layout of a program from a whitespace and comment perspective will have a great impact on how well a developer can read your code.

Prettier to the eye and more easy to follow are subjective and will not be the same for every programmer.

That being said, some developers prefer to see more code on the screen at once, while others prefer to have more whitespace/comments.

At the end of the day, you will be more comfortable reading code that you are used to reading.

Uncle Bob Martin, author of Clean Code makes the argument that comments are frequently used to excuse bad code and should be avoided whenever possible.  Instead your code itself should be readable and organized well enough to allow another developer to easily pick it up and begin working.

Title: Does commentary style affect how readers understand code?

Body:
This question has been obsessing me for the past 2 months.

A while ago a friend who is a great programmer gave me some example codes, and for the first time I've noticed a unique style of organizing comments. He took some effort to design comments in a way that would make me more comfortable with the code itself. For example:

```<code>/////////////////////////////////////////////                                                   //                                             //
//  This code prints a basic "Hello world" //
// message to the console screen. You can  //
// change the text in the brackets.        //
//                                         //
/////////////////////////////////////////////

#include <iostream>

int main() {
  cout << "Hello world";

}
</code>```

when he could have simply written

```<code>/* This code prints a basic "Hello world" message to the console, change text in brackets */

 #include <iostream>

int main() {
  cout << "Hello world";

}
</code>```

This kind of example only on a bigger scale. I find this a little unproductive in professional situations but in a learning situation, it seems ideal.

The question here is, if comment style affects how the reader understands code. In my personal opinion option #1 is prettier to the eye and easier to follow than #2. Does the way you comment on code affect ones ability to comprehend your code, or is it just wasted time and space?


问:
How can I bootstrap a software development community at my school?
I'm a student at the University of South Florida who's frustrated with the educational environment in the Computer Science program. Right now, I'm taking "Program Design." I should be learning how to organize my source code into functions and modules in order to make my programs readable and maintainable; instead, I'm learning about arrays and recursion in C. Next semester, I have to take "Object-Oriented Design," which is taught through C++ (shudder.)

Two years ago, I fell in love with programming, and I've been learning as much as I could since then. The prospect of taking another C++ class bores me almost to tears. For that reason, I thought I would start a programming club in order to meet similarly ambitious students, learn new languages, discuss software development topics, and work with other students developers.

However, I'm beginning to realize that there may not be any other students who share my software development experience. It's not because of a lack of motivation but a lack of opportunity: I know of only one other programming class ("Programming Languages") and no classes on real-world software development. Everybody else only has experience writing trivial scripts in C and C++.

I've realized that if I want to work with other student software developers, I'm going to have to train them myself. Now, I'm planning to make the club a software development bootcamp, teaching members how to develop software with modern tools and languages. Obviously, starting an unofficial software development course is a monumental task with many possible approaches. My question to you, dear reader, is

What's my plan of attack?

Should I

lecture the club myself, trying to balance club work with homework?

ask the CS faculty to teach on topics within their expertise which may be less than relevant to members?

try to find a sympathetic, experienced developer inside or outside the school who can share my workload?

show video lectures (from MIT OpenCourseWare, Google Tech Talks, etc)?

hold hands-on programming workshops?

assign homework?

do something else?

答:
The group project is a great idea. Especially if the project is something that can help out the university, or your fellow classmates.

I joined a group while in college that was working on projects for students.

The most popular project was a 360 degree virtual tour of the campus.

We purchased the equipment needed and started taking photos around campus.  Then we built a website to house the tour, figured out the hosting, and got it featured on the university's web site for prospective students. This project spanned more than just programming tasks, and got non-programmers interested as well.

Try identifying a new website or application that not only you would use, but everyone on campus would like to use.  I think it's easier and more fun to learn if you have a goal in mind.

ContentLicense: CC BY-SA 2.5


答:
Yes, commenting style affects readability (how can it not?), but I would argue that the example you gave is a very poor style. Excessive formatting is just that: excessive.

Writing good comments is a skill to be practiced and refined, just like writing code.


答: I'd say the standard code metrics can be used as a high-level relative view of technical indebtedness. VS Ultimate includes a Code Analyzer that will give you a "Maintainability Index" based on Cyclomatic Complexity, Coupling, LoC, and Depth of Inheritance. You can dive down into any trouble spots and see details (down to the function level). I just ran it on my project and the lowest scores we got were 69 on our Data package (configuring and initializing EF) and our Test Suite. Everything else was 90 or above. There are other tools that will give you more metrics like those discussed in Uncle Bob's PPP

Title: How can I quantify the amount of technical debt that exists in a project?

Body:
Does anyone know if there is some kind of tool to put a number on technical debt of a code base, as a kind of code metric?  If not, is anyone aware of an algorithm or set of heuristics for it?

If neither of those things exists so far, I'd be interested in ideas for how to get started with such a thing.  That is, how can I quantify the technical debt incurred by a method, a class, a namespace, an assembly, etc.

I'm most interested in analyzing and assessing a C# code base, but please feel free to chime in for other languages as well, particularly if the concepts are language transcendent.


答:
Technical debt is just an abstract idea that, somewhere along the lines of designing, building, testing, and maintaining a system, certain decisions were made such that the product has become more difficult to test and maintain. Having more technical debt means that it will become more difficult to continue to develop a system - you either need to cope with the technical debt and allocate more and more time for what would otherwise be simple tasks, or you need to invest resources (time and money) into reducing technical debt by refactoring the code, improving the tests, and so on.

There are a number of metrics that might give you some indication as to the quality of the code:

Code coverage. There are various tools that tell you what percentage of your functions, statements, and lines are covered by unit tests. You can also map system and acceptance tests back to requirements to determine the percentage of requirements covered by a system-level test. The appropriate coverage depends on the nature of the application.

Coupling and cohesion. Code that exhibits low coupling and high cohesion is typically easier to read, understand, and test. There are code analysis tools that can report the amount of coupling and cohesion in a given system.

Cyclomatic complexity is the number of unique paths through an application. It's typically counted at the method/function level. Cyclomatic complexity is related to the understandability and testability of a module. Not only do higher cyclomatic complexity values indicate that someone will have more trouble following the code, but the cyclomatic complexity also indicates the number of test cases required to achieve coverage.

The various Halstead complexity measures provide insight into the readability of the code. These count the operators and operands to determine volume, difficulty, and effort. Often, these can indicate how difficult it will be for someone to pick up the code and understand it, often in instances such as a code review or a new developer to the code base.

Amount of duplicate code. Duplicated code can indicate potential for refactoring to methods. Having duplicate code means that there are more lines for a bug to be introduced, and a higher likelihood that the same defects exist in multiple places. If the same business logic exists in multiple places, it becomes harder to update the system to account for changes.

Often, static analysis tools will be able to alert you of potential problems. Of course, just because a tool indicates a problem doesn't mean there is a problem - it takes human judgement to determine if something could be problematic down the road. These metrics just give you warnings that it might be time to look at a system or module more closely.

However, these attributes focus on the code. They don't readily indicate any technical debt in your system architecture or design that might relate to various quality attributes.


答:
Sonar has a technical debt heuristic as well as several other features useful to a software project.

It also supports a pretty wide range of languages.

SonarQube (formerly Sonar) is an open source platform for Continuous Inspection of code quality...

Support 25+ languages: Java, C/C++, C#, PHP, Flex, Groovy, JavaScript, Python, PL/SQL, COBOL, etc.

SonarQube is also used in Android Deveopment.

Offers reports on duplicated code, coding standards, unit tests, code coverage, complex code, potential bugs, comments and design and architecture.

Time machine and differential views.

Fully automated analyses: integrates with Maven, Ant, Gradle and continuous integration tools (Atlassian Bamboo, Jenkins, Hudson, etc.).

Integrates with the Eclipse development environment

Integrates with external tools: JIRA, Mantis, LDAP, Fortify, etc.

Expandable with the use of plugins.

Implements SQALE methodology to compute technical debt...


答:
How can I convince him that Python is a better choice?

It seems you're having a battle of personal preferences with your boss.  You havent provide here a single reason why, from a business & development perspective, you think Python would be better than PHP.  So if you want to work in Python, provide those reasons.  And I'll give you a hint - that you simply prefer the syntax isnt a valid business reason.  He obviously prefers PHP's syntax, and the tie breaker usually goes to the boss...


答:
I hate to use an analogy from finance but it seems really appropriate.  When you're pricing something (assets of any kind), it can have both intrinsic and extrinsic value.  In this case, the existing code has intrinsic value which would be a quantity corresponding to the relative quality of said code and it would also have extrinsic value (value from what could be done to the code) and those quantities would be additive.  The intrinsic value can be broken down into credits and debits (good vs. bad) using whatever methodology you're using to score the code (+5 for comments/readability, -10 for code coverage, etc.)

I certainly don't know of any tools that quantify this today and I think you'd have an entirely new discussion on your hands if you argue the merits of different "debt valuation" strategies but I agree with Matthew -- the debt is the cumulative cost of getting the code as good as you can possibly get it, using whatever method you use to cost out the man-hours it takes to get there.

Something else to consider is that there is certainly a measure of cost-effectiveness whereby as one gets closer to "perfection", the value of an hour spent on the code base is more than likely decreasing exponentially so there is probably an additional optimization problem to maximize utility of the work done.


答:
If this is going to be an extra-curricular activity, don't do the homework thing. That's just lame.

You could probably get something cool going by just starting up a github group and postering/emailing in your school (I guess kids these days use Facebook and Twitter too? Might be a good idea to hit those points as well). When you get a group of 5-6 people who are really interested together, decide on a project and just work at it.

If there's no interest, it's pretty ridiculously easy to join an open source project if you're reasonably skilled. Simple as forking something you're interested in at github, and starting to talk to the developers.

The advantage you have that the previous generation didn't is that it's not difficult at all to connect to programmers at your level, and in your language, while being very geographically disparate. And I don't mean just send an email. Skype/iChat/Ventrilo make voice conferences easy, tools like git/mercurial (and the associated project pages online) make it easy to code as a group even if you're on opposite sides of the atlantic. There's really no reason not to code socially these days, if that's what you want to do.

Finally, don't make a habit of judging people by the languages they know/want to know. It's an easy trap to fall into when you're the only Smalltalker in a herd of people who think C++ represents the limit of programming, but it won't get you many friends, and it'll give you a bias against certain tools. I've met hackers who are miles ahead of me in skill and experience, who have used LISP, Perl and C on the same project. The people at the top of the professional developer heap tend to not care much what level their tools are as long as they do the job.

Title: How can I bootstrap a software development community at my school?

Body:
I'm a student at the University of South Florida who's frustrated with the educational environment in the Computer Science program. Right now, I'm taking "Program Design." I should be learning how to organize my source code into functions and modules in order to make my programs readable and maintainable; instead, I'm learning about arrays and recursion in C. Next semester, I have to take "Object-Oriented Design," which is taught through C++ (shudder.)

Two years ago, I fell in love with programming, and I've been learning as much as I could since then. The prospect of taking another C++ class bores me almost to tears. For that reason, I thought I would start a programming club in order to meet similarly ambitious students, learn new languages, discuss software development topics, and work with other students developers.

However, I'm beginning to realize that there may not be any other students who share my software development experience. It's not because of a lack of motivation but a lack of opportunity: I know of only one other programming class ("Programming Languages") and no classes on real-world software development. Everybody else only has experience writing trivial scripts in C and C++.

I've realized that if I want to work with other student software developers, I'm going to have to train them myself. Now, I'm planning to make the club a software development bootcamp, teaching members how to develop software with modern tools and languages. Obviously, starting an unofficial software development course is a monumental task with many possible approaches. My question to you, dear reader, is

What's my plan of attack?

Should I

lecture the club myself, trying to balance club work with homework?

ask the CS faculty to teach on topics within their expertise which may be less than relevant to members?

try to find a sympathetic, experienced developer inside or outside the school who can share my workload?

show video lectures (from MIT OpenCourseWare, Google Tech Talks, etc)?

hold hands-on programming workshops?

assign homework?

do something else?


答: I wouldn't think of technical debt as dollars where you need a fancy model to quantify it.  I would think of it as favors.  If someone does you a favor and you are likely to forget, you write it down.  When you take a short cut, write it down.  This helps you remember, and more impotent forces you to acknowledge it.  No fancy tool is needed.  Notepad or Ecxel can do the trick.</p>


问:
Would it be hard to screen form submissions (e.g., comments) for non-words/non-sentences?
I've been thinking a lot lately about the need for better form security, and good ways to accomplish that.

We currently use captcha codes to screen for bots, but that's annoying to users and may not work forever.

I think that we need a more intuitive, organic system for screening bad comments/contact form submissions.

One option that has come to mind would be trying to screen comments for things that are obviously not words, in addition to screening for duplicate comments.  E.g., when a spammer on Facebook, Twitter, or a comments section is stopped from just posting the same thing a lot of times, they add garbled letters and or numbers somewhere in the post to make it "unique".

If it was possible to screen out obvious not-text, this could be overcome. If you could go a step further, and screen out posts that obviously have words placed in for no reason except to make the post "unique", you could force the spammer/scam artist down to only use repetitive post options which actually make gramatical sense.

At the very least, you could have posts be flagged for moderator attention if they looked similar but which just had random garbage added in for no reason. This would significantly reduce a spammer's ability to keep spamming, even across multiple accounts.

Could it be possible to screen form field results for random word and number combinations, and words thrown in just to make a post "unique"?

答:
You can borrow various Bayesian filters from email apps. There are some open source ones around that you can learn from and build your own implementation. The problem is that asute spammers use the same code to build their text generation apps to avoid the filters.

The best way I've found to prevent most automated spamming and to avoid the user experience problems with CAPTCHA is to have an AJAX validation method that will thwart bots and degrade gracefully to use server side code for non-Javascript users. This won't help with paid manual spamming where somebody in a third world Internet cafe gets paid $5 to put a link on X number of sites though.

What I've found is that combining the script on the front end with automated moderation on the backend (flagging certains words and phrases, posts with links and so forth) stops about 99.9% of spam attempts. The only ones that get through are ones that are well done manual ones and those are quite rare.


问:
How do we call a concept when my acceptor loop is ran by some real application while all services are plugins for that application?
So say we have an app (server) that somehow attaches to itself plugins (services) in form of .dll or .so libraries. Is there any nice short name for such server behaviour model?</p>

答:
Your architecture can be probably be genericized as a plugin-based architecture, where the server gets functionality from loading libraries.

Your model also fits the idea of service-oriented architecture, where a software system contains different services that operate together.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Entia non sunt multiplicanda praeter necessitatem

(Keep it simple, stupid)

Years ago I ran across a poster that had the Latin expression with the English translation under it.

LastEditorDisplayName: Roger Pate


问:
Putting audit functionality into the database
Our database does not have any audit functionality.

It does not records who inserts the record or who who changes it

It does not keep a history of the changes made

Nothing can be restored if something goes wrong

There are many other short comings for example the database does not have any data integrity, anything an be thrown in, no check on different fields, duplicates etc

My question is, who's job it is to put this functionality in? An ASP Developer who knows basics of SQL and who interacts with the database regularly. Or an SQL Administrator who's sole job is to work with the databases, optimize it and maintain it?

At this point we do not have an SQL Administrator, but can hire one. How big of an undertaking this should be for a developer to fix the above issues?

答:
This is not the job of an ASP developer or the SQL Admnin (DBA). It is the job of a database developer or database architect.  If you have to you can hire a DBA to do it, but really they are generally too busy to do design.

Note it is much harder to put things like referential integrity and data checks into place once there is data in the database, this is why you should never design a database without an expert. ANd of course audit functionality will be limited to only those changes going forward, no one can recreate what happened in the past that was not recorded.


答:
I'm a Ruby developer, but I've dabbled in both Python and PHP too. I love S. Lott's answer, but I thought I would add some of my own thoughts.

I find that convincing people who are like your boss is much easier when you go beyond the technical capabilities of what the language/framework provides.

For instance, you could demonstrate that the language (and the community around it) allow for better maintenance of code, better practices (enforced by a framework, usually) and developer happiness (how much does hiring people suck?).

If you put it in terms of also how much money would be saved over the long run by not maintaining a crufty PHP no-framework solution and instead re-writing it in a Python+Django one, I'm sure that could convince him also.

If he's still quite stubborn in his choice, then I hear there's other people looking for developers.

Lastly, I don't think Ruby is a "potential middle ground", but rather more of an alternative to Python+Django. Many of the arguments that would convince somebody of using Python could also be used to convince them of Ruby.

My personal preference is, of course, Ruby. Mainly due to the religious adherence to best practices such as test driven development and constant striving to be better at the language. Oh, and everyone is so damn nice. Like, Canadian-nice.

But that means naught in this context. It's totally up to you what language you will convince your boss to use.


答:
Actually SQL Server has auditing built into the product. The easiest way to insure that all the things you describe are done is to enable C2 audit tracing. In SQL Server management studio right click n your server and select properties. C2 audit tracing is under security.

Here is a blog post with video showing how to do it.

To answer your question "who's job it is to put this functionality in?" nobody's, Microsoft has already built it into the product.

It should be the job of your internal auditors to insure that it is turned on and running properly.

Title: Putting audit functionality into the database

Body:
Our database does not have any audit functionality.

It does not records who inserts the record or who who changes it

It does not keep a history of the changes made

Nothing can be restored if something goes wrong

There are many other short comings for example the database does not have any data integrity, anything an be thrown in, no check on different fields, duplicates etc

My question is, who's job it is to put this functionality in? An ASP Developer who knows basics of SQL and who interacts with the database regularly. Or an SQL Administrator who's sole job is to work with the databases, optimize it and maintain it?

At this point we do not have an SQL Administrator, but can hire one. How big of an undertaking this should be for a developer to fix the above issues?


答:
It does not records who inserts the record or who changes it

This is a database design responsibility.

It does not keep a history of the changes made

This is a database design responsibility. A work around could exist by the DBA but the question here how do you use this history and how often?

Nothing can be restored if something goes wrong

This is the responsibility of the DBA and the project manager who allowed this system to go to live.

There are many other short comings for example the database does not have any data integrity, anything an be thrown in, no check on different fields, duplicates etc

Data integrity is a complex issue. Generally, the referential integrity is tackled by the database designer/modeller. Row duplication should not be allowed of course however, if you have two rows like this for (id, name, salary):

1 Joe 100

2 joe 100

most database system will consider these as 2 different rows even though the 'business data' is identical. This is a requirement and database design issue.


答:
if you are creating database entities, you should rather have some factory class which you will inject instead to your controller,

if you need to create primitive objects like ints or longs. Also you should create "by hand" most of the standard library objects like dates, guids, etc.

if you would like to inject configuration strings it's probably better idea to inject some configuration objects (in general it is recommended to wrap simple types into meaningful objects: int temperatureInCelsiusDegrees -> CelciusDeegree temperature)

And don't use Service locator as dependency injection alternative, it's anti-pattern, more info: http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx

Title: When is it not appropriate to use the dependency injection pattern?

Body: Since learning (and loving) automated testing I have found myself using the dependency injection pattern in almost every project. Is it always appropriate to use this pattern when working with automated testing? Are there any situations were you should avoid using dependency injection?</p>


答:
I believe that code formatting can make a huge difference in readability, but mostly well-formatted (or even just consistently-indented) code gives me a warm, fuzzy feeling that the writer actually took a little care, rather than just cut-n-pasting whatever snippets he or she had on hand.

I'm not so sure about comments. Code that I write, I firmly believe the commentary helps. On the other hand, if I want to understand "enterprise" code that I come across at work, I habitually delete all commentary, reformat the code to have consistent indentation, and print it out on paper to read through in detail, marking basic blocks with pencil, etc.

This contradiction (me: good comments; everyone else: misleading comments) makes me think that comments are vastly overrated.  Even my own.


问:
What is a good non-technical example of a cumulative error?
I'm working on a report which needs to explain in non-technical terms the effects of a cumulative error, and why it is of importance to use absolute calculations.

Definition of 'cumulative error' from dictionary.com:

an error that gradually increases in degree or significance during a
  series of measurements or calculations; an error that grows during
  observation

Ideally I could give a real world example so they grasp the concept of it without knowing about the specifics.

The first one I though of is 'Chinese whispers' which is pretty well known, but I wouldn't exactly classify it as 'real world'. Does anybody know of better examples?

答:
Real world? Try carpentry. Most people have played around in a workshop a little.

You measure a piece of lumber and cut it. You need 20 of these. But to save time you take the previous one you cut, lay it flush with the next piece of lumber, and mark where you need to cut.

After 20 times you'll notice that your saw has a non-zero width and/or your pencil doesn't mark exactly where you want to cut. Errors build up and the first piece of lumber won't match the last piece of lumber.


答: Take a value like 0.335. Consider this value to be the selling price of an item in your store. Sell this item to 50 customers. When you sum the total without rounding you get this value: $16.75 but when your computer rounds the value to 2 digits after the point before storing each sale in memory (to become 0.34), your total will be $17. The gap between the two numbers will keep growing as you sell more and more.</p>


问:
Tips for debugging with very little info?
I've inherited a project with a fairly large codebase, and the original developer rarely, if ever, replies to emails. There's a ton of different ways to do some things in it, and I don't know all of them. A lot of duplicated code along these paths (rather than functions included by, say, 5 pages that do relatively the same thing, it's code copied across 5 pages), and some subtle issues in the database (we've all heard of spaghetti code, but have you ever heard of a spaghetti database?)

All of this I can deal with most of the time no problem.

The issue is when a client finds a bug somewhere. They'll usually send a screenshot of the ending issue, and say, "Could you take a look at this?" while highlighting the specific thing on the page that's wrong, and sometimes what was expected. Very little more information is given, and trying to talk to them and get more (such as what they did to get the result) is like pulling teeth.

Basically, it boils down to this:

Large and complex code base I'm not 100% familiar with

Many many ways things can go wrong

Very little information on how a bug came to be

Does anybody have any tips, tricks, suggestions, etc. on how to debug this sort of thing?

答:
I had a similar problem a few years ago and the biggest boost to productivity and code clean-up was integrating bug tracking into the system.

We used Fogbugz (I assume they still do Fogcreek!) and we were able to build an exception handling mechanism where the user could press a button any time an exception was raised and it would get immediately logged into our system -- no more calls and no more screenshots.  With this option you take the information you need instead of trying to extract it from the user.  Sounds like a variant would do you some good, especially with a screenshot capture option.

The other thing you'll want to start doing is to start adding logging.  You may want to go as far as logging every method call with argument values.  Since it sounds like you're working with legacy code (code with no tests), this logging will help you add appropriate unit tests so you don't repeat any problems.


问:
How much experience on average should a Sr. developer have to be competent with a framework or library?
If you are a Senior developer with say 8+ years experience, how much time spent doing programming is reasonable for competency on average?  Specifically working with some library or framework associated with the core language they have worked with.  For example, 2 years of Spring or Hibernate for a java developer.

I understand that this is based on the complexity of the toolkit, framework or library, plus the competence of the individual developer, however, I'm sure there are reasonable ranges based on time with a language (hence the reference to Senior) that a Senior developer should be able to get competency and be productive.

The reason I ask the question is IT Managers should know this when writing requirements for a position and as a developer, I would like to have a better idea as to what criteria is involved for this type of experience = competency formula that has to exist.  Even if it's a rule of thumb only.

What prompted this question is that I've found recruiters, who generally don't have a technical background, are trying to place technical people and they just look at technology buzzwords on a resume and how much experience for each the dev has.  The hiring manager oftentimes doesn't have a technical background and does the same thing with the resume and uses his architect or other technical expert to screen the candidate to make sure the resume matches the person in the interview.

The problem here is the perception of "competency" in the mind of the hiring IT manager, whether or not the dev can really pick things up and run with it.  They rely on some formula in their mind as to how much experience the dev has with a technology will work for what they want.

答:
If you apply a rule blindly you will pass over candidates you should hire, and perhaps even hire someone who isn't entirely suitable, because although they have the relevant experience you're looking for, there are other problems.

Remember, that familiarity with the specific framework is not the greatest predictor of success in the actual job.   The best candidates will be smart people who get things done effectively and can apply the skills they already have in new ways to problems that haven't been solved yet.

Try not to rule people out entirely at the advertising stage.   Instead, find efficient ways to filter the stream of applicants to a level that it's feasible to do short phone interviews with.


答:
Outside of dependency-injection frameworks, dependency injection (via constructor injection or setter injection) is very nearly a zero-sum game: you decrease the coupling between object A and it's dependency B, but now any object that needs an instance of A must now also construct object B.

You've slightly reduced the coupling between A and B, but reduced A's encapsulation, and increased coupling between A and any class that must construct an instance of A, by coupling them to A's dependencies as well.

So dependency injection (without a framework) is about equally harmful as it is helpful.

The extra cost is often easily justifiable, however: if the client code knows more about how to construct the dependency than the object itself does, then dependency injection really does reduce coupling; for example, a Scanner doesn't know much about how to obtain or construct an input stream to parse input from, or what source the client code wants to parse input from, so constructor injection of an input stream is the obvious solution.

Testing is another justification, in order to be able to use mock dependencies. That should mean adding an extra constructor used for testing only that allows dependencies to be injected: if you instead change your constructors to always require dependencies to be injected, suddenly, you have to know about your dependencies' dependencies' dependencies in order to construct your direct dependencies, and you can't get any work done.

It can be helpful, but you should definitely ask yourself for each dependency, is the testing benefit worth the cost, and am I really going to want to mock this dependency while testing?

When a dependency-injection framework is added, and the construction of dependencies is delegated not to client code but instead to the framework, the cost/benefit analysis changes greatly.

In a dependency-injection framework, the tradeoffs are a bit different; what you're losing by injecting a dependency is the ability to know easily what implementation you are relying on, and shifting the responsibility for deciding what dependency you are relying on to some automated resolution process (e.g. if we require an @Inject'ed Foo, there must be something that @Provides Foo, and whose injected dependencies are available), or to some high-level configuration file that prescribes what provider should be used for each resource, or to some hybrid of the two (for example, there may be an automated resolution process for dependencies that can be overridden, if necessary, using a configuration file).

As in constructor injection, I think the advantage of doing so ends up, again, being very similar to the cost of doing so: you don't have to know who is providing the data you rely on, and, if there are multiple potential providers, you don't have to know the preferred order to check for providers in, make sure that every location that needs the data checks for all potential providers, etc., because all of that is handled at a high level by the dependency injection platform.

While I don't personally have a great deal of experience with DI frameworks, my impression is that they provide more benefit than cost when the headache of finding the correct provider of the data or service that you need has a higher cost than the headache, when something fails, of not immediately knowing locally what code provided the bad data that caused a later failure in your code.

In some cases, other patterns that obscure dependencies (e.g. service locators) had already been adopted (and perhaps also proven their worth) when DI frameworks appeared on the scene, and the DI frameworks were adopted because they offered some competitive advantage, such as requiring less boilerplate code, or potentially doing less to obscure the provider of dependency when it becomes necessary to determine what provider is actually in use.


答:
Ideally you would never place a specific requirement on experience in a particular framework or library. A good developer should be able to pick up any new framework or library fairly rapidly, so my general suggestion is always try to recruit the best developer overall and don't pay too much attention to specific tick-boxes.

For example, lets say you found an absolutely excellent Java developer who'd been writing GUI apps for 6 years that connected to various back-end servlets that she also wrote. She is motivated, keen to learn, can clearly code pretty much anything in core Java as well as architect complex client/server systems. Would you turn her down just because she doesn't have Spring on her CV? It would in my view make much more sense to hire her and let her pick up Spring along the way. She can lean Spring from other colleagues which she teaches the others something about GUI development....

What's more, good developers are in my experience naturally curious and will generally appreciate the opportunity you give them to learn something new. It's depressing to be hired to do the same thing over and over again.

There are of course some situations where specific experience in a library or framework might be considered very important:

In an emergency - if you are recruiting to solve an urgent problem with a tight deadline, then you haven't got time to bring somebody up the learning curve. You need someone who can start cranking solid work out right away. Clearly you want someone with solid experience in the specific library or framework, perhaps 6months+ recent experience.

For a leadership / mentoring role - if you're hiring someone to lead, teach or mentor others, then they better know their stuff or they won't be respected and fail badly. Perhaps 2+ years direct experience in the area you want them to teach is necessary, in addition to general experience, talent and seniority.

If the technology is fundamental to a field - for example, if someone claimed to be an "Enterprise Java Developer" with "Extensive SQL Experience" then I'd expect them to know something about JDBC. If they didn't then I'd be suspicious about their entire CV... did they really do significant work in this field? Note that you can only check this at interview, since people often leave basic technologies off their CV on the grounds that they are assumed to be there.

Title: How much experience on average should a Sr. developer have to be competent with a framework or library?

Body:
If you are a Senior developer with say 8+ years experience, how much time spent doing programming is reasonable for competency on average?  Specifically working with some library or framework associated with the core language they have worked with.  For example, 2 years of Spring or Hibernate for a java developer.

I understand that this is based on the complexity of the toolkit, framework or library, plus the competence of the individual developer, however, I'm sure there are reasonable ranges based on time with a language (hence the reference to Senior) that a Senior developer should be able to get competency and be productive.

The reason I ask the question is IT Managers should know this when writing requirements for a position and as a developer, I would like to have a better idea as to what criteria is involved for this type of experience = competency formula that has to exist.  Even if it's a rule of thumb only.

What prompted this question is that I've found recruiters, who generally don't have a technical background, are trying to place technical people and they just look at technology buzzwords on a resume and how much experience for each the dev has.  The hiring manager oftentimes doesn't have a technical background and does the same thing with the resume and uses his architect or other technical expert to screen the candidate to make sure the resume matches the person in the interview.

The problem here is the perception of "competency" in the mind of the hiring IT manager, whether or not the dev can really pick things up and run with it.  They rely on some formula in their mind as to how much experience the dev has with a technology will work for what they want.


问:
Do C library functions generally mimic the Intel assembly language style?
I'm looking at the basic strcpy function. It is

```<code>char *strcpy( char *dest, const char *src );
</code>```

Which reminds me of assembly language: MOV   DEST, SRC

答:
The Intel processors were not yet invented when the C library was designed, so no.

Your observation that C is similar to assembly language is correct, however.  C was designed to replace assembly when Unix needed to be ported to other architectures than the original PDP-11 and many constructs map directly to the PDP-11 machine language.

I do not know if the machine language of the PDP-11 was similar to Intel (dest, src) or the reason for the API convention was just that it was this way that made most sense to the designer.

See http://www.unix.org/what_is_unix/history_timeline.html for time line.


答:
Sometimes a useful proxy for competence in a specific framework is "shipped a product with it." However, shipping a product with "similar" frameworks may be just as good. Also consider how they tested their code in that framework.

Some frameworks are more involved than others and take deeper experience to grok. jQuery for an experienced JavaScript dev who is fluent with Dojo or ExtJS -- no prob. jQuery for a C programmer with no JavaScript -- riskier, since they haven't learned yet how to "think" like a JavaScript dev. Learning all of Spring for a non-Java dev -- risky too -- tools are different, concepts, terminology, even open source may be new.

I do not believe that you only should hire devs already up to speed in tech X, but sometimes the learning curve is too big to absorb right now.. and your question did ask specifically about already being competent.


答:
The way people know about the book Mythical Man Month - which talks about bogus myth of Man-month in project planning - i guess there is a clear need for another parallel book called "Mythical Man Years" to explain why number of years is a useless metrics to evaluate people.

There are many aspects to explain this:

1. Number of years alone don't count:

In a consulting/project-based IT company - there are often significant periods where staff are on the bench, or where staff are assigned on a project but don't do anything meaningful. Sometimes even if people do some constructive work, there are cases where they have 1 year experience multiplied 8 times rather than doing 8 different things over 8 years.

Choose candidate, based on depth - not length of career

2. What you learn is more important.

Following up, we are talking about how much she/he has learned from others so that now she can apply herself to other problems. There are many people who are so obedient and show successful results by following the boss's nod rather than
applying individual thinking. This means if the candidate does not get the support of good colleagues and bosses, they become a disaster (and many candidates themselves don't understand this)

Choose candidate, based on their original contribution than project
  results and complexity

3. Number of years sometimes is inversely proportional to how much you can learn.

This doesn't have to be true, but it is a possibility. Because someone has spent a lot of time on one subject - they may cease to learn; learning a new framework (details of it) might not be as much if someone has worked in similar level of challenge (and gained wisdom) otherwise. Given this, you can be better off with a relatively newer guy compared to a guy who has some experience.

Choose a candidate who has energy to learn rather than someone tired
  or who thinks she/he knows everything.

4. New area of work requires new thinking

this implies that often in more senior roles, specific details (how to solve problems with a specific tool) are less important but rather insight on how to approach problems in general becomes more important. It takes wisdom rather than years of experience to foresee upcoming problems.

Choose candidate who has developed insight rather than someone who
  knows all terms of the API!


问:
Simple explanation of the Unix sockets
I can search and I've already looked at the wikipedia entry and in some other places, but even though I have some programming experience, I don't really grasp the concept. Can you treat me like a 10 year old and give me a clear explanation on socket communication?</p>

答:
Let me give you an example:
Say you want to communicate/chat with your friend, who lives not at your address. For that to happen, you have to establish a "communication channel". Say, you want to do this communication using telephones. You know that there is a network of telephone lines in the city that is extended to every house.

Now, there is a telephone socket in your house, and one in your friends house. For the communication to take place, you and your friend have to connect to the network by plugging your phone to the socket, at the both end of the communication. Sockets in programming is the same, conceptually, as the telephone sockets.

In programming, you have two processes (running programs) that want to communicate with each other. For that, they have to establish a communication link between themselves. Again, there is a network available, they just need to connect to this network using some sort of sockets. Unix sockets are one such socket that provides this connectivity/pluggability to the network. So, in each of the two programs, you will have some piece of code that does the job of connecting to the network through sockets.

The rest are details.

Title: Simple explanation of the Unix sockets


答:
Unless I need something done this week, I don't care if candidates have any experience with the technology I am hiring them to use.  If I already have one in-house expert, I care even less.  In two months a good developer with no experience in a platform will be outperforming the average developer with ten years experience in it.  The good developer will read a handful of books in the first month that the average developer has never thought to look at.  The good developer will search in the standard library, and then the internet for common functions, while the average developer is busy re-implementing date formatting.  The good developer will produce understandable DRY code while the average developer cuts and pastes his way through the day.

Certainly, if I can hire an great developer who knows the platform inside and out, I will, but general ability beats experience very quickly.


答: A problem with this:  Acronyms.  Sometimes people post non-words without them being gibberish.  I asked the IRS if I could roll my 401k over to a Roth IRA.  Three non-words in one sentence without it being filter-bait.</p>

Title: Would it be hard to screen form submissions (e.g., comments) for non-words/non-sentences?

Body:
I've been thinking a lot lately about the need for better form security, and good ways to accomplish that.

We currently use captcha codes to screen for bots, but that's annoying to users and may not work forever.

I think that we need a more intuitive, organic system for screening bad comments/contact form submissions.

One option that has come to mind would be trying to screen comments for things that are obviously not words, in addition to screening for duplicate comments.  E.g., when a spammer on Facebook, Twitter, or a comments section is stopped from just posting the same thing a lot of times, they add garbled letters and or numbers somewhere in the post to make it "unique".

If it was possible to screen out obvious not-text, this could be overcome. If you could go a step further, and screen out posts that obviously have words placed in for no reason except to make the post "unique", you could force the spammer/scam artist down to only use repetitive post options which actually make gramatical sense.

At the very least, you could have posts be flagged for moderator attention if they looked similar but which just had random garbage added in for no reason. This would significantly reduce a spammer's ability to keep spamming, even across multiple accounts.

Could it be possible to screen form field results for random word and number combinations, and words thrown in just to make a post "unique"?


问:
Where can I locate business data to use in my application?
This question talks about any and all free public raw data which appeared to have valuable pieces but nothing that really provides what I am looking for.

Instead of using a socially defined listing of businesses (foursquare), I would like a business listing data set of registered businesses and associated addresses that could then be searchable based on location (coordinates). The critical need is that the data set should be filterable based on varying criteria (give me all restaurants, coffee shops, etc...).

If the data is free that is great but anywhere that sells this type of data would also suffice. Infochimps looked like a possibility but perhaps something a bit more extensive exists.

Where can I find a free or for fee data set of registered business that is filterable based on type of business and location?

答:
I have use the data from http://localeze.com/.  It is categorized so you can filter like you said and geocoded, for geographic lookup.  I have an application that uses their data and it is as good as anything else out there.

Pretty expensive though.


答:
10,000 hours seems to be the magical number for mastery in anything. Those who get to this point typically spend at least 10 years getting there, although in programming, those 10 years are not typically all spent on a paid job - many programmers start their 'career' at a young age (between ages 12 and 16 seems to be quite common), so it is certainly possible to find a 25-year-old candidate who is already a master in his/her particular field, despite having "only" maybe six years of on-the-job experience.

That said, a lot depends on how much knowledge exactly is required in which area.

Knowing a particular framework inside-out isn't necessarily required for a senior developer role: technologies come and go, and a good programmer can pick up any halfway decent framework in a matter of weeks (days even, if the framework makes sense and is well documented). Skills that are much more important typically include communication, writing clean and robust code, analytic skills, prioritizing, etc.

Of course, if the particular role is that of a 'guru', then in-depth knowledge of that particular technology is the top requirement, but most of the time, you don't need gurus; in fact, they can be a risk. If their specialism goes out of fashion, or gets discontinued, you can only hope that they have acquired a similar level of expertise in a replacement technology by the time you start transitioning.


问:
Will Java still be relevant in 5 years?
Will Java have the same importance it had in the past, or it will be less relevant than nowadays?</p>

答: COBOL, Fortran, and C are still relevant.  What's the chance that Java will go away in five years?  Conceivably there won't be much new Java development in five years, but I'd bet against that, too, since there's lots of people who use Java and shops are rather slow to switch their preferred languages.</p>

Title: Will Java still be relevant in 5 years?


问:
What are the advantages of separating 'result' from 'status'
Let's say you have some automated processes that generally go through the following states;
scheduled - initiated - validating - executing - completed

On top of that these processes can prematurely end because of an error or explicit user cancellation.

My first impulse is to simply add error and cancelled to the list of possible status values, but I was wondering about the (conceptual) advantages of separating result from status (even though it seems to me that one might argue that error and cancelled are also simply different states than the completed state).

答:
The state you assign to your processes should reflect what your program (or the users, if you are just visualizing states) are going to do with this information. So do you have the requirement to evaluate / show the state of your processes as long as they are running and showing no error? Then separate result from status. If you just need the status when a process has ended, then don't separate.

You should not model anything just for the sake of modeling. Better check your requirements. And if you are unsure about what you might need later, choose the smallest, most simple solution for the requirements you know for sure. If you are just "guessing", in 90% of all cases you will guess wrong, so you will have to change your model later anyway.


答:
IMHO, first one is suitable for commenting on what a class does or at the beginning of a source file; second one is suitable for describing what the following code block does. for methods, I'd use

```<code>//////////////////////////////////////////////////////////////////////
This code prints a basic "Hello world" message to the console screen. You can change the text in the brackets.
</code>```

In addition to other great answers, I think consistency in commentary style is another point. If you use different types of commentary styles for same kind of tasks that would hurt readability of your code rather badly.

Body:
IMHO, first one is suitable for commenting on what a class does or at the beginning of a source file; second one is suitable for describing what the following code block does. for methods, I'd use

//////////////////////////////////////////////////////////////////////
This code prints a basic "Hello world" message to the console screen. You can change the text in the brackets.

In addition to other great answers, I think consistency in commentary style is another point. If you use different types of commentary styles for same kind of tasks that would hurt readability of your code rather badly.