问:
Are session aware Models a bad thing?
I'm thinking specifically in Rails here, but I suspect this is a wider question.

In a Rails web application I'm using data from the session in models in order that the models know who is logged in. I use this in a method which filters out some data from the database depending on a very simple permissions system.

The thing is: using sessions in models in Rails requires a bit of a workaround. It works, but I've a feeling that it's something that I shouldn't be doing and I'm worried there's a big gotcha I'm missing.

I suppose the Right Thing To Do would be to return all the data and filter out the not-wanted bits in the controller before passing that to the view, but doing it in the model seems to avoid quite a bit of code duplication and so feels "cleaner."

Can anyone tell me why or shouldn't do this? Or that it's not a problem?

答:
I can't tell from a "should" or "should not" perspective. It breaks the MVC model to some extend.

Then on the other side your model is responsible to generate the most efficient business logic and database query possible. So letting the controller sort data by permission is not the way to solve this issue (it should never get any data the actual user is not allowed to see for security reasons). So this may be even worse than accessing the session in the model.

In my opinion (and how I would implement it if possible) I would add some special methods that take the user information as params (like def show_orders(current_user)) and return the results. That way you can keep the session handling in the controller (relevant if later you decide to use the model for another web interface or whatever) and still have optimized access.

Or add the access permission handling to the User model so you can access them like current_user.orders. If it's really simple permissions, you may be able to add this to the has_many declarations in Rails. Otherwise add some methods there.

Title: Are session aware Models a bad thing?


答:
Filtering in the controller partially defeats the purpose of a database, i.e. doing a full table scan on the database and filtering in the program is a huge performance killer.

That said, your model should not store any session information. Why? Because that will cause race conditions when many users are accessing the system concurrently.

ContentLicense: CC BY-SA 3.0

Title: Are session aware Models a bad thing?

Body:
I'm thinking specifically in Rails here, but I suspect this is a wider question.

In a Rails web application I'm using data from the session in models in order that the models know who is logged in. I use this in a method which filters out some data from the database depending on a very simple permissions system.

The thing is: using sessions in models in Rails requires a bit of a workaround. It works, but I've a feeling that it's something that I shouldn't be doing and I'm worried there's a big gotcha I'm missing.

I suppose the Right Thing To Do would be to return all the data and filter out the not-wanted bits in the controller before passing that to the view, but doing it in the model seems to avoid quite a bit of code duplication and so feels "cleaner."

Can anyone tell me why or shouldn't do this? Or that it's not a problem?


问:
As a programmer, are you required to do timesheets?
Timesheets are something that I've never been fond of, but none the less something that is a requirement within my company. They don't bother me so much, but they seem to really grind some other people's gears. I suppose I have a few questions, and feedback would be great.

Are you required to do timesheets, assuming you aren't a contractor? (That is understandable to me).

What is the granularity of timesheets that you would be comfortable with or that you use? (ex: all entries must be under two hours).

Would timesheets ever factor into your reasons for not accepting a job or leaving a current one?

How has management within your organization justified timesheets if you aren't billing to a client?

答:
I used to have to fill out time sheets at all previous companies, but not in my current gig.

Mostly it seemed like a pointless exercise except in one case: a company I worked for where we were directly billing clients for our developers' time. This was understandable.

The problem with timesheets in typical software work is that the work is too dynamic to fit into nice little bundles. For example, in my current gig: in a typical hour I might spend 17 minutes responding to emails from Marketing, 11 minutes answering questions from Helpdesk regarding some client issue, 12 minutes helping out a newbie colleague with something, and 20 minutes actually working on an official CR issue that can be clearly timesheeted. Mix these intervals up randomly, and there you have a typical senior developer's hour.

Not every hour of every day is like this of course, but it's like this often enough to make timesheets pretty well pointless around here. Unless you're trying to measure how much time is being spent on a particular billable task (which is never the case here), they're basically a waste of time (both developer time and payroll time).

ContentLicense: CC BY-SA 2.5


问:
Calculating 3d rotation around random axis
This is actually a solved problem, but I want to understand why my original method didn't work (hoping someone with more knowledge can explain).

(Keep in mind, I've not very experienced in 3d programming, having only played with the very basic for a little bit...nor do I have a lot of mathematical experience in this area).

I wanted to animate a point rotating around another point at a random axis, say a 45 degrees along the y axis (think of an electron around a nucleus). I know how to rotate using the transform matrix along the X, Y and Z axis, but not an arbitrary (45 degree) axis.

Eventually after some research I found a suggestion: Rotate the point by -45 degrees around the Z so that it is aligned. Then rotate by some increment along the Y axis, then rotate it back +45 degrees for every frame tick. While this certainly worked, I felt that it seemed to be more work then needed (too many method calls, math, etc) and would probably be pretty slow at runtime with many points to deal with.

I thought maybe it was possible to combine all the rotation matrixes involve into 1 rotation matrix and use that as a single operation.

Something like:

```<code> [ cos(-45)    -sin(-45)         0]
 [ sin(-45)     cos(-45)         0]      rotate by -45 along Z
 [    0            0             1]
</code>```

multiply by

```<code> [ cos(2)          0       -sin(2)]
 [    0            1            0 ]      rotate by 2 degrees (my increment) along Y
 [ sin(2)          0        cos(2)]
</code>```

then multiply that result by (in that order)

```<code> [ cos(45)      -sin(45)         0]
 [ sin(45)       cos(45)         0]      rotate by 45 along Z
 [    0            0             1]
</code>```

I get 1 mess of a matrix of numbers (since I was working with unknowns and 2 angles), but I felt like it should work. It did not and I found a solution on wiki using a different matirx, but that is something else.

I'm not sure if maybe I made an error in multiplying, but my question is: this is actually a viable way to solve the problem, to take all the separate transformations, combine them via multiplying, then use that or not?

答:
The problem you get by rotating the axis separately is that you can experience what is called 'gimbal lock', a state where the rotations on the separate axis make it overlap in a way that your calculations will not produce the desired effect because the separate calculations interfere with the end result due to overlap. The solution to this is to specify the axis in a vector and rotation expressed in the form of an imaginary number. The way to calculate this is to use
Quaternions.
all types of rotation calculation will eventually yield a 4x4 matrix, as this is always the required form for expressing the final transformation. This implies that you can indeed add up the calculations through multiplication, but as described before, the additions can interfere with each other in certain cases.</p>


问:
What's special about currying or partial application?
I've been reading articles on Functional programming everyday and been trying to apply some practices as much as possible. But I don't understand what is unique in currying or partial application.

Take this Groovy code as an example:

```<code>def mul = { a, b -> a * b }
def tripler1 = mul.curry(3)
def tripler2 = { mul(3, it) }
</code>```

I do not understand what is the difference between tripler1 and tripler2. Aren't they both the same? The 'currying' is supported in pure or partial functional languages like Groovy, Scala, Haskell etc. But I can do the same thing (left-curry, right-curry, n-curry or partial application) by simply creating another named or anonymous function or closure that will forward the parameters to the original function (like tripler2) in most languages (even C.)

Am I missing something here? There are places where I can use currying and partial application in my Grails application but I am hesitating to do so because I'm asking myself "How's that different?"

Please enlighten me.

EDIT:
Are you guys saying that partial application/currying is simply more efficient than creating/calling another function that forwards default parameters to original function?

答:
Currying is about turning/representing a function which takes n inputs into n functions that each take 1 input. Partial application is about fixing some of the inputs to a function.

The motivation for partial application is primarily that it makes it easier to write higher order function libraries. For instance the algorithms in C++ STL all largely take predicates or unary functions, bind1st allows the library user to hook in non unary functions with a value bound. The library writer therfore does not need to provide overloaded functions for all algorithms that take unary functions to provide binary versions

Currying itself is useful because it gives you partial application anywhere you want it for free i.e. you no longer need a function like bind1st to partially apply.


问:
Rest Design concerning user login
To be as restful as possible, is a user login better designed using a GET or a POST on a REST webservice? And why?</p>

答: I would use a POST, since it makes serious changes to the state of the server (even if not saved into the database). Though that's more a HTTP rule than REST.</p>

Title: Rest Design concerning user login


问:
How should I expand Jenkins to help me release?
Pushing new Sparkle releases of our internal apps is a pain. I have to make the build, make the release notes file, sign the .zip with the private key, and add a new entry to the appcast file tying everything together.

I'd love it if Jenkins could help: use the commit messages for the release notes, and automatically do the rest of it.

Should I be looking at writing a new Jenkins plugin, or using shell scripting, or is there something already that will do what I want? (A quick Google didn't find anything.)

答:
why can't Jenkins help? The build steps that occur when code is checked in can be completely customised - so whatever it is you do, ensure that they are reproducible and put those steps into Jenkins as part of the build as shell scripts.

You may have to parametrize things like path or project name, and you may want to create a new 'dummy' or 'release' project that you can run manually (or chained as part of a Jenkins dependency so it builds automatically after several other projects have built).

Open up a Jenkins project and see the steps, look at the documentation and play with a dummy project.


问:
How can I use UML to model a relationship between two classes, where one has functions exposed as friend to the other?
I have a two classes:

```<code>  ------------                         ---------------
     X                                       Y
  ------------                         ---------------
                      relation
  ------------    ------------------   ---------------
      A()                                   C()
      B()
      D()
      E()
  ------------                         ---------------
</code>```

I want to inherit just these two functions from X class, where they are defined with the friend access modifier. My class will be:

```<code> ---------------
      Y
 ---------------

 ---------------
    C()
    A()
    D()
 ---------------
</code>```

Y class uses some functions of X class namely A and D. How can I model this relationship in a UML class diagram?

答:
If the methods of X are instance methods, you can use the association relationship, which is a solid line between the two classes, however this might indicate to the reader of the model that the relationship is bidirectional. If an instance of Y maintains a reference to X in it and X does not maintain any kind of reference to 'Y', you can add the open-ended arrow to the end pointing toward X to add directionality. If Y can't exist without X, you can also consider using aggregation to indicate this.

If the methods of X are static, consider the dependency relationship, represented by a dotted line and open ended arrow from Y to X. This relationship is used Y calls static methods of X or if the functions of Y take X as a parameter but a reference to X is not maintained within an instance of Y.

In your specific case, when you're trying to model the friend relationship in C++, the information that I can find (such as this question on Stack Overflow) seems to suggest that you should annotate the members of X with the <> stereotype. From this point, I'd use either the association or dependency relationship discussed above, based on how Y is accessing X, with association if Y maintains an instance of X and dependency if Y receives instances of X as parameters to functions as they are needed.


问:
how do early stage startups hire ninja programmers
I am programmer who just started working on a startup idea. At the moment I want to bring onboard at least one programmer. This programmer should be a ninja - a 10x engineer.

Since early days are probably the most risky for a startup, I want to make sure I approach this problem the best I can.

How do I find these people? and How do I convince them to come onboard?

I would love to hear from people who started their own companies and what their thoughts are about hiring

Update: I would like to get the ninja as a co-founder so besides being a ninja (ie. great programmer with computer science background) he/she has to have a healthy appetite for risk (for great programmers this is not a big deal because they can be hired anytime into mainstream jobs if the startup doesn't work)

答: Get a booth at a developer conference. Demonstrate a proof-of-concept and let people know you're hiring.</p>


答: GET method should be used to obtain a representation of a resource. PUT - to update or replace an existing resource. Therefore, to perform the login action, POST is better.

Title: Rest Design concerning user login

Body: To be as restful as possible, is a user login better designed using a GET or a POST on a REST webservice? And why?</p>


问:
How to choose a development method?
There are many academic/industrial researchs about various development methods (Scrum, XP, waterfall, ect.), telling us how to do it right and stuff. But I never saw something that suggest how to choose a method, what will be better for a given project.

I know that what the developers are used to is an very important aspect. But lets say that I am assembling a new group from scratch, and that every programmer in the world is willing to work with me. :)

What aspects of the project should I consider to decide between Scrum, XP, TDD, ect.? Or is that an entirely human thing, regardless of what is being developed?

I said that all programmers are available, but you may comment they're knowledge about the domain, or other characteristics in the answers. E.g. "If you chose to hire people with no domain knowledge, MethodX is better than MathodY, beacause ...." is a completely welcomed answer.

答:
In Rapid Development, Steve McConnell writes about choosing an appropriate lifecycle model for your project. There's an entire section of a chapter devoted to this topic, but it comes down to the characteristics of the project - the level of understanding of the requirements, the level of understanding of the architecture, the required reliability, the amount and severity of risks, the schedule and budget constraints, desired customer and/or management visibility, and the skill/sophistication of the project team are identified as the major selections.

The type of system has very little to do with it, although that does frequently play into the reliability or future tendency to modify/enhance the system). The people are your biggest drivers in terms of how well they understand the domain, the tools, the project, and what the interaction is between the development team and other stakeholders. Knowledge of the process is also important as there's overhead in learning new techniques to doing work.

Title: How to choose a development method?


问:
Is the output of Eclipse's incremental java compiler used in production? Or is it simply to support Eclipse's features?
I'm new to Java and Eclipse. One of my most recent discoveries was how Eclipse comes shipped with its own java compiler (ejc) for doing incremental builds. Eclipse seems to by default output incrementally built class files to the projRoot/bin folder.

I've noticed too that many projects come with ant files to build the project that uses the java compiler built into the system for doing the production builds.

Coming from a Windows/Visual Studio world where Visual Studio is invoking the compiler for both production and debugging, I'm used to the IDE having a more intimate relationship with the command-line compiler. I'm used to the project being the make file. So my mental model is a little off.

Is whats produced by Eclipse ever used in production? Or is it typically only used to support Eclipse's features (ie its intellisense/incremental building/etc)? Is it typical that for the final "release" build of a project, that ant, maven, or another tool is used to do the full build from the command line?

Mostly I'm looking for the general convention in the Eclipse/Java community. I realize that there may be some outliers out there who DO use ecj in production, but is this generally frowned upon? Or is this normal/accepted practice?

答: The output of the Eclipse Java compiler is indeed heavily used in production applications. The Eclipse platform itself is built with the Eclipse compiler, as are thousands of other products (Eclipse based or otherwise). The Eclipse java compiler is also heavily used in the Linux community, and by web servers for compiling JSPs in commercial applications. Maven has a maven-compiler-plugin to allow you to run your command line builds using the Eclipse compiler.  This is valuable not only to ensure you have consistent output at development and deployment, but also gives you access to the rich and highly configurable set of errors and warnings reported by the Eclipse compiler. </p>


答:
But I can do the same thing (left-curry, right-curry, n-curry or partial application) by simply creating another named or anonymous function or closure that will forward the parameters to the original function (like tripler2) in most languages (even C.)

And the optimizer will look at that and promptly go on to something it can understand. Currying is a nice little trick for the end user, but has much better benefits from a language design standpoint. It's really nice to handle all methods as unary A -> B where B may be another method.

It simplifies what methods you have to write to handle higher order functions. Your static analysis and optimization in the language only has one path to work with that behaves in a known manner. Parameter binding just falls out of the design rather than requiring hoops to do this common behavior.

Title: What's special about currying or partial application?

Body:
I've been reading articles on Functional programming everyday and been trying to apply some practices as much as possible. But I don't understand what is unique in currying or partial application.

Take this Groovy code as an example:

```<code>def mul = { a, b -> a * b }
def tripler1 = mul.curry(3)
def tripler2 = { mul(3, it) }
</code>```

I do not understand what is the difference between tripler1 and tripler2. Aren't they both the same? The 'currying' is supported in pure or partial functional languages like Groovy, Scala, Haskell etc. But I can do the same thing (left-curry, right-curry, n-curry or partial application) by simply creating another named or anonymous function or closure that will forward the parameters to the original function (like tripler2) in most languages (even C.)

Am I missing something here? There are places where I can use currying and partial application in my Grails application but I am hesitating to do so because I'm asking myself "How's that different?"

Please enlighten me.

EDIT:
Are you guys saying that partial application/currying is simply more efficient than creating/calling another function that forwards default parameters to original function?


问:
Is there a way to publish IOS app from windows/Linux?
I have been using Linux (especially, Ubuntu) and Windows 7 for a long time.  I want to publish iOS apps, but I don't have a Mac or an iPhone.  I don't have anyone near me who will lend me a Mac, and I don't actually want to buy them either.

So my question is: how do I publish my iOS app from Windows or Linux? I am not referring to publishing programs for jailbroken iPhones, I want to publish through the Apple Store.

My search results indicate that there is no fool-proof way of publishing an iOS app from Windows or Linux. I also want to make it a paid app, and not give it away for free.

Does anyone know of a way to publish iOS apps from Windows or Linux?

答:
I can't believe no one mentioned Dragonfire SDK. They recently came out with version 2.0, which adds a lot of features. You program in C/C++ with Visual Studio, and your C++ code uses their API to actually call iOS objective C funtions, so it ends up being native. It comes with a great simulator for testing from within VS. Then when you are ready to compile it to native code, you send it to their servers, which compile it in MacOS X, then sends the file back to you. You can even publish paid apps to the app store through them from Windows. If you don't have an iOS developer ID, they let you publish free apps through them for free, in their name. I assume you could use your own ads that way.

The only downsides are that it costs $99 for iPhone or iPad versions and $149 to do both. Also, it's Windows only; they don't have a Linux version.


答:
I think your main challenge will be identifying the superstar programmers. You'll get all kinds of applicants if you just say "I'll give you a truckload of money." The choice of programming language will help. Your applicants will be mostly commodity programmers if you use C# or Java. By commodity programmers I mean those who are only doing programming for the money and don't care about learning anything beyond what is necessary to complete whatever task happens to be in front of them. EDIT: I'm not claiming that all C#/Java programmers have this attitude. I personally know some who are very competent and dedicated. But finding them can be difficult.

If you use Haskell or Common Lisp, commodity programmers won't be interested because there aren't large numbers of Haskell and Common Lisp jobs posted on search sites [EDIT: not to mention the standard criticisms of Haskell (looks like line noise, slow) and Common Lisp (archaic, too many parentheses, macros are dangerous)]. You'll get people who are very dedicated to learning and able to pick up powerful concepts that the average developer would have trouble with. Examples of these concepts would be monads in Haskell or Lisp macros. If you want the best, these are the people you want.

Title: how do early stage startups hire ninja programmers

Body:
I am programmer who just started working on a startup idea. At the moment I want to bring onboard at least one programmer. This programmer should be a ninja - a 10x engineer.

Since early days are probably the most risky for a startup, I want to make sure I approach this problem the best I can.

How do I find these people? and How do I convince them to come onboard?

I would love to hear from people who started their own companies and what their thoughts are about hiring

Update: I would like to get the ninja as a co-founder so besides being a ninja (ie. great programmer with computer science background) he/she has to have a healthy appetite for risk (for great programmers this is not a big deal because they can be hired anytime into mainstream jobs if the startup doesn't work)


答: I suggest you try the Process Consultant at OPFRO web site. Click on "Process Consultant" on the left-hand side menu and answer the multiple-choice questions about your needs. The tool will recommend a method life cycle. You will also see some explanation about why that is the best option.</p>

Title: How to choose a development method?

Body:
There are many academic/industrial researchs about various development methods (Scrum, XP, waterfall, ect.), telling us how to do it right and stuff. But I never saw something that suggest how to choose a method, what will be better for a given project.

I know that what the developers are used to is an very important aspect. But lets say that I am assembling a new group from scratch, and that every programmer in the world is willing to work with me. :)

What aspects of the project should I consider to decide between Scrum, XP, TDD, ect.? Or is that an entirely human thing, regardless of what is being developed?

I said that all programmers are available, but you may comment they're knowledge about the domain, or other characteristics in the answers. E.g. "If you chose to hire people with no domain knowledge, MethodX is better than MathodY, beacause ...." is a completely welcomed answer.


问:
On what basis would you split donation money among your open source team members without any strife?
I am a developer of an open source project which is hosted in SourceForge.

It started out as a little app then after some releases, it got more and more popular and it started consuming more time and responsibility from me. So I have enabled the donation option in SourceForge.

I'm passionate to continue developing it for free but if (ever) any money comes in, how should I split it with my team?

Should I split the amount equally among the number of team members? (50-50 as it is two-member team now)

Number of classes, commits or any other valuable submissions by team members?

Any other idea?

What would you do in such situation? Please give your opinions.

I hope this question will be useful for others.

答: I really like the idea of "code bounties". It helps to encourage people to donate because they're donating to improve something that is important to them, and it means whoever implements the requested feature/s wins the money (and also solves the "how to divide 50 cents evenly when there's 8 developers" problem ;-) ).</p>


问:
How to implement a safe password history
Passwords shouldn't be stored in plain text for obvious security reasons: you have to store hashes, and you should also generate the hash carefully to avoid rainbow table attacks.

However, usually you have the requirement to store the last n passwords and to enforce minimal complexity and minimal change between the different passwords (to prevent the user from using a sequence like Password_1, Password_2, ..., Password_n). This would be trivial with plain text passwords, but how can you do that by storing only hashes?

In other words: how it is possible to implement a safe password history mechanism?

答:
Store the hashes and verify an entered password against those stored hashes, the same way you verify a password when logging in. You would have to generate 'alternative' passwords from the one given based on numerical patterns to detect your 'minimal' changes.

On login, you verify the entered password against a hash already, there is no need to store the password in plaintext. The same trick works when it comes to changing a password, simply check the entered and 'minimal change' generated passwords against the historical hashes. If the new password is satisfactory, move the current password hash over to the historical set, and replace it with a new hash for the new password.


答:
This article at InfoQ has helped with my understanding of REST. Paraphrasing from the Use standard methods section:

PUT means, essentially: "update this resource with this data, or
create it at this URI if it’s not there already", whereas POST means
"create a new resource."

According to IBM DeveloperWorks though:

To create a resource on the server, use POST.

To change the state of a resource or to update it, use PUT.

Based on these definitions, if you plan to continually update some kind of access token to indicate that a user is still logged in, use POST to create it, then PUT to update it on subsequent requests.

Also, from the Communicate statelessly section:

REST mandates that state be either turned into resource state, or kept
on the client. In other words, a server should not have to retain some
sort of communication state for any of the clients it communicates
with beyond a single request. The most obvious reason for this is
scalability — the number of clients interacting would seriously impact
the server’s footprint if it had to keep client state. (Note that this
usually requires some re-design — you can’t simply stick a URI to some
session state and call it RESTful.)

But there are other aspects that might be much more important: The
statelessness constraint isolates the client against changes on the
server as it is not dependent on talking to the same server in two
consecutive requests. A client could receive a document containing
links from the server, and while it does some processing, the server
could be shut down, its hard disk could be ripped out and be replaced,
the software could be updated and restarted — and if the client
follows one of the links it has received from the server, it won’t
notice.

Given that, it seems like we shouldn't be creating any server state to track what users are logged in; rather we should perhaps be using HTTP Authentication.

Here's another good question related to the issue of authentication for REST services.

Title: Rest Design concerning user login


问:
Use decorator and factory together to extend objects?
I'm new to OOP and design pattern.

I've a simple app that handles the generation of Tables, Columns (that belong to Table), Rows (that belong to Table and have Columns) and Values (that belong to Rows). Each of these object can have a collection of Property, which is in turn defined as an enum.

They are all interfaces: I used factories to get concrete instances of these products, depending on circumnstances.

Now I'm facing the problem of extending these classes. Let's say I need another product called "SpecialTable" which in turn has some special properties or new methods like 'getSomethingSpecial' or an extended set of Property. The only way is to extend/specialize all my elements (ie. build a SpecialTableFactory, a SpecialTable interface and a SpecialTableImpl concrete)? What to do if, let's say, I plan to use standard methods like addRow(Column column, String name) that doesn't need to be specialized?

I don't like the idea to inherit factories and interfaces, but since SpecialTable has more methods than Table i guess it cannot share the same factory. Am I wrong?

Another question: if I need to define product properties at run time (a Table that is upgraded to SpecialTable at runtime), i guess i should use a decorator. Is it possible (and how) to combine both factory and decorator design? Is it better to use a State or Strategy pattern, instead?

答:
Yes, SpecialTable can be produced by the same factory (and by the same factory method) that produces Table. This not a problem, as long as SpecialTable provides at least the methods guaranteed by the Table interface (which it does).

This sort of situation makes sense when objects returned from the factory have some guaranteed behaviour/functionality (interface Table), and some optional stuff (interface SpecialTable).

So, in order to make use of the optional extra abilities/stuff available on some concrete objects returned by the factory, you have a few choices:

use polymorphism (recommended)

make use of instanceof (or similar), which can be used to check for interface compliance/exact typing (avoid this if possible!)

Using polymorphism

An example to illustrate: suppose SpecialTable has extra data and an extra widget 'blarg' which appears on the UI representing special tables. Do you really need the code which uses SpecialTable to know that it needs to add 'blarg' to the UI? Or can you just have your external code ask the thing of type Table to add its necessary UI components to some UI container? Then the calling code doesn't care what exact type the thing is -- SpecialTable deals with it, adding the 'blarg' to the container itself. This pattern can be described as the delegate pattern (also sometimes also known as strategy pattern).

Using instanceof (type checking)

Example of instanceof use:

```<code>// Table and SpecialTable are interfaces
Table table = TableFactory.instance().getDefaultTable();

if (table instanceof "SpecialTable") {
  SpecialTable specialTable = (SpecialTable)table;
  specialTable.specialMethod();
}

table.normalMethod();
</code>```

Note that when you define your SpecialTable interface you can declare it as extending the Table interface and then only list the extra methods.

Your factory will be producing concrete objects of either type. So you might have a concrete class called BoringTable which implements Table, and a concrete class called ExcitingTable which implements SpecialTable.

Beware instanceof!

It's generally better to avoid things like 'instanceof' (or generally speaking, ifs of any kind which depend on what type an object is). You should favour polymorphism instead. By this I mean having multiple different classes, of a common type, enclosing different behaviour in their implementation code.

Ask yourself this: does the class using something of type Table (which might also be of type SpecialTable) need to care if it's a special table or not? Can you not hide that distinction in some sort of implementation of the SpecialTable -- have it do something different, something extra, that plain old Table does?

Body:
Yes, SpecialTable can be produced by the same factory (and by the same factory method) that produces Table. This not a problem, as long as SpecialTable provides at least the methods guaranteed by the Table interface (which it does).

This sort of situation makes sense when objects returned from the factory have some guaranteed behaviour/functionality (interface Table), and some optional stuff (interface SpecialTable).

So, in order to make use of the optional extra abilities/stuff available on some concrete objects returned by the factory, you have a few choices:

use polymorphism (recommended)

make use of instanceof (or similar), which can be used to check for interface compliance/exact typing (avoid this if possible!)

Using polymorphism

An example to illustrate: suppose SpecialTable has extra data and an extra widget 'blarg' which appears on the UI representing special tables. Do you really need the code which uses SpecialTable to know that it needs to add 'blarg' to the UI? Or can you just have your external code ask the thing of type Table to add its necessary UI components to some UI container? Then the calling code doesn't care what exact type the thing is -- SpecialTable deals with it, adding the 'blarg' to the container itself. This pattern can be described as the delegate pattern (also sometimes also known as strategy pattern).

Using instanceof (type checking)

Example of instanceof use:

// Table and SpecialTable are interfaces
Table table = TableFactory.instance().getDefaultTable();

if (table instanceof "SpecialTable") {
  SpecialTable specialTable = (SpecialTable)table;
  specialTable.specialMethod();
}

table.normalMethod();

Note that when you define your SpecialTable interface you can declare it as extending the Table interface and then only list the extra methods.

Your factory will be producing concrete objects of either type. So you might have a concrete class called BoringTable which implements Table, and a concrete class called ExcitingTable which implements SpecialTable.

Beware instanceof!

It's generally better to avoid things like 'instanceof' (or generally speaking, ifs of any kind which depend on what type an object is). You should favour polymorphism instead. By this I mean having multiple different classes, of a common type, enclosing different behaviour in their implementation code.

Ask yourself this: does the class using something of type Table (which might also be of type SpecialTable) need to care if it's a special table or not? Can you not hide that distinction in some sort of implementation of the SpecialTable -- have it do something different, something extra, that plain old Table does?


答:
to add onto @martijnPieter's answer the minimal change can be implemented by doing a short brute force based on the new and previous passwords (which you both have available)

for example you can iterate over all passwords with a hamming distance of 1 or 2 from the new password and see if it matches an old pass

but you might want to note that this can reduce the confidence of users that you are hashing passwords (as you are essentially saying you can get a previous password back to reject a new password)

Title: How to implement a safe password history

Body:
Passwords shouldn't be stored in plain text for obvious security reasons: you have to store hashes, and you should also generate the hash carefully to avoid rainbow table attacks.

However, usually you have the requirement to store the last n passwords and to enforce minimal complexity and minimal change between the different passwords (to prevent the user from using a sequence like Password_1, Password_2, ..., Password_n). This would be trivial with plain text passwords, but how can you do that by storing only hashes?

In other words: how it is possible to implement a safe password history mechanism?


答:
When the user changes their password, require them to enter their previous password.  You now have access to two plain text passwords, even though you are not storing plain text passwords in your database.

Perform whatever verifications you want on these two passwords.  This won't prevent the user from alternating between two passwords (with a suffix - you can prevent direct alternation per the suggestions in other answers), but it will prevent the more blatant cases.


答:
Several jobs ago, in a different country to the one I now live in, we didn't do time sheets. We got paid a salary. If the work was getting done, then that was the end of it.

When I moved to Australia, time sheets everywhere. Paid what was called a "salary", but with time sheets, and hours recorded. Not quite my commonwealth understanding of a salaried position vs a waged one.

Title: As a programmer, are you required to do timesheets?

Body:
Timesheets are something that I've never been fond of, but none the less something that is a requirement within my company. They don't bother me so much, but they seem to really grind some other people's gears. I suppose I have a few questions, and feedback would be great.

Are you required to do timesheets, assuming you aren't a contractor? (That is understandable to me).

What is the granularity of timesheets that you would be comfortable with or that you use? (ex: all entries must be under two hours).

Would timesheets ever factor into your reasons for not accepting a job or leaving a current one?

How has management within your organization justified timesheets if you aren't billing to a client?


问:
Is it bad to be the only person supporting software you have developed?
My employer has a need for a web-based application to manage and share data within the department, with approximately 50-75 possible users.  I feel I have the ability to write it for them.  I would likely use Python/Django with a MySQL database, so it would be open source.  However, I'm the only IT person in my department (our larger organization has a separate IT support staff with which I often work, but not for web development).  I want to develop this application, but if I leave in 1-2 years, and someone else has to come in after me and support it, will this be seen as a bad decision?

This is assuming all the obvious points -- I will write documentation, I will comment my code, and I will strive to follow good application design principles.  But will that be enough?  In principle, is it acceptable for one person to develop and support an entire web application?  Is this a "do first, then show and ask" kind of situation, or should I be certain it will be adopted by everyone involved first?

With regards to specifics, I work in an academic department of a university that has specific processes for student applicants and for their being admitted.  You have to apply to the university, AND my department separately.  The department-specific process is very manual and pieced together, which is where my development would come in.  We (myself and IT) are already planning on incorporating the additional questions that pertain to my department into the main university application (which IS electronic, and feeds into PeopleSoft), so that solves the front-end piece and everything would be in one place.  But for the faculty and staff to acquire and "digest" that information throughout the admissions process will require an application of some sort, which I would prefer to do "my way".  The IT staff want to develop it ALL in PeopleSoft, and I fear it will be too inflexible and will not be well received by our department, and may still not completely meet our needs.  There are third-party solutions which meet this need perfectly but they are cost-prohibitive.  I would query the data from PeopleSoft and present it how I know the faculty and staff need to see it.  (Getting access to query PeopleSoft is a different battle altogether.)

答:
Being a sole developer is a blessing and a curse. Many people will never get the opportunity though so take it and you will learn a great deal by having to maintain your own mistakes, feeling the pain you will learn many things folks in large corporations never do. The curse part is that you will not get the outside input that can sometimes accelerate you're ability to apply new solutions which you wouldn't have recognized on your own. Moral of the story, take the rare opportunity, but don't stay at it too long as the insularity can cement bad habits without folks to correct you. Also make sure to be active in online communities with other developers to get as much of that feedback as you can. See https://codereview.stackexchange.com/ for this purpose and perhaps search for a forum you can share ideas and get discussion on.

Given your problem scope you need to look into two tools types of which there are many and utilizing these to create your solution will yield a far stabler more comprehensive solution: ETL (Extract Transform Load), and a Reporting Engine. Try to do as little custom work as possible, this will minimize your maintenance work and though integrating tools together may not seem as glamorous as hacking out your own solution, it will display a higher aptitude for seeing the whole picture and recognizing the value of a problem being solved is greater than a solution being made.

The problem domain you detailed is a very common one and it is known in industry by the term "Business Intelligence".

What you want to do is extract data from the peoplesoft database, transform it into useful aggregates for your purposes, and load it into your own MySql database. Following that, you want to generate reports off that MySql database to display information in a useful manner to your colleagues. Usually reporting engines will have things like schedulable executions, and optional automatic e-mails of said reports etc, these are the robustness and comprensiveness features it's nice to get from a reporting engine rather than hand-writing something.

Here are some open source reporting engines I was able to dig up (I know nothing about any of them, the analysis of these solutions and others you may find is on you). Note, there is a significant difference between "charting" and "reporting". Do not confuse the ideas and think reporting just means pretty graphs which won't convey all your information, that's charting. Reporting refers to generating reports with both tabular data and graphs as well as any general information you want to display as you would expect in a report.

Python:

Gerald Reports - http://www.geraldoreports.org/

PyRep - http://code.google.com/p/pyrep/

RLib - http://rlib.sicompos.com/

Solutions in other languages may interoperate well with python so don't ignore them until you do your technical analysis.

Java:

BIRT - http://www.eclipse.org/birt/phoenix/

Jasper - http://www.jaspersoft.com/

Pentaho - http://www.pentaho.com/

G2 - http://code.google.com/p/g2-report-engine/

C++:

ReportLab - http://www.reportlab.com/

OOFILE - http://www.oofile.com.au/reportwriter.html

This question talks about reporting engines with opinions:
https://stackoverflow.com/questions/126622/open-source-reporting-engines

Here are some quick ETL solutions I found.

petl - http://packages.python.org/petl/0.11.1/index.html

pygrametl - http://pygrametl.org/

Simplistic Python ETL - http://www.ohloh.net/p/etlpy


问:
Can I use a project code which has New BSD license but uses a GPL license library?
I want to use the ICSOpenVpn project source code in my commercial application.

If we see the ICSOpenVpn project, it states that its license is New BSD but the libopenvpn.so library it uses is under GNU GPLv2 license.

As per FAQ for version 2 of GNU GPL "If a library is released under the GPL (not the LGPL), does that mean that any program which uses it has to be under the GPL?" The answer says: "Yes, because the program as it is actually run includes the library."

Also, how could ICSOpenVpn change the license to New BSD?

答:
It looks like ICSOpenVpn is in violation of the GPL, at least the GPL as it's interpreted by the FSF.

That shouldn't concern you if you can use the project's source code without using libopenvpn.so, but otherwise I would be very wary. OpenVPN is actually developed by a for-profit company, and while they may turn a blind eye to a small open source project violating their license terms, a commercial application would be quite different.

The alternative would be to simply buy a commercial OpenVPN license. If your application generates significant revenue, that shouldn't be a problem.


问:
Creating a Predicate Builder extension method
I have a Kendo UI Grid that I am currently allowing filtering on multiple columns. I am wondering if there is a an alternative approach removing the outer switch statement?

Basically I want to able to create an extension method so I can filter on a IQueryable<T>  and I want to drop the outer case statement so I don't have to switch column names.

```<code>    private static IQueryable<Contact> FilterContactList(FilterDescriptor filter, IQueryable<Contact> contactList)
    {
        switch (filter.Member)
        {
            case "Name":
                switch (filter.Operator)
                {
                    case FilterOperator.StartsWith:
                        contactList = contactList.Where(w => w.Firstname.StartsWith(filter.Value.ToString()) || w.Lastname.StartsWith(filter.Value.ToString()) || (w.Firstname + " " + w.Lastname).StartsWith(filter.Value.ToString()));
                        break;
                    case FilterOperator.Contains:
                        contactList = contactList.Where(w => w.Firstname.Contains(filter.Value.ToString()) || w.Lastname.Contains(filter.Value.ToString()) || (w.Firstname + " " + w.Lastname).Contains( filter.Value.ToString()));
                        break;
                    case FilterOperator.IsEqualTo:
                        contactList = contactList.Where(w => w.Firstname == filter.Value.ToString() || w.Lastname == filter.Value.ToString() || (w.Firstname + " " + w.Lastname) == filter.Value.ToString());
                        break;
                }
                break;
            case "Company":
                switch (filter.Operator)
                {
                    case FilterOperator.StartsWith:
                        contactList = contactList.Where(w => w.Company.StartsWith(filter.Value.ToString()));
                        break;
                    case FilterOperator.Contains:
                        contactList = contactList.Where(w => w.Company.Contains(filter.Value.ToString()));
                        break;
                    case FilterOperator.IsEqualTo:
                        contactList = contactList.Where(w => w.Company == filter.Value.ToString());
                        break;
                }

                break;
        }
        return contactList;
    }
</code>```

Some additional information, I am using NHibernate Linq. Also another problem is that the
"Name" column on my grid is actually "Firstname" + " " + "LastName" on my contact entity. We can also assume that all filterable columns will be strings.

EDIT Remember this needs to work with NHibernate Linq and AST.

答:
Answering your specific question,

```<code>private static IQueryable<Contact> FilterContactList(
    FilterDescriptor filter,
    IQueryable<Contact> contactList,
    Func<Contact, IEnumerable<string>> selector,
    Predicate<string> predicate)
{
    return from contact in contactList
           where selector(contract).Any(predicate)
           select contact;
}
</code>```

In the case of "Name", you call it as;

```<code>FilterContactList(
    filter,
    contactList,
    (contact) => new []
        {
            contact.FirstName,
            contact.LastName,
            contact.FirstName + " " + contact.LastName
        },
    string.StartWith);
</code>```

You should add an overload as,

```<code>private static IQueryable<Contact> FilterContactList(
    FilterDescriptor filter,
    IQueryable<Contact> contactList,
    Func<Contact, string> selector,
    Predicate<string> predicate)
{
    return from contact in contactList
           where predicate(selector(contract))
           select contact;
}
</code>```

So you can call it like this for "Company" field.

```<code>FilterContactList(
    filter,
    contactList,
    (contact) => contact.Company,
    string.StartWith);
</code>```

This prevents the overhead of forcing the caller to create an array when they only intend to seleect one Field/Property.

What you're probably after is something as follows

To remove that logic completely around defining the selector and predicate need more info on how filter is constructed.  If possible filter should have the selector and predicate as properties for FilterContactList to use that get automatically constructed.

Expanding on that a little,

```<code>public class FilterDescriptor
{
    public FilterDescriptor(
        string columnName,
        FilterOperator filterOperator,
        string value)
    {
        switch (columnName)
        {
            case "Name":
                Selector = contact => new []
                               {
                                   contact.FirstName,
                                   contact.LastName,
                                   contact.FirstName + " " + contact.LastName
                               };
                break;
            default :
                // some code that uses reflection, avoids having
                // a case for every column name

                // Retrieve the public instance property of a matching name
                // (case sensetive) and its type is string.
                var property = typeof(Contact)
                    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                    .FirstOrDefault(prop =>
                        string.Equals(prop.Name, columnName) &&
                        prop.PropertyType == typeof(string));

                if (property == null)
                {
                    throw new InvalidOperationException(
                        "Column name does not exist");
                }

                Selector = contact => new[]
                {
                    (string)property.GetValue(contact, null)
                };
                break;
        }

        switch (filterOperator)
        {
            case FilterOperator.StartsWith:
                Predicate = s => s.StartsWith(filter.Value);
                break;
            case FilterOperator.Contains:
                Predicate = s => s.Contains(filter.Value);
                break;
            case FilterOperator.IsEqualTo:
                Predicate = s => s.Equals(filter.Value);
                break;
        }
    }

    public Func<Contact, IEnumerable<string>> Selector { get; private set; }
    public Func<string, bool> Predicate { get; private set; }
}
</code>```

Your FilterContactList would then become

```<code>private static IQueryable<Contact> FilterContactList(
    FilterDescriptor filter,
    IQueryable<Contact> contactList)
{
    return from contact in contactList
           where filter.Selector(contract).Any(filter.Predicate)
           select contact;
}
</code>```

Body:
Answering your specific question,

private static IQueryable<Contact> FilterContactList(
    FilterDescriptor filter,
    IQueryable<Contact> contactList,
    Func<Contact, IEnumerable<string>> selector,
    Predicate<string> predicate)
{
    return from contact in contactList
           where selector(contract).Any(predicate)
           select contact;
}

In the case of "Name", you call it as;

FilterContactList(
    filter,
    contactList,
    (contact) => new []
        {
            contact.FirstName,
            contact.LastName,
            contact.FirstName + " " + contact.LastName
        },
    string.StartWith);

You should add an overload as,

private static IQueryable<Contact> FilterContactList(
    FilterDescriptor filter,
    IQueryable<Contact> contactList,
    Func<Contact, string> selector,
    Predicate<string> predicate)
{
    return from contact in contactList
           where predicate(selector(contract))
           select contact;
}

So you can call it like this for "Company" field.

FilterContactList(
    filter,
    contactList,
    (contact) => contact.Company,
    string.StartWith);

This prevents the overhead of forcing the caller to create an array when they only intend to seleect one Field/Property.

What you're probably after is something as follows

To remove that logic completely around defining the selector and predicate need more info on how filter is constructed.  If possible filter should have the selector and predicate as properties for FilterContactList to use that get automatically constructed.

Expanding on that a little,

public class FilterDescriptor
{
    public FilterDescriptor(
        string columnName,
        FilterOperator filterOperator,
        string value)
    {
        switch (columnName)
        {
            case "Name":
                Selector = contact => new []
                               {
                                   contact.FirstName,
                                   contact.LastName,
                                   contact.FirstName + " " + contact.LastName
                               };
                break;
            default :
                // some code that uses reflection, avoids having
                // a case for every column name

                // Retrieve the public instance property of a matching name
                // (case sensetive) and its type is string.
                var property = typeof(Contact)
                    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                    .FirstOrDefault(prop =>
                        string.Equals(prop.Name, columnName) &&
                        prop.PropertyType == typeof(string));

                if (property == null)
                {
                    throw new InvalidOperationException(
                        "Column name does not exist");
                }

                Selector = contact => new[]
                {
                    (string)property.GetValue(contact, null)
                };
                break;
        }

        switch (filterOperator)
        {
            case FilterOperator.StartsWith:
                Predicate = s => s.StartsWith(filter.Value);
                break;
            case FilterOperator.Contains:
                Predicate = s => s.Contains(filter.Value);
                break;
            case FilterOperator.IsEqualTo:
                Predicate = s => s.Equals(filter.Value);
                break;
        }
    }

    public Func<Contact, IEnumerable<string>> Selector { get; private set; }
    public Func<string, bool> Predicate { get; private set; }
}

Your FilterContactList would then become

private static IQueryable<Contact> FilterContactList(
    FilterDescriptor filter,
    IQueryable<Contact> contactList)
{
    return from contact in contactList
           where filter.Selector(contract).Any(filter.Predicate)
           select contact;
}


问:
C# coding standards” Use the const directive only on natural constants
I've seen these 2 guidelines in coding c# standard and I’m not sure the what the 2nd one means.

With the exception of zero and one, never hard-code a numeric value; always declare a constant instead.

Use the const directive only on natural constants such as the number of days of the week.

What is the definition of a natural constants and if the number is not a natural constants given the 1st rule how does one declare a constant in c# without the const directive?

So how is the 2nd rule not contradicting the 1st rule for non natural constants?

See http://www.scribd.com/doc/10731655/IDesign-C-Coding-Standard-232 for reference.

答:
You cannot declare a "constant" without the const directive. When it refers to "natural constants" it's simply referring to values which are defined by an immovably obvious guarantee, something that is axiomatic, for example:

There are 7 days in a week. This will never change.

There are 12 inches in a foot. This will never change.

These seem pretty fixed and hard to identify relatably to a real situation though, there are however fixed guarantees similar to this which you can find in your own systems surely.

For example, say you're writing a web service, and you are versioning the contracts as you should, so you have an OblogonRepository service, it would be reasonable to claim inside that service:

This is version 1 of the OblogonRepository. This will never change.

Now that all of that has been said, let me go on to say, this rule sounds very restrictive and I don't particularly agree with it.

It is however very important to understand the behaviour of a const in C#, in relation to this: Everywhere a const is referenced, it will at compile time be replaced by a fixed reference to the literals in the assemblies table. This means if you have other assemblies referencing this const, and you compile them then recompile the assembly with the const with changed values, the referencing assemblies will not have the const value updated until you recompile them.

Do be cautious with consts, but in my personal subjective opinion, this rule is far more restrictive than is useful. Using consts for things like max allowed users or column numbers is completely common idiomatic C#, even though they may change unlike "natural numbers".

Here's a little further reading on consts which details their compile time behaviour:
Link

This article claims a rule which sounds pretty spot on to me (emphasis mine):

Thus, const should be used mainly for values that are not subject to
change, or [can be used] freely if the scope of the const is limited to the same
assembly or smaller.

ContentLicense: CC BY-SA 4.0


答:
I think you can read "Natural Constant" as "This is a well-known and well-understood number, and is unlikely to ever change."  Constants like e and pi meet this definition.

Magic numbers like seeds for pseudo-random number generators are not natural constants and, according to this coding standard, are better served by using the readonly keyword.

Title: C# coding standards” Use the const directive only on natural constants

Body:
I've seen these 2 guidelines in coding c# standard and I’m not sure the what the 2nd one means.

With the exception of zero and one, never hard-code a numeric value; always declare a constant instead.

Use the const directive only on natural constants such as the number of days of the week.

What is the definition of a natural constants and if the number is not a natural constants given the 1st rule how does one declare a constant in c# without the const directive?

So how is the 2nd rule not contradicting the 1st rule for non natural constants?

See http://www.scribd.com/doc/10731655/IDesign-C-Coding-Standard-232 for reference.


答:
Let's pretend that you have been tasked with writing an program that manages a satellite's trajectory in orbit.  You wrote this program expecting the satellite to orbit earth, so all your calculation is done with a gravity constant of 9.81.  Well, NASA decides to send this satellite to the Moon, where the gravity is 1/6 of the earth.  You hard coded the gravity constant in your app, so Joe Schmo goes through your source code, changing all instances of 9.81 to 1.66.  Except Joe Schmo forgot to change 1 formula, and the multi-billion dollar satellite crashes and burns on the moon's surface because 1 formula was using Earth's gravitational constant.  By declaring a constant for gravity and using that constant every place you need gravity, any change to that constant can be implemented by changing 1 line of code, instead of five thousand lines.

So that's the WHY one should use constants instead of hard coding them in.

You cannot declare a constant without using the const directive.  And if you are declaring a constant, use the const directive.  You can only assign a constant a value when you declare it.  For example:

```<code>   public const float Gravity = 9.81;
   Gravity = 1.6;
</code>```

will not compile because you are attempting to change the value of a constant.

A natural constant is something that will never change:  The length of an inch.  The acceleration due to gravity on earth.  The number of days in a week.  The number of days in January.  The ratio of cms to inches.  These are all natural constants.

Body:
Let's pretend that you have been tasked with writing an program that manages a satellite's trajectory in orbit.  You wrote this program expecting the satellite to orbit earth, so all your calculation is done with a gravity constant of 9.81.  Well, NASA decides to send this satellite to the Moon, where the gravity is 1/6 of the earth.  You hard coded the gravity constant in your app, so Joe Schmo goes through your source code, changing all instances of 9.81 to 1.66.  Except Joe Schmo forgot to change 1 formula, and the multi-billion dollar satellite crashes and burns on the moon's surface because 1 formula was using Earth's gravitational constant.  By declaring a constant for gravity and using that constant every place you need gravity, any change to that constant can be implemented by changing 1 line of code, instead of five thousand lines.

So that's the WHY one should use constants instead of hard coding them in.

You cannot declare a constant without using the const directive.  And if you are declaring a constant, use the const directive.  You can only assign a constant a value when you declare it.  For example:

   public const float Gravity = 9.81;
   Gravity = 1.6;

will not compile because you are attempting to change the value of a constant.

A natural constant is something that will never change:  The length of an inch.  The acceleration due to gravity on earth.  The number of days in a week.  The number of days in January.  The ratio of cms to inches.  These are all natural constants.


答:
This is really more of an addendum to @Brian's clever answer.  Hats off also to @Martijn Pieters for adding details about how to brute force the old passwords based on the current one and to @ratchet freak for "hamming distance."  I'm not deleting my answer because I think it provides interesting background to back them up.

State of the art password storage requires using multiple rounds of a strong one-way cryptographic hash (SHA-512+) with unique salt (128-bits+) for each user.  But do not be tempted to store additional information about each password.  The more information you will store about each password, the more you undermine the security of your hashing algorithm.

Example

Consider how easy it becomes to brute-force a password if you know that:

It's 7 characters long

Characters 3-5 are upper-case (4 is lower)

1 and 7 are numbers

6 is a symbol

A US keyboard has 95 printable characters, so knowing that the password is 7 characters long yields 95^7 = 69,833,729,610,000 = 7x10^13 permutations.  If it were truly random, it might take a year to crack this on a single 3Ghz processor. But:

There are only 26 upper-case and 26 lower-case characters

There are only 10 digits yielding 100 possiblities for those two numbers

There are only 32 symbols

So (corrected thanks to @Hellion):

```<code>         26^4 (charcters 2-5 are known upper or lower-case)
        x 100 (characters 1 & 7 are digits)
        x  32 (character 6 is a symbol)
         ====
1,462,323,200 possible passwords.
</code>```

That's 50,000 times easier to crack!  Storing good information to prevent similar passwords in this case has taken your crack time for a 7-character password from a year down to a couple hours.  Decoding all your passwords with on a powerful multi-processor desktop with a good video card and a little patience is now very feasible.  I hope this simple example demonstrates that the more meaningfully you can compare similar passwords, the less secure your hashing will be.

Importance of Strong Hashing

Databases with passwords are stolen regularly, with gargantuan break-ins in the news every month.  Heck, just last month the state of SC lost everyone's social security numbers - oops!  How many more of these breaches are covered up?

Closing Thought

The most frightening thing for me is when people choose the same or similar password for multiple sites so that breaking into one gives the attacker access to them all.  I'd love to see a proven method of preventing that situation, though I think preventing the most common bad passwords would help more than preventing an individual user from reusing their bad password within the same site.  The best I can suggest is a company-wide policy to use a secure password manager that generates highly random passwords for each of your users and stores them securely.

Body:
This is really more of an addendum to @Brian's clever answer.  Hats off also to @Martijn Pieters for adding details about how to brute force the old passwords based on the current one and to @ratchet freak for "hamming distance."  I'm not deleting my answer because I think it provides interesting background to back them up.

State of the art password storage requires using multiple rounds of a strong one-way cryptographic hash (SHA-512+) with unique salt (128-bits+) for each user.  But do not be tempted to store additional information about each password.  The more information you will store about each password, the more you undermine the security of your hashing algorithm.

Example

Consider how easy it becomes to brute-force a password if you know that:

It's 7 characters long

Characters 3-5 are upper-case (4 is lower)

1 and 7 are numbers

6 is a symbol

A US keyboard has 95 printable characters, so knowing that the password is 7 characters long yields 95^7 = 69,833,729,610,000 = 7x10^13 permutations.  If it were truly random, it might take a year to crack this on a single 3Ghz processor. But:

There are only 26 upper-case and 26 lower-case characters

There are only 10 digits yielding 100 possiblities for those two numbers

There are only 32 symbols

So (corrected thanks to @Hellion):

         26^4 (charcters 2-5 are known upper or lower-case)
        x 100 (characters 1 & 7 are digits)
        x  32 (character 6 is a symbol)
         ====
1,462,323,200 possible passwords.

That's 50,000 times easier to crack!  Storing good information to prevent similar passwords in this case has taken your crack time for a 7-character password from a year down to a couple hours.  Decoding all your passwords with on a powerful multi-processor desktop with a good video card and a little patience is now very feasible.  I hope this simple example demonstrates that the more meaningfully you can compare similar passwords, the less secure your hashing will be.

Importance of Strong Hashing

Databases with passwords are stolen regularly, with gargantuan break-ins in the news every month.  Heck, just last month the state of SC lost everyone's social security numbers - oops!  How many more of these breaches are covered up?

Closing Thought

The most frightening thing for me is when people choose the same or similar password for multiple sites so that breaking into one gives the attacker access to them all.  I'd love to see a proven method of preventing that situation, though I think preventing the most common bad passwords would help more than preventing an individual user from reusing their bad password within the same site.  The best I can suggest is a company-wide policy to use a secure password manager that generates highly random passwords for each of your users and stores them securely.


问:
Why does Eclipse need to be restarted after installing a plugin?
As Eclipse uses OSGi to handle modules and bundles, and therefore should be able to hot-deploy them, why does it suggest to restart after installing a plugin "for changes to take effect"?

Has Eclipse hit some OSGi limitation, or is its architecture such that even with hot-deploy, it cannot guarantee that deployments went smoothly and hence takes the safest route by offering a restart?

答:
The Eclipse platform does support dynamically installing plugins without restarting. In the past this option was made available via an "Apply Now" option. Unfortunately for this to work properly the plugin itself also needs to support dynamic behavior. The large majority of Eclipse plugins out there are not dynamic themselves - they don't clean up after themselves, and they don't dynamically react to services or extensions being added/removed after they have started. Therefore the "Apply Now" button was sometimes jokingly referred to as the "I'm feeling lucky" button. Maybe it will work, but maybe some of the plugins currently installed won't handle the dynamic change to the system.

In the end installing plugins is infrequent enough that a restart is the cleanest and safest approach. This is not so much an architectural limitation... making code fully dynamic is hard work in any application framework, and many tool writers clearly don't think it is worth the investment.


问:
Best practice to represent SQL in program source code
Where SQL statements are executed from a program, what is the best practice to store the statement text?

Most often it is in a read only string, in the source file it is executed in.

I think a better approach would be to have a separate text file containing all SQL statements, that are then read in to a dictionary object where the key is the purpose of that statement. Statements can then be executed by using their key, decoupling database implementation from the program and allowing reuse of statements between program objects.

Is this efficient? Is there a better way? Thank you!

答:
The only reason I can think of to treat SQL as data instead of code is if you are dynamically generating SQL statements, and you don't need to store those.

There are actually advantages to going in the other direction; by hard-coding your SQL statements into Stored Procedures, you benefit from certain security and performance optimizations that the RDBMS can provide.

SQL is already naturally "parameterized;" if you need additional flexibility beyond that, you should carefully balance your application requirements against the additional security challenges that will accrue from treating your SQL statements as data.  SQL injection is one example of a potential security leak that can occur.

If you need generalized CRUD (create, read, update, delete) statements for each of your tables, you should use an Object-Relational Mapper to generate them.


答:
What you get when you use a constant is a description of the value and a single point of change. A constant is a hard-coded value. All the uses of the constant variable are replaced with the actual value at compile time.

As for when to use const... you can use a const or you can't. I use const whenever I can, my program will have to track one less variable and will be that much more efficient.


问:
Should I expect my peers to read or practice on a regular basis?
I've been debating asking this question for some time.  Based several of the comments I read in this question I decided I had to ask.

This feels like I'm stating the obvious, but I believe that regular reading (of books, blogs, StackOverflow, whatever) and/or practice are required just to stay current (let alone excel) in whichever stack you use to pay the bills, not to mention playing with things outside your comfort zone to learn new ways of doing things.

Yet, I virtually never see this from many of my peers. Even when I go out of my way to point out useful (and almost always free) learning material, I quite often get a sense of total apathy from those I'm speaking to.

I'd even go so far as to say that if someone doesn't try to improve (or at least stay current), they'll atrophy as technology advances and actually become less useful to the company.

I don't expect people to spend hours a day studying or practicing.  I have two young kids and hours of practice simply aren't feasible.  Still, I find some time; perhaps on the train, at lunch, in bed for a few minutes, whatever.

I'm willing to believe this is arrogance or naivete on my part, but I'd like to hear what the community has to say.

So here's my question: Should I expect (and encourage) the same from my peers, or just keep my mouth shut and do my own thing?

答: It's illogical to expect the improbable.  Most professional developers do very little outside reading.  You should encourage your peers to read more, but most won't.  You can stay in this group and accept your colleagues as they are, or try to find employment with a company or team that hires more selectively.


问:
Automated unit testing, integration testing or acceptance testing
TDD and unit testing seems to be the big rave at the moment. But it is really that useful compared to other forms of automated testing?

Intuitively I would guess that automated integration testing is way more useful than unit testing. In my experience the most bugs seems to be in the interaction between modules, and not so much the actual (usual limited) logic of each unit. Also regressions often happened because of changing interfaces between modules (and changed pre and post-conditions.)

Am I misunderstanding something, or why are unit testing getting so much focus compared to integration testing? It is simply because it is assumed that integration testing is something you have, and unit testing is the next thing we need to learn to apply as developers?

Or maybe unit testing simply yields the highest gain compared to the complexity of automating it?

What are you experience with automated unit testing, automated integration testing, and automated acceptance testing, and in your experience what has yielded the highest ROI? and why?

If you had to pick just one form of testing to be automated on your next project, which would it be?

Thanks in advance.

答:
I feel like acceptance tests are king in this scenario.

If a commit breaks acceptance tests it needs to be sorted out.

Acceptance tests tell you where your software is, unit tests do not.

Therefore unit tests can provide a very false sense of security.


答: Networking is required not only for job hunters, but for employers as well.  Go to meetups and conferences and try to find good programmers who are on the market.  I'm the last person in the world who should be giving you advice on how to do that (I hate networking), but it's worth mentioning.


答:
You should certainly encourage it.  Consider the position pretty much any teacher is in: a roomful of students, most of whom don't really want to be there, just hoping to get by.  Some may be enthusiastic on your subject, but they are the minority.

That said, teachers are valuable--you will reach some of them.  If you're really enthusiastic about something new, it can wear off on people.  So keep trying. Just know it's an uphill battle.

Title: Should I expect my peers to read or practice on a regular basis?

Body:
I've been debating asking this question for some time.  Based several of the comments I read in this question I decided I had to ask.

This feels like I'm stating the obvious, but I believe that regular reading (of books, blogs, StackOverflow, whatever) and/or practice are required just to stay current (let alone excel) in whichever stack you use to pay the bills, not to mention playing with things outside your comfort zone to learn new ways of doing things.

Yet, I virtually never see this from many of my peers. Even when I go out of my way to point out useful (and almost always free) learning material, I quite often get a sense of total apathy from those I'm speaking to.

I'd even go so far as to say that if someone doesn't try to improve (or at least stay current), they'll atrophy as technology advances and actually become less useful to the company.

I don't expect people to spend hours a day studying or practicing.  I have two young kids and hours of practice simply aren't feasible.  Still, I find some time; perhaps on the train, at lunch, in bed for a few minutes, whatever.

I'm willing to believe this is arrogance or naivete on my part, but I'd like to hear what the community has to say.

So here's my question: Should I expect (and encourage) the same from my peers, or just keep my mouth shut and do my own thing?


答:
I'd say the best way is to use Stored Procedures, if the DBMS supports it, for the following reasons:

They centralize the logics so you don't need to keep multiple copies in sync, which seems to be what you cares most.

They centralize the permission control (authorization) to the DBMS.

They are pre-compiled so they run faster.

(minor) The string size sent over the network is smaller (code and DBMS usually run on different servers).

Title: Best practice to represent SQL in program source code

Body:
Where SQL statements are executed from a program, what is the best practice to store the statement text?

Most often it is in a read only string, in the source file it is executed in.

I think a better approach would be to have a separate text file containing all SQL statements, that are then read in to a dictionary object where the key is the purpose of that statement. Statements can then be executed by using their key, decoupling database implementation from the program and allowing reuse of statements between program objects.

Is this efficient? Is there a better way? Thank you!


答:
It is reasonable for a programmer to practice and learn above and beyond one's "day job", but if you work at the average company, it is not probable that many programmers will do so.

My experience is that I am grateful to those who encouraged me to go above and beyond "average".

If you have not already read it, I recommend Robert (Bob) Martin's Clean Coder book.


答:
I'd even go so far as to say that if someone doesn't try to improve
  (or at least stay current), they'll atrophy as technology advances and
  actually become less useful to the company.

That's not your problem. How (and whether) you choose to grow intellectually is your business; how (and whether) your colleagues choose to grow intellectually is theirs. How'd you like it if the guy in the next cube decided that because studying music or a foreign language or mathematics changed his worldview in a way that helped him professionally, you should do it too?

If these folks work for you rather than with you, and if you decide to make continuing education one of the boxes to be ticked at a performance review or just something that you want to encourage, that's one thing. If these folks work with you rather than for you, then you should feel free to say: "hey guys, look at this great article I found -- I think the ideas in here could work really well on our project," but leave it at that. Beyond that, if you don't like how your coworkers maintain their skills you should consider finding some coworkers that are more compatible with your values.


问:
How to move a car around an environment with hills in C++?
I don't have any code for this since I don't know how I am meant to do this.

I have a car and I am able to move it around on a flat plane and I have that working correctly. However, I want it to also be able to move up hills accurately. So that when I drive up a hill the front wheels start going up first and then the back wheels follow like a normal car would. So far all I have managed to be able to do is when one point of the car reaches an incline the whole car moves to that new y value instead of just the section of the car that is supposed to. Does it require some kind of translation and rotation applying to it so that it reacts correctly?

答:
You will need to keep track of the position of the front and rear of the car separately based on the terrain under the car.  Then calculate the transformation matrix directly from the position of the center front and center rear of the car.  Compute orthonormal vectors where one is aligned with the direction of the car, a second is horizontal, and the third is the cross product of the others.  These vectors will form the GL transformation matrix.

Calculating rotation and pitch angles is an unnecessary excursion into spherical coordinates.

It may be even simpler to use a physics library.


问:
How to tell whether your programmers are under-performing?
I am a team lead with 5+ developers. I have a developer (let's call him A) who is a good programmer, who writes good clean, easy to understand code. However he is somewhat difficult to manage, and sometimes I wonder whether he is really under-performing or not.

Our company requires the developers to indicate the work progress in the bug tracker we use, not so much as to monitor the programmers but to keep the stakeholders apprised of the progress. The thing is, A only updates a task progress when it is done ( maybe 3 weeks after it is first worked on) and this leaves everyone wondering what is going on in the middle of the development week. He wouldn't change his habit despite repeated probing. ( It's OK, developers hate paperwork, I do, too)

Recent 2-3 months he on leave quite often due to various events-- either he is sick, or have to attend a lot of personal events etc. ( It's OK, bad things happen in a string. It's just a coincidence)

We define sprints, or roadmaps for each month. And in the beginning of the sprint, we will  discuss the amount of work each of the developers have to do in a sprint and the developers get to set the amount of time they need for each task. He usually won't be able to complete all of them. (It's OK, the developers are regularly missing deadlines not due to their fault).

I am based in Singapore. Not sure if that matters. Yeah, Asians are known to be reticent, but does that matter?

If only one or two of the above events happen, I won't feel that A is under-performing, but they all happen together. So I have the feeling that A is under-performing and maybe-- God forbid--- slacking off.

This is just a feeling based on my years of experience as programmer. But I could be wrong.

It is notoriously hard to measure the work of a programmer, given that not all two tasks are alike, and there lacks a standard objective to measure the commitment of a programmer to your company. It is downright impossible to tell whether the programmer is doing his job or slacking off. All you can do, is to trust them-- yeah, trusting and giving them autonomy is the best way for programmers to work, I know that, so don't start a lecture on why you need to trust your programmers, thank you every much-- but if they abuse your trust, can you know?

Outcome:

I've a straight talk with him regarding my perception on his performance. He was indignant when I suggested that I had the feeling that he wasn't performing at his best level. He felt that this was a completely unfair feeling. I then replied that this was my feeling and I didn't know whether my feeling was right or not. He would have none of this and ended the discussion immediately.

Before he left he said that he "would try to give more to the company" in a very cold tone. I was taken aback by his reaction. I am sure that I offended him in some ways. Not too sure whether that was the right thing to do for me to be so frank with him, though.

My question is: How can you tell whether your programmers are under-performing? Surely there are experience team leads who know better than me on this?

Extra notes:

I hate micromanaging. So all that we have for our software process is Sprint ( where tasks get prioritized and assigned, and at the end of the month, a review of the amount of work done). Developers would require to update the tasks as they go along everyday.

There is no standup meeting, or anything of the sort. Mainly because we have the freedom to work from home and everyone cherishes this freedom.

Although I am the one who sets the deadline, but the developers will provide the estimate for each tasks and I will decide-- based on the estimate-- the tasks that go into a particular sprint. If they can't finish the tasks at the end of the sprint, I will push them to the next. So theoretically one can just do only 1 or 2 tasks during the whole sprint and then push the remaining 99 tasks to the next sprint and still he will be fine as long as justifies this-- in the form of daily work progress updates

答:
Pointless

Daily status updates are pointless. Having people report 'today I am 2.5% complete', 'today I am 3.74% complete' is ridiculous.

It provides no value to the stakeholders, and annoys the people doing the work.

Leave them to their work, undisturbed.

Baseless

On what grounds do you suppose that developer A is 'underperforming'? If his/her work is being done on time, that should be good enough.

You say you hate micromanaging, yet what you have described is exactly that.

Our company requires the developers to indicate the work progress in
the bug tracker we use, not so much as to monitor the programmers but
to keep the stakeholders apprised of the progress.
... Developers would require to update the tasks as they go along
everyday.

This is pointless (see above) nonsense. Your team is not flipping burgers, they are crafting technical solutions. Progress is not linear, nor is it easily measured or even estimated. Even if it was, such daily measurements or estimates have no value.

Dangerous

Reexamine the basis for your 'feeling' that developer A is 'underperforming'. You think he/she could do better, but on the basis of what evidence?

Unhappy != underperforming

Continue as described, and at some point, developer A will likely decide that he/she is under-appreciated, has given enough to the company, and will find another company. Squeezing the last 0.01% of effort from employees is far less important than retaining them for the long term.


问:
Transitioning to asynchronous programming model
Our team is mantaining and developing a .NET web service written in C#. We have stress tested the web service's farm and we have evidence that the actual architecture doesn't scale well, as the number of requests are constantly increasing.

We analyzed Martin Fowler's conclusion in this article, and our team feels that migrating to an asynchronous programming model such as the one described could be the right direction to point to for our service too. My question is: do you think that this "switch" needs a complete rewrite of the application? Has been someone of you been able to adopt APM without rewriting everything and has some insight to share?

Thank you in advance

答:
Use the async and await keywords in C# 5.0.  These keywords allow you to insert the async functionality into the method calls that require it, without having to create callback mechanisms.  The callbacks are created for you automatically by the compiler, under the covers.  This should greatly simplify the refactoring effort.

Anders Hejlsberg describes the async functionality in this video, with a detailed example application and demonstration.


问:
Where does the "mm" come from in GTKmm, glibmm, etc
I understand that the "mm" suffix [in various GTK-associated C++ binding libraries] means "minus minus," but where exactly does it come from?

I understand that there is a programming language called "C--," but if there were bindings (and I'm pretty sure I've seen some), they would be suffixed "--".

TL;DR: Is there some page on gnu.org that explains the "mm" suffix in various C++ bindings or is it just a de facto standard adopted by the open source community with no reasoning behind it?

答:
From gtkmm's documentation:

gtkmm was originally named gtk-- because GTK+ already has a + in the name. However, as -- is not easily indexed by search engines the package generally went by the name gtkmm, and that's what we stuck with.


答:
Bits that are blocking are calls to external services whose response is needed in order, for our service, to provide a meaningful response.

Is there more processing you could do while waiting for the response from these external service calls?  If not then you are out of luck async will only buy you performance if you are able to do more in parallel.

On the other hand if these external services are the only thing needing to be executed in parallel, I would look into futures, they seem like a good fit for kicking off a service call then doing something else while waiting for the result as well as the fact that they would be minimally invasive to your current design.

Title: Transitioning to asynchronous programming model

Body:
Our team is mantaining and developing a .NET web service written in C#. We have stress tested the web service's farm and we have evidence that the actual architecture doesn't scale well, as the number of requests are constantly increasing.

We analyzed Martin Fowler's conclusion in this article, and our team feels that migrating to an asynchronous programming model such as the one described could be the right direction to point to for our service too. My question is: do you think that this "switch" needs a complete rewrite of the application? Has been someone of you been able to adopt APM without rewriting everything and has some insight to share?

Thank you in advance


问:
Migrating from VSS to TFS. What is the benefit of creating separate projects?
We have a Visual SourceSafe installation that 4 developers collaborate on.  Inside that there are 30 or so independent projects in different top level folders.

Is it necessary for us to create a new TFS "Project" for each of those 30 items, or can we simply place them in the same overarching project folder... possibly assigning permissions to each?

The reason I ask is because I'm demo-ing the migration now and it takes a long time to migrate and create the "New Team Project" within Visual Studio in order to create a 1:1 correlation.

What are the other benefits I may get from using separate projects in TFS?

答:
Separate Team Projects in TFS will provide separate scope for permissions and policies on the source tree (e.g., check-in comment requirements), a separate project portal site and reports (if you're using them), separate scope for work items (again, if you're using them), and separate scope for automated build definitions.

You might check out this article "Visual Studio TFS Team Project and Collection Guidance" - http://msdn.microsoft.com/en-us/magazine/gg983486.aspx


问:
In TFS, how should different "releases" be structured? (version 1.0, version 2.0)
I am importing a website into TFS that is stored in SourceSafe as

```<code>$/MyApp 1.0
$/MyApp 2.0
$/MyApp 3.0
$/MyApp 3.5
</code>```

Should I import this as several distinct projects (MyApp1.0 ... ) or as one project called "MyApp"?

答:
As a single "MyApp", then use a branching strategy...

You should consider following a standard branching strategy that contains Development, Main, and Release branches.  It may take a little getting used to if you haven't dealt with branching and merging before, but it will provide benefits when it comes to managing changes when multiple teams or features being developed at the same time.

There is a group called the ALM Rangers that publish guidance on this for TFS (see links below).

TFS Rangers Branching & Merging Guide - http://vsarbranchingguide.codeplex.com/

MSDN Article "Visual Studio TFS Branching and Merging Guidance" - http://msdn.microsoft.com/en-us/magazine/gg598921.aspx


答:
A rule of thumb is to not worry about different TFS projects except when you want different TFS templates. This means different work-item templates, different sharepoint projects sites, different reporting services spaces.

9 times out of 10 people make extra TFS projects based on what should be branches, remember, the only difference between two TFS projects is the template. If you want to use the same work-item templates etc for all your source code, put it all in one TFS project. Multiple TFS projects becomes a pain to manage over time and often is completely unnecessary.

Title: In TFS, how should different "releases" be structured? (version 1.0, version 2.0)

Body:
I am importing a website into TFS that is stored in SourceSafe as

```<code>$/MyApp 1.0
$/MyApp 2.0
$/MyApp 3.0
$/MyApp 3.5
</code>```

Should I import this as several distinct projects (MyApp1.0 ... ) or as one project called "MyApp"?


答:
One project named "MyApp" and then multiple branches representing each release. This article should give you a good overview of how to branch for releases:

http://visualstudiomagazine.com/articles/2010/09/14/tfs2010-branch-by-release.aspx


问:
"Comments are a code smell"
A coworker of mine believes that any use of in-code comments (ie, not javadoc style method or class comments) is a code smell.  What do you think?

答:
No one said this so far in this thread, so I will:

Type names, variable names, function names, method names and comments are just metadata about your code, and has nothing to do with the machine code that the compiler generates (except the names of the exported and debug symbols of course).

Type names and variable names are your nouns, function and method names are your verbs, with these you describe steps to be done. Comments are for everything else.

Some examples:

```<code>double temperature; // In Kelvins.

/**
 * Returns true if ray hits the triangle
 */
bool castRayOnTriangle(Triangle t, Ray r)
{
    //...
    if (determinant == 0)
    {
        /* The ray and the triangle are parallel, no intersection possible.*/
        return false;
    }
    //...
}

/* X algorithm. Visit http://en.wikipedia.org/... for details.*/
<implementation of something difficult to understand for the layman algorithm. >
</code>```

Comments may bacome obsolete, if not updated, but variable and function names can become obsolete too. I recently encountered a bufPtr field in a C structure, which has nothing to do with buffers or pointers. And I saw a inflateBuffer function that does not decompress a deflated data but a complete GZIP file... These are as annoying as outdated comments.

Title: "Comments are a code smell"

Body:
No one said this so far in this thread, so I will:

Type names, variable names, function names, method names and comments are just metadata about your code, and has nothing to do with the machine code that the compiler generates (except the names of the exported and debug symbols of course).

Type names and variable names are your nouns, function and method names are your verbs, with these you describe steps to be done. Comments are for everything else.

Some examples:

double temperature; // In Kelvins.

/**
 * Returns true if ray hits the triangle
 */
bool castRayOnTriangle(Triangle t, Ray r)
{
    //...
    if (determinant == 0)
    {
        /* The ray and the triangle are parallel, no intersection possible.*/
        return false;
    }
    //...
}

/* X algorithm. Visit http://en.wikipedia.org/... for details.*/
<implementation of something difficult to understand for the layman algorithm. >

Comments may bacome obsolete, if not updated, but variable and function names can become obsolete too. I recently encountered a bufPtr field in a C structure, which has nothing to do with buffers or pointers. And I saw a inflateBuffer function that does not decompress a deflated data but a complete GZIP file... These are as annoying as outdated comments.


问:
how do early stage startups hire ninja programmers
I am programmer who just started working on a startup idea. At the moment I want to bring onboard at least one programmer. This programmer should be a ninja - a 10x engineer.

Since early days are probably the most risky for a startup, I want to make sure I approach this problem the best I can.

How do I find these people? and How do I convince them to come onboard?

I would love to hear from people who started their own companies and what their thoughts are about hiring

Update: I would like to get the ninja as a co-founder so besides being a ninja (ie. great programmer with computer science background) he/she has to have a healthy appetite for risk (for great programmers this is not a big deal because they can be hired anytime into mainstream jobs if the startup doesn't work)

答:
I think that in most situations they use the Texas Sharpshooter recruiting approach.

That is, they hire the best they can find, then call them "Ninjas", "Rock stars", or whatever it takes to convince the VC guys that their Web 2.0 App will be da-bomb and no one else could possibly compete with them.