答:
I took a 6 hour coding test at one point.  When I took this test I had fairly high confidence I would be hired - while it came true, I wasn't all that satisfied with the follow-on.

Obviously having lots of employers each asking for 4 hours is excessive.  What the person was looking for in the test I took was my coding style - I was hired because mine was 'closest' to his.  In this context, look at the problem from this perspective: First, is it an interesting problem that solving is worthwhile to you in any case?  After all, you could learn something valuable.

Second, if you can 'pass' the test does it mean you're hired?  If this isn't fairly obvious then you have to decide whether there are other reasons to do it anyway.

Third, they might estimate that it takes '4 hours', but you might find out differently. Do they really know how long this should take?  Most likely the answer is no.  Therefore, they are going to keep testing people on 4 hour deadlines until they realize it won't fit in four hours.  In that case you're wasting your time.  The best approach then is to get aggressive with the hiring manager, and figure out whether you should stop at four hours and give them what you have, or continue until it's done and tell them how long it took.  In short, there may be a character test wrapped up in this, and simply trying to accept it on their terms may reveal inexperience.


问:
Pre-screening coding test - How long is reasonable?
EDIT

After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references.

For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question:

a 4 hours pre-interview, offsite programming test is not usual but

many people pointed it out that for some companies you would interview for much-much longer than that all together

it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company

all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances

I wanted my original question to be about how reasonable to expect 4 hours from me, and how ethical to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange.

However, I found all your answers valuable and thanks for sharing.

ORIGINAL POST

I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own.

Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in.

Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than 4 hours.

Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test)

Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated.

What I came up as a conclusion with this company is that either:

1) My motivation is not good and probably they are looking for someone else

2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them

3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...)

How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?

答:
You may not have 4 hours, but somebody more interested in their company certainly will. I was essentially hired based on a similar task that a company asked me to do beforehand on the task alone. Apparently, writing clean and understandable code, thorough test cases and understandable and coherent design documentation is an abnormality. Actually seeing someone do it blew people away. Anyways, everyone I spoke with at the interview commended me on what I did and I felt like I had to impress nobody in the interview because they had already made up their mind. It was simply a matter of me not giving them a reason to say no by doing something stupid.

So while I agree 4 hours is a fairly large time investment, it also means the task is of sufficient size that you have an opportunity to really show what you are capable of. Your work very well may speak volumes more than you ever could in an actual interview situation.

As a side note: I have tried a similar thing lately but using a much smaller problem and I haven't been happy with the results. Small problems are to trivial to demonstrate enough of the person's knowledge. Plus, trivial problems tend to require the person to recognize some trick/detail necessary to solve the problem.  Thus, there is some balance between taking up too much of a person's time versus not gaining any real benefits because the task is to trivial. I would think a 4 hour task is probably the right amount of time to be complex enough for candidates to demonstrate their skills and not be so long that nobody would bother.

ContentLicense: CC BY-SA 3.0


问:
Using multiple Git repositories instead of a single one containing many apps from different teams?
I am migrating a 10-years-old big CVS repository to Git. It seemed obvious to split this multiple-projects repository into several Git ones. But the decision-makers are used to CVS, therefore their point of view is influenced by CVS philosophy.

To convince them to migrate from one CVS repo to different Git repositories I need to give them some arguments.

When I speak with mates working on Git repo for years, they say that using multiple Git repo is the way to use Git. I do not know really why (they give me some ideas). I am a newbie in this field so I ask here my question.

What are the arguments to use multiple Git repositories instead of a single one containing different applications and libraries from different teams?

I have already listed:

branches/tags impact the whole Git repository files => pollutes other team projects

4GB limit Git repo size but this is wrong

git annotate may be slower on bloat Git repo...

Eamon Nerbonne has noticed the related question:

Choosing between Single or multiple projects in a git repository?

The reason the team managers finally have accepted the split: the single Git repo (550 MB) was requiring 13 minutes to be cloned on Windows (one minute on Linux).

The bloat CVS repo split in 100 Git repositories:

each dead apps in one repo

each stabilized library in one repo (source code almost never changed any longer)

related apps/libs kept together in one repo

moved large files not used for compilation (config...) to other repos (Git does not like large files)

skipped other unrelevant files (*.jar, *.pcb, *.dll, *.so, *.backup ...)

Successfully installed the repo tool used by Android Open Source Project in order to handle all these Git repos:

easy installation on Linux

more difficult on Windows because of Cygwin and NTFS native symlinks requirements

答:
Git tends to experience performance problems when used with large repositories.

To quote Linus:

And git obviously doesn't have that kind of model at all. Git

  fundamnetally never really looks at less than the whole repo. Even if
  you   limit things a bit (ie check out just a portion, or have the
  history go   back just a bit), git ends up still always caring about
  the whole thing,   and carrying the knowledge around.

So git scales really badly if you force it to look at everything as
  one   huge repository. I don't think that part is really fixable,
  although we   can probably improve on it.

Emphasis mine.  That's not to say your company's version control repository is "large," but this is one reason people tend to avoid large repositories within Git.


问:
Is this a good measure of PHP script usage of the system?
I've been trying to see a way to get a measure of how much a PHP script costs of memory to the server. Well, I've found some solutions out there that requires some software to make tests and even require to install something on the server. Those solutions are not what I'm looking for, as I just want a simple measure of the consumption.

My try was to do the following:

```<code><?php
     $initialMem = memory_get_usage();
     /* Script comes here */
     $finalMem = memory_get_usage();
     echo ($finalMem - $initialMem)/1024 . " Kbytes";
?>
</code>```

Where I divided by 1024 to convert from bytes to kilobytes. The idea was that the function memory_get_usage() gets the amount of memory allocated for the execution of the script and so I thought that taking the difference would be a good measure of the usage.

Is this correct? Is the difference between those values a good measure of the usage of memory by the script? If not, how can I get a good measure of this usage without having to install anything on the server?

答:
If your script contains any unset()'s or objects that otherwise perform cleanup during execution, your script could be hogging more memory during execution that you'll see reported. I think you want your final measurement to be peak usage:

```<code> $initialMem = memory_get_usage();
 /* Script comes here */
 $finalMem = memory_get_peak_usage();
 echo ($finalMem - $initialMem)/1024 . " Kbytes";
</code>```

Also, the $finalMem in this scenario is relevant only in optimizing your code. If you're trying to assess the script's impact on overall system performance (sounds like you do), you need to account for PHP's overhead. In that case, you don't need to compute a delta; just report the peak usage at script end.

Body:
If your script contains any unset()'s or objects that otherwise perform cleanup during execution, your script could be hogging more memory during execution that you'll see reported. I think you want your final measurement to be peak usage:

 $initialMem = memory_get_usage();
 /* Script comes here */
 $finalMem = memory_get_peak_usage();
 echo ($finalMem - $initialMem)/1024 . " Kbytes";

Also, the $finalMem in this scenario is relevant only in optimizing your code. If you're trying to assess the script's impact on overall system performance (sounds like you do), you need to account for PHP's overhead. In that case, you don't need to compute a delta; just report the peak usage at script end.


答:
It doesn't matter how much memory PHP is using. As long as there is enough allocated.

PHP runs in a sandbox inside a webserver. The sandbox is allocated a chunk of memory for use by PHP, and when you hit that limit then PHP throws an out of memory exception. You have to either increase the limit in php.ini or change your code.

PHP scripts do not remain executing after a request is made. The script is terminated and the output buffer is sent to the browser. Your sample source code will only tell you how much memory was used for that HTTP request. The amount of memory used by PHP will change depending upon how many concurrent requests are made to the server, and what that server is configured to handle.

I think the default chunk of memory for PHP is 64MB, but I run mine at 2BG because I have command line cron jobs that are very memory hungry.

How much memory PHP uses is peak = 64MB * concurrent requests.

Title: Is this a good measure of PHP script usage of the system?

Body:
I've been trying to see a way to get a measure of how much a PHP script costs of memory to the server. Well, I've found some solutions out there that requires some software to make tests and even require to install something on the server. Those solutions are not what I'm looking for, as I just want a simple measure of the consumption.

My try was to do the following:

```<code><?php
     $initialMem = memory_get_usage();
     /* Script comes here */
     $finalMem = memory_get_usage();
     echo ($finalMem - $initialMem)/1024 . " Kbytes";
?>
</code>```

Where I divided by 1024 to convert from bytes to kilobytes. The idea was that the function memory_get_usage() gets the amount of memory allocated for the execution of the script and so I thought that taking the difference would be a good measure of the usage.

Is this correct? Is the difference between those values a good measure of the usage of memory by the script? If not, how can I get a good measure of this usage without having to install anything on the server?


问:
How to make a method synchronized across all instances of a class
Today I was asked this interview question and could not answer.
If you have two instances of a Person class which has a setAddress method that is synchronized. Now if it was only one object and multiple threads were accessing it, the synchronized will make sure that only one method can access it at a time.

But if there are different objects, one thread will not wait on the other before entering the method.

Now the question is...if I wanted to make the method synchronized across all instances of Person Objects, how do I do that?

答:
Synchronize on the Person.class or create a static LOCK object on which you synchronize:

```<code>synchronized(Person.class){
    //...
}
</code>```

or

```<code>private static final Object LOCK = new Object();

//...
synchronized(LOCK){
    //...
}
</code>```

Either way, we're using a single (static) lock object instance which is common to all callers. Synchronizing on the class mirrors the default behavior of synchronized static methods. But it somewhat exposes the lock, which can be dangerous because for instance, some evil code could synchronize on Person.class and never release the lock, and make your code jam up. Keeping a separate private lock is therefore more secure.

Body:
Synchronize on the Person.class or create a static LOCK object on which you synchronize:

synchronized(Person.class){
    //...
}

or

private static final Object LOCK = new Object();

//...
synchronized(LOCK){
    //...
}

Either way, we're using a single (static) lock object instance which is common to all callers. Synchronizing on the class mirrors the default behavior of synchronized static methods. But it somewhat exposes the lock, which can be dangerous because for instance, some evil code could synchronize on Person.class and never release the lock, and make your code jam up. Keeping a separate private lock is therefore more secure.

ContentLicense: CC BY-SA 4.0


问:
Best way to reference static database data in code?
Many applications include 'static data': data that doesn't really change during the lifetime of the application. For example, you might have a list of Sales Areas that is likely to be a fixed list for the foreseeable future.

It isn't uncommon to find this static data in a database table (often because you want to refer to it in the foreign keys of other tables). A simple example table will have an Id to use as a primary key and a Description. For example, your SalesArea table will have (at least) a SalesAreaId column and a SalesAreaDescription column.

Now, in code you might not want to treat each row of the table the same. For example, you might want to set a default Sales Area on some screens, provide different figures for some areas, or restrict what users can do in other areas.

What is the best way to refer to this static data in code? Why?

Hard-code the descriptions in your code. Use this to look up the SalesAreaId from the database when you need it.

Hard-code the IDs in your code. Use this to look up the SalesAreaDescription when you need it.

Add a column to the table for each purpose, e.g. an "IsDefaultOnProductLaunchScreen" column and so on (there could be lots of these).

Something else.

Are there any other special considerations I should make when dealing with static database data? For example, giving these tables a special name?

答:
My solution to this, which may not work in all situations, is to bind the static database data to a hard-coded enum. Since the problem comes from having dynamic data (database) bound to static logic (code), make this binding explicit (and loose) by having a database table that associates to the enum. Ex:

```<code>LooseDBCodeBinding (database table)
   ID : Int32 (key)
   Name : String
   HardCodedTypeID : Int32

// in code:
public enum LooseDBCodeBinding
{
   TYPE_1 = 1,
   TYPE_2 = 2,
   TYPE_3 = 3 // etc...
}
</code>```

Then write a UI that allows you to easily view the list of LooseDBCodeBinding records, and map them to LooseDBCodeBinding enum values (including supporting "broken" bindings). You can then program around the enum, and design the database around the table key, and it's just this one table that has knowledge of both contexts.

Body:
My solution to this, which may not work in all situations, is to bind the static database data to a hard-coded enum. Since the problem comes from having dynamic data (database) bound to static logic (code), make this binding explicit (and loose) by having a database table that associates to the enum. Ex:

LooseDBCodeBinding (database table)
   ID : Int32 (key)
   Name : String
   HardCodedTypeID : Int32

// in code:
public enum LooseDBCodeBinding
{
   TYPE_1 = 1,
   TYPE_2 = 2,
   TYPE_3 = 3 // etc...
}

Then write a UI that allows you to easily view the list of LooseDBCodeBinding records, and map them to LooseDBCodeBinding enum values (including supporting "broken" bindings). You can then program around the enum, and design the database around the table key, and it's just this one table that has knowledge of both contexts.


答:
This is premature optimization at its worse.

Firstly any modern DBMS will retrieve data from small tables at lightning speed and they all have caching algorithms ranging from good to superb (the more you paid for the DBMS the better the cacheing!). So you are optimizing something that consumes minimal resources.

Secondly you have very little experience of real world business applications if you imagine something like a "sales area" is static data. These are liable to change with every change of Marketing Director or CEO. So you are heading for a world of pain two years down the line.

There are only two ways to go here:-

Store it in a database and access the data with "normal" sql.

Store it in a fancy XML configuration file (possibly accessed via REST or SOAP) which can be easily edited whenever there is "a strategic change of policy".

Title: Best way to reference static database data in code?

Body:
Many applications include 'static data': data that doesn't really change during the lifetime of the application. For example, you might have a list of Sales Areas that is likely to be a fixed list for the foreseeable future.

It isn't uncommon to find this static data in a database table (often because you want to refer to it in the foreign keys of other tables). A simple example table will have an Id to use as a primary key and a Description. For example, your SalesArea table will have (at least) a SalesAreaId column and a SalesAreaDescription column.

Now, in code you might not want to treat each row of the table the same. For example, you might want to set a default Sales Area on some screens, provide different figures for some areas, or restrict what users can do in other areas.

What is the best way to refer to this static data in code? Why?

Hard-code the descriptions in your code. Use this to look up the SalesAreaId from the database when you need it.

Hard-code the IDs in your code. Use this to look up the SalesAreaDescription when you need it.

Add a column to the table for each purpose, e.g. an "IsDefaultOnProductLaunchScreen" column and so on (there could be lots of these).

Something else.

Are there any other special considerations I should make when dealing with static database data? For example, giving these tables a special name?


问:
Having trouble understanding recursion
I have just started learning about recursion but I'm having a hard time understanding it. Please would you recommend any links or books that explain recursion in detail.</p>

答:
Start with a piece of paper that has the number 1 on it and the phrase "change the number by adding one".  Do what is written on the piece of paper.

That quote is our function:

```<code>count = 1
def function():
    global count
    count += 1
</code>```

Modify the note (our function) to say: "change the number by adding one, then do what is written on the note". Do what is literally on the piece of paper - change the number, then do what is written on the paper, which is to change the number and do what is on the paper, which is to change the number and do what is on the paper, ...

Again, that quote is our function:

```<code>count = 1
def function():
    global count
    count += 1
    function() # <- this is what makes this function recursive
               # ie: "do what is written on the paper"

</code>```

That's infinite recursion. When you call the function, it does something, and then it calls itself.

Practical recursion says you need some sort of condition to tell you when to stop. To do that, change what's on the note to read "Change the number by adding one. If the number is less than 100, then do what is written on the paper". Again, that quote is our function:

```<code>count = 1
def function():
    global count
    count += 1
    if (count < 100):
        function()
</code>```

Generally speaking, every proper recursive function needs some sort of terminal condition -- a test that prevents the function from calling itself forever.

Write on a piece of paper "Change the number by adding one, then do what is written on this paper". Put that piece of paper in your pocket as a reminder of what recursion is.

Note: the fact that the example increments a number is not at all related to recursion in general. It's just a simple way to represent "doing some work". A recursive function doesn't necessarily have to increment or decrement a counter. All it needs is some way to determine when there is no more work to be done.

If you still don't understand what recursion is, read this answer to the question "Having trouble understanding recursion".

Title: Having trouble understanding recursion

Body:
Start with a piece of paper that has the number 1 on it and the phrase "change the number by adding one".  Do what is written on the piece of paper.

That quote is our function:

count = 1
def function():
    global count
    count += 1

Modify the note (our function) to say: "change the number by adding one, then do what is written on the note". Do what is literally on the piece of paper - change the number, then do what is written on the paper, which is to change the number and do what is on the paper, which is to change the number and do what is on the paper, ...

Again, that quote is our function:

count = 1
def function():
    global count
    count += 1
    function() # <- this is what makes this function recursive
               # ie: "do what is written on the paper"

That's infinite recursion. When you call the function, it does something, and then it calls itself.

Practical recursion says you need some sort of condition to tell you when to stop. To do that, change what's on the note to read "Change the number by adding one. If the number is less than 100, then do what is written on the paper". Again, that quote is our function:

count = 1
def function():
    global count
    count += 1
    if (count < 100):
        function()

Generally speaking, every proper recursive function needs some sort of terminal condition -- a test that prevents the function from calling itself forever.

Write on a piece of paper "Change the number by adding one, then do what is written on this paper". Put that piece of paper in your pocket as a reminder of what recursion is.

Note: the fact that the example increments a number is not at all related to recursion in general. It's just a simple way to represent "doing some work". A recursive function doesn't necessarily have to increment or decrement a counter. All it needs is some way to determine when there is no more work to be done.

If you still don't understand what recursion is, read this answer to the question "Having trouble understanding recursion".


问:
I have to compromise: DRY, or Command-Query-Separation?
I was recently refactoring a method that was both a command and a query method.

After separating it into a one command method and one query method, I found that there are now multiple places in the code where I am calling the command then getting the value from the query, which seems like a violation of the DRY principle.

But if I were to wrap that common code into a method, that method would be both command and a query. Is this acceptable?

答:
DRY is more important, since it solves a much more fundamental need - avoiding redundant, effectively wasted effort. This is a fundamental thing - one need not be a programmer to understand it.

CQS is a response to the difficulty, in languages with no support for tracking effects, of understanding code that is executed both for its results and its effects. However:

The necessity to execute code for its results cannot be avoided, because this is the basis for composing large programs from small units.

The necessity to execute code for its effects cannot be avoided either, because, outside of mathematics and theoretical computer science, the value of running a program lies on what it observably can do for us.

The necessity to cause effects and produce results in the same code cannot be avoided, because, in practice, we need both effects and compositionality, not just one or the other.

The actual solution to the problem of tracking effects being too hard for unaided humans is, of course, to have computers aid us humans! A similar thing can be said about tracking intricate relationships between runtime values (such as the validity of array indices), for which exceptions and runtime-enforced contracts constitute (non-)solutions.

In conclusion, "solutions" like CQS merely get in the way of designing programs according to sound principles based on reality. Go for DRY.


问:
Collection interfaces in C#, coming from Java
In Java, I'm used to declaring collections using the most-abstract interface possible and then constructing them using the concrete implementation that makes sense at the time. It usually looks something like this:

```<code>public class MyStuff {
    private Map<String, Address> customerAddresses;
    private List<ToDoItem> tasks;
    private Set<Person> people;

    public MyStuff() {
        customerAddresses = new HashMap<String, Address>();
        tasks = new ArrayList<ToDoItem>();
        people = new HashSet<Person>();
    }
}
</code>```

This allows me more flexibility to change a collection's implementation later when all I really depend on is the high-level interface (i.e. I need something to store key-value pairs, or something to store ordered data), and it's generally considered a standard "best practice" in Java.

I'm just starting to program in C#, though, and I'm not sure if there's an equivalent practice for C#'s collections hierarchy. Collections in C# differ from collections in Java in several ways: Collection is a concrete type, the ICollection interface exposes similar methods to Java's Set while the ISet interface specifies a lot more features, and the key-set or value-set of a Dictionary is not an ISet, to name a few. Does it make sense to do something like this in C#?

```<code>public class MyStuff {
    private IDictionary<String, Address> customerAddresses;
    private IList<ToDoItem> tasks;
    private ISet<Person> people;

    public MyStuff() {
        customerAddresses = new Dictionary<String, Address>();
        tasks = new List<ToDoItem>();
        people = new HashSet<Person>();
    }
}
</code>```

Or are there different "standard" interfaces and implementations to use for such collections? Should I be using ICollection and Collection in place of either the Set or the List? I'm tempted to use the C# classes and interfaces that "look closest" to the Java ones I'm used to, but I'd rather use the setup that better fits with C# paradigms and standards.

答:
IEnumerable<T> is the interface to use.  It is the most basic interface available for collection type objects.  IEnumerable<T> is able to be used in foreach loops.  It also contains a number of quite useful extension methods, which allow you to do anything from convert it to a list by calling ToList(), filtering results by calling Where(x => { //filtering functionality } and all sorts of other things.

The other interface to use is IDictionary, which is the interface to use for dictionaries.  ConcurrentDictionary<TKey, TValue> is probably the most useful of the standard concrete dictionary types as it is designed (funnily enough) for concurrency.

Whatever you do, avoid using List<T> outside of local variables.

The other thing to note is that LinkedList<T> does not implement the IList<T> interface.

Body:
IEnumerable<T> is the interface to use.  It is the most basic interface available for collection type objects.  IEnumerable<T> is able to be used in foreach loops.  It also contains a number of quite useful extension methods, which allow you to do anything from convert it to a list by calling ToList(), filtering results by calling Where(x => { //filtering functionality } and all sorts of other things.

The other interface to use is IDictionary<U, V>, which is the interface to use for dictionaries.  ConcurrentDictionary<TKey, TValue> is probably the most useful of the standard concrete dictionary types as it is designed (funnily enough) for concurrency.

Whatever you do, avoid using List<T> outside of local variables.

The other thing to note is that LinkedList<T> does not implement the IList<T> interface.


问:
Why does the US government disallow dynamic languages for secure projects?
I know some people that are currently working on a project for the US military (low security level, non-combat human resources type data).

An initial state of the project code was submitted to the military for review, and they ran the program through some sort of security analyzer tool. It returned a report of known security issues in the code and required changes that needed to be implemented before delivery of the final product.

One of the items that needed to be resolved was removal of part of the project that was written in Ruby as it is a dynamic language.

What is the background/reason for not allowing a dynamic language to be used in a secure setting? Is this the government being slow to adopt new technologies? Or do dynamic languages pose an additional security risk compared to static languages (ala C++ or Java)?

答:
I spent some time interviewing with the DOD (Department of Defense), for a position writing code for the F-16's MMU. Without violating any non-disclosures: the MMU is the computer unit which controls nearly all the F-16's functions. It is (obviously) critical that no errors, such as run-time bugs, occur during flight. It's equally critical that the system perform real-time computing operations.

For this and other historical reasons, all code for this system is written in or compiled to ADA, a static object-oriented programming language.

Because of Ada's safety-critical support features, it is now used not
  only for military applications, but also in commercial projects where
  a software bug can have severe consequences, e.g. avionics and air
  traffic control, commercial rockets (e.g. Ariane 4 and 5), satellites
  and other space systems, railway transport and banking. For
  example, the fly-by-wire system software in the Boeing 777 was written
  in Ada.

I hate to quote too much, but this explains really well why exactly static languages (like ADA) are used for projects like this:

A large number of compile-time checks are supported to help avoid bugs
  that would not be detectable until run-time in some other languages or
  would require explicit checks to be added to the source code. For
  example, the syntax requires explicitly named closing of blocks to
  prevent errors due to mismatched end tokens. The adherence to strong
  typing allows detection of many common software errors (wrong
  parameters, range violations, invalid references, mismatched types,
  etc.) either during compile-time, or otherwise during run-time. As
  concurrency is part of the language specification, the compiler can in
  some cases detect potential deadlocks. Compilers also commonly check
  for misspelled identifiers, visibility of packages, redundant
  declarations, etc. and can provide warnings and useful suggestions on
  how to fix the error.

Ada also supports run-time checks to protect
  against access to unallocated memory, buffer overflow errors, range
  violations, off-by-one errors, array access errors, and other
  detectable bugs. These checks can be disabled in the interest of
  runtime efficiency, but can often be compiled efficiently. It also
  includes facilities to help program verification. For these reasons,
  Ada is widely used in critical systems, where any anomaly might lead
  to very serious consequences, e.g., accidental death, injury or severe
  financial loss. Examples of systems where Ada is used include
  avionics, railways, banking, military and space technology.

Ada's dynamic memory management is high-level and type-safe. Ada does
  not have generic (and vague) "pointers"; nor does it implicitly
  declare any pointer type. Instead, all dynamic memory allocation and
  deallocation must take place through explicitly declared access types.
  Each access type has an associated storage pool that handles the
  low-level details of memory management; the programmer can either use
  the default storage pool or define new ones (this is particularly
  relevant for Non-Uniform Memory Access). It is even possible to
  declare several different access types that all designate the same
  type but use different storage pools. Also, the language provides for
  accessibility checks, both at compile time and at run time, that
  ensures that an access value cannot outlive the type of the object it
  points to.


问:
Can i sell my own software that uses parts of PSEXEC
I just have a quick licensing question about PSEXEC by sysinternals.

As some of you may know if you have ever used PSEXEC, it is confusing to learn at first. I have created a program that makes it easier to use, and was wondering if I am allowed to sell that program (even if PSEXEC is included with it?). I looked in the sysinternals license agreement, but couldn't really find the answer to my question.

The agreement is here: http://technet.microsoft.com/en-us/sysinternals/bb469936

The main download and info page for PSEXEC is here: http://technet.microsoft.com/en-us/sysinternals/bb469936

Please let me know if I will be allowed to sell my program.

(I assume i am on the right stackexchange site, but let me know if I should move my question)

Thanks!

答:
I am no lawyer, but from the agreement:

You may not:

...

rent, lease or lend the software;

transfer the software or this agreement to any third party;

Makes it pretty clear that selling it is a no-go.

Anyways, psexec uses pretty standard API calls to do its work, you'd be better off just reimplementing it, in fact I think they used to have, and still might, a doc explaining just how all the sysinternals tools worked.


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答: Design Patterns mostly. They are over used and under utilised.</p>

ContentLicense: CC BY-SA 2.5


问:
Do I need to return error: null in JSON response?
When designing a RESTful API that uses JSON to respond to requests, I usually return an object like this when an error happens:

```<code>{
  "error": "Something bad happened",
  "error_code": "XXX"
}
</code>```

Do I need to have a "error": "" or "error": null in my object when there is no error?

答:
If the response is a success, don't include error in your response. Example:

```<code>GET /product/15406/

200 OK
{
    "id": 15406,
    "name": "A cookie with pieces of chocolate",
    "price": 1.45,
    "is-available": true
}
</code>```

On the other hand, an error would look like:

```<code>GET /product/nan/

403 Forbidden
{
    "error": 5020,
    "error-message": "The specified product identifier cannot be converted to a number."
}
</code>```

Notes:

Do change the HTTP status code on error. Returning 200 OK when something got wrong is silly.

Don't include error fields in the success response. Why would you? You aren't including price or is-available in the erroneous response, are you?

Do use strings for text and numbers for numbers. Your "error_code": "XXX" looks like you are putting a number as an error code, but passing it as a string. If it's a number, it should remain a number in the response. Note that using strings as error codes may be a good solution: error 5020 is not extremely explicit; error "InvalidProductIdentifier" is.

Body:
If the response is a success, don't include error in your response. Example:

GET /product/15406/

200 OK
{
    "id": 15406,
    "name": "A cookie with pieces of chocolate",
    "price": 1.45,
    "is-available": true
}

On the other hand, an error would look like:

GET /product/nan/

403 Forbidden
{
    "error": 5020,
    "error-message": "The specified product identifier cannot be converted to a number."
}

Notes:

Do change the HTTP status code on error. Returning 200 OK when something got wrong is silly.

Don't include error fields in the success response. Why would you? You aren't including price or is-available in the erroneous response, are you?

Do use strings for text and numbers for numbers. Your "error_code": "XXX" looks like you are putting a number as an error code, but passing it as a string. If it's a number, it should remain a number in the response. Note that using strings as error codes may be a good solution: error 5020 is not extremely explicit; error "InvalidProductIdentifier" is.


问:
Find pattern in a string
How would one approach the following question:

We have two strings: a normal alphanumeric string and a pattern string. the pattern string can be composed by alphanumeric chars plus the char "?" and "*"

We want to check if the first string match the pattern, where the ? means that every char (alphanumeric) is permitted in that position, while * allows to have a sequence of alphanumeric chars.

答:
If I was asked this question in an interview, this would be how I would begin figuring out my algorithm. Note: the first two cases are just how I would arrive at the final answer, and they aren't actually a suitable answer until number 3.

I would start with the easy case which is where there is no '?' or '*'. I would do a scan of the search string until I hit the first character in the pattern string. At that point, go to the next character in the pattern string and see if it matches the next character in the search string. If it does, continue, otherwise move back to the beginning of the pattern string but keep the current position in the search string. When you run out of characters in the pattern string, then you have a match, if you run out of characters in the search string, you don't.

Then move to the case of a '?' character. Do the same algorithm as before, except when you hit a '?' in the pattern string, go ahead and skip the current position in the search string and get the next character in the pattern string. Continue as you did in case 1.

Then move to the final case of '?' and '*' permitted. Do the same as the other two cases, except this time when you hit a '*', immediately find the next character after the '*' in the pattern string. Then scan the search string to find that next character. If you find it, keep going with case 1 & 2, when you are out of pattern characters you have a match. If you run out of search string characters, go to the next instance in the search string of the character immediately after the '*' in the pattern string and try again. If you still haven't found it at this point, then you could have had a false alarm with the very first match. So, start at the point where you started your last match check and do this whole process over again. When you hit the end of the search string, you don't have a match.

At this point, you have solved the problem. The solution is O(n) in most cases, but the worst case could be O(n^2)

Title: Find pattern in a string


答:
The difference between ICollection and Set is that ICollection represents an arbitrary collection of items, while Set and ISet represent mathematical sets, e.g. no duplicate items and items have no defined order. .NET's version has more methods, because those operations are expected from mathematical sets. The reason why IDictionary doesn't implement ISet is most probably because then KeyValuePair<Key,Value> must have defined proper equality, which would transitively require Value to have defined equality. But IDictionary only requires equality to be defined for Key and not Value.

Also you should learn about the Difference between List(T) and Collection(T) in .NET

Title: Collection interfaces in C#, coming from Java

Body:
In Java, I'm used to declaring collections using the most-abstract interface possible and then constructing them using the concrete implementation that makes sense at the time. It usually looks something like this:

```<code>public class MyStuff {
    private Map<String, Address> customerAddresses;
    private List<ToDoItem> tasks;
    private Set<Person> people;

    public MyStuff() {
        customerAddresses = new HashMap<String, Address>();
        tasks = new ArrayList<ToDoItem>();
        people = new HashSet<Person>();
    }
}
</code>```

This allows me more flexibility to change a collection's implementation later when all I really depend on is the high-level interface (i.e. I need something to store key-value pairs, or something to store ordered data), and it's generally considered a standard "best practice" in Java.

I'm just starting to program in C#, though, and I'm not sure if there's an equivalent practice for C#'s collections hierarchy. Collections in C# differ from collections in Java in several ways: Collection is a concrete type, the ICollection interface exposes similar methods to Java's Set while the ISet interface specifies a lot more features, and the key-set or value-set of a Dictionary is not an ISet, to name a few. Does it make sense to do something like this in C#?

```<code>public class MyStuff {
    private IDictionary<String, Address> customerAddresses;
    private IList<ToDoItem> tasks;
    private ISet<Person> people;

    public MyStuff() {
        customerAddresses = new Dictionary<String, Address>();
        tasks = new List<ToDoItem>();
        people = new HashSet<Person>();
    }
}
</code>```

Or are there different "standard" interfaces and implementations to use for such collections? Should I be using ICollection and Collection in place of either the Set or the List? I'm tempted to use the C# classes and interfaces that "look closest" to the Java ones I'm used to, but I'd rather use the setup that better fits with C# paradigms and standards.


答:
If I had to actually solve this problem I'd probably just transform the pattern into a regular expression pattern by replacing * with [A-Za-z0-9]* and ? with [A-Za-z0-9] then use regex to match the string against the pattern.

For interview I'd probably then go on to give an answer like Jonathan's as I guess that is what they are looking for

Title: Find pattern in a string

Body:
How would one approach the following question:

We have two strings: a normal alphanumeric string and a pattern string. the pattern string can be composed by alphanumeric chars plus the char "?" and "*"

We want to check if the first string match the pattern, where the ? means that every char (alphanumeric) is permitted in that position, while * allows to have a sequence of alphanumeric chars.


答:
Pragmatic approach:

Convert pattern string into a valid Regex string.

Simply replace ? with \w and * with \w* or \w+

Use the regex to search the pattern

Title: Find pattern in a string


答:
I'd just call the function. fnmatch(3) (POSIX.2; on other platforms I'd just dig it from some posix emulation library). Most other language besides C/C++ have such function too.

If the interviewer wasn't happy with that answer, I'd count it against the company for deciding whether they made the review.

If the interviewer liked the answer, but asked about implementing that function, there is:

simple recursive variant (using arbitrary pseudo-code) (O(mn) worst):

```<code>bool matches(string:string, pattern:string):
    if pattern[0] == '*':
        # assuming || short-circuits this order is the faster on average
        return matches(string, pattern[1:]) || matches(string[1:], pattern)
    elseif pattern[0] == '?' or pattern[0] == string[0]:
        return matches(string[1:], pattern[1:])
    else:
        return False
</code>```

the complicated variant compiling the finite automaton (O(n) in time traded for higher space complexity for the automaton/time complexity of the preprocess, which I think is O(m2), but am too lazy to derive precisely right now).

Title: Find pattern in a string

Body:
I'd just call the function. fnmatch(3) (POSIX.2; on other platforms I'd just dig it from some posix emulation library). Most other language besides C/C++ have such function too.

If the interviewer wasn't happy with that answer, I'd count it against the company for deciding whether they made the review.

If the interviewer liked the answer, but asked about implementing that function, there is:

simple recursive variant (using arbitrary pseudo-code) (O(mn) worst):

bool matches(string:string, pattern:string):
    if pattern[0] == '*':
        # assuming || short-circuits this order is the faster on average
        return matches(string, pattern[1:]) || matches(string[1:], pattern)
    elseif pattern[0] == '?' or pattern[0] == string[0]:
        return matches(string[1:], pattern[1:])
    else:
        return False

the complicated variant compiling the finite automaton (O(n) in time traded for higher space complexity for the automaton/time complexity of the preprocess, which I think is O(m2), but am too lazy to derive precisely right now).


问:
Does dealing with legacy code help one evolve as a programmer?
I'm a Java developer with a bit more than a year of experience which places me somewhere above a junior, but not among mid-level developers yet. Recently I was offered a long-term project which is about studying an existing banking application code for 4 months and then introducing changes when needed. As a not-so-experienced programmer I'm looking for ways to develop and I wonder what such a project might give.

Would you consider dealing with a big and probably not-so-well written application a good practice for a beginner?

答:
It will absolutely help you, but you need to be careful.

You need to make sure you learn from the legacy code. How do you know what is good and what is bad? Maybe you can recognise the pros and cons of different patterns/methods, but if you were a junior developer just starting out, you may not be able to.

And stay too long in that first job, and you might not be learning or building enough skills and end up stuck there.


问:
Would Single Page Apps(thin server-thick client architectures) kill server side languages like Java, C++
Single Page Apps strips server down to a REST api. If SPAs are the modern and better way of developing web apps, then would someday JavaScript rule the world and server-side languages like Java, C++ etc would not be the prominent skill companies look for?

Or are there still parts of huge and prominent web apps like youtube, amazon.com which just can't be all ported to client side JavaScript and would continue to depend upon server-side languages.

答:
Sorry, but it is a simplistic view of programming...

As said in the comments of your question, there is generally more than a simple DB access between the Rest service handler and the data.

For example, in an e-commerce application, you have to handle security, to gather the purchases related to a client, to apply some rules to compute the shipping or rebates, to propose some items related to previous purchases, to generate a PDF invoice, and so on.

There is still some logic to manage! Even if the server is "thin", it is not non-existent.
Beside, a "thick" client has limits, in speed and memory: you won't upload a big blob of data, you will paginate it, it is done on the server side. You need to keep some information confidential, and processing it on the client side is then not a good idea (a good hacker can alter the client side logic or inspect the data).

And it is not the only, dominant trend anyway. A framework like Vaadin inverts the GWT paradigm by using generic JS components, processing the logic on the server side and sending the relevant information to the client side which is then only a glue.

No, server side languages are not dead!


问:
When being a technical genius is not enough to be a successful developer?
There has been a lot of discussion around the excellent question "Will high reputation in Stack Overflow help to get a good job?". I immediately agreed with JoshK that basically said "No" (I'll will explain why), but Joel chimed in with lot of convincing facts which made me upvote him as well.

My question is what other skills (other than being a technical genius) do you require from a developer? To get the job, or to keep it.

I believe being a genius is far from being enough. I have met many technical geniuses in various companies I have worked for that impressed me a lot, but sadly in lot of cases, they were simply fired after a few months or put in ivory towers (mainly because of internal mutiny from other developers). I've seen many in personal distress as a result of this which I understand.

That's why I'm a big fan of non-technical questions for technical positions. I like to know how the candidate will interact with others (including non-technical employees), how much consideration he will have for the business, if he will work for the desired outcome, and so on.

I would like to know what you require from your developers and WHY it's important (after all, you hire someone to write code, don't you? Why would you want him to be assertive?). Ideally, I'd like you to come up with an example question you would ask during interviews in support of your answer.

答:
These are more traits than skills, but I'd likely suggest these are still worth finding in someone to be a successful developer:

Versatility would be another trait I'd put on there.  Sometimes a developer may have to fill roles outside of pure development,e.g. business analyst, architect, or tester.  I know I've had various parts on projects where I'm doing something other than designing or writing code and this should be something to see in another.  Not everyone can accept taking on those other roles.  Ask what kinds of situations has the developer had in the past where they had to fill another role and how that turned out.

Humility would be another that I'd likely put as a requirement.  Ego can cause lots of trouble in some places and not everyone can accept that there may be someone better at something than they are.  If someone else has a better idea, let that be what gets done.  You might have a sample of the developer's code that you ask them to critique and see how well can they correct themselves or not.

Pride would be another to put down there.  This is somewhat in contrast to the previous quality, but if someone doesn't have a sense of pride in their work what kind of quality do you think it is?  Not being satisfied is slightly different here as probably a lot of developers can be perfectionistic.  Ask of what past project do they feel most proud?

Self-motivation would also be an important skill to see.  What drives them?  How well can they articulate this?  "Office Space" has this line from Peter Gibbons:

Eight, Bob. So that means that when I
  make a mistake, I have eight different
  people coming by to tell me about it.
  That's my only real motivation is not
  to be hassled, that and the fear of
  losing my job. But you know, Bob, that
  will only make someone work just hard
  enough not to get fired.

That is something to which I suspect many developers and non-developers can relate.  Why are you doing the job you do?  This can be a good question but do look for the sincerity and authenticity in the response as sometimes canned answers can occur that one has to spot.

Curiosity would be last on my list to add.  The desire to see how something works, to learn new technologies and step outside one's comfort zone, are other markers for this that can be found in successful developers.  A short story on how one gets into development may be a way to see this trait though another is to ask them about something they haven't seen and see if they have a, "Well that could be interesting to explore," or a "Oh brother, not that again," type of look.


答:
I'm going to take a crack at this solution.  Jonathan has the general gist of it, but I saw a possible problem and I like the challenge of attempting a solution myself.

This solution is assuming of course that regular expressions are not an option.  Regular expressions exist expressly to match tricky patterns like this in an efficient manner, and I'm a strong believer in programmers writing modular libraries which do one thing and one thing well, and all other programmers using that library rather than re-invent the wheel.

My take on this is that * creates an interesting situation where a number of solutions become possible and not just one.  In order to check the matching string for all these possibilities, you must quite literally check for all these possibilities.  To give an  example, I could have pattern a*bc to match azbbc, and if you assume the b following the z belongs to the section after the *, you don't match what would otherwise be a match.  Likewise, if you didn't assume the b following the z to belong to the section after the *, then you no longer match azbc.

So a simplified version of the algorithm is the following (implementation can be seen here):

```<code>function search(matchString, pattern) {
    var i = 0;

    // For each character in matchString and pattern
    for(; i<matchString.length && i<pattern.length; i++) {
        if(pattern[i] === '*') {
            // Star!  If pattern has been valid up to now, then
            // only one match must be valid after the *, so pass responsibility
            // to searchStar.
            var subMatchString = matchString.substring(i, matchString.length);
            var subPattern = pattern.substring(i+1, pattern.length);

            return searchStar(subMatchString, subPattern);
        } else if (pattern[i] !== '?') {
            // If it isn't * and it isn't ?, then compare characters.
            // If characters don't match, we know it isn't valid.
            if(matchString[i] !== pattern[i]) {
                return failure(matchString, pattern);
            }
        } // else if (pattern[patternIndex] === '?') {
            // Ignore '?'.. move along
        //}
    }
    if(i === pattern.length) {
        return success(matchString, pattern);  // pattern exhausted
    } else {
        return failure(matchString, pattern);  // matchString ended with unmatched pattern
    }
}

// This function is called when star is encountered in pattern and
// pattern thus far is correct.  This applies search on remaining
// match string and returns true if even one proves true.
function searchStar(matchString, pattern) {
    while(matchString.length > 0) {
        if(search(matchString, pattern)) {
            return true;
        }
        matchString = matchString.substring(1, matchString.length);
    }
    return failure(matchString, pattern);
}
</code>```

Efficiency can probably be improved by doing little things like ignoring duplicated "*"s and things of that sort, but I tried to keep it as simple as possible so that the reader can understand the general idea.

Hope that helps!

Title: Find pattern in a string

Body:
I'm going to take a crack at this solution.  Jonathan has the general gist of it, but I saw a possible problem and I like the challenge of attempting a solution myself.

This solution is assuming of course that regular expressions are not an option.  Regular expressions exist expressly to match tricky patterns like this in an efficient manner, and I'm a strong believer in programmers writing modular libraries which do one thing and one thing well, and all other programmers using that library rather than re-invent the wheel.

My take on this is that * creates an interesting situation where a number of solutions become possible and not just one.  In order to check the matching string for all these possibilities, you must quite literally check for all these possibilities.  To give an  example, I could have pattern a*bc to match azbbc, and if you assume the b following the z belongs to the section after the *, you don't match what would otherwise be a match.  Likewise, if you didn't assume the b following the z to belong to the section after the *, then you no longer match azbc.

So a simplified version of the algorithm is the following (implementation can be seen here):

function search(matchString, pattern) {
    var i = 0;

    // For each character in matchString and pattern
    for(; i<matchString.length && i<pattern.length; i++) {
        if(pattern[i] === '*') {
            // Star!  If pattern has been valid up to now, then
            // only one match must be valid after the *, so pass responsibility
            // to searchStar.
            var subMatchString = matchString.substring(i, matchString.length);
            var subPattern = pattern.substring(i+1, pattern.length);

            return searchStar(subMatchString, subPattern);
        } else if (pattern[i] !== '?') {
            // If it isn't * and it isn't ?, then compare characters.
            // If characters don't match, we know it isn't valid.
            if(matchString[i] !== pattern[i]) {
                return failure(matchString, pattern);
            }
        } // else if (pattern[patternIndex] === '?') {
            // Ignore '?'.. move along
        //}
    }
    if(i === pattern.length) {
        return success(matchString, pattern);  // pattern exhausted
    } else {
        return failure(matchString, pattern);  // matchString ended with unmatched pattern
    }
}

// This function is called when star is encountered in pattern and
// pattern thus far is correct.  This applies search on remaining
// match string and returns true if even one proves true.
function searchStar(matchString, pattern) {
    while(matchString.length > 0) {
        if(search(matchString, pattern)) {
            return true;
        }
        matchString = matchString.substring(1, matchString.length);
    }
    return failure(matchString, pattern);
}

Efficiency can probably be improved by doing little things like ignoring duplicated "*"s and things of that sort, but I tried to keep it as simple as possible so that the reader can understand the general idea.

Hope that helps!


问:
When to Use workflow engines?
I've worked in past on some of the workflow engines as programmer but never had a clarity on why we chose the work-flow engines in first place. And as programmer I know that there are at least 100 ways to do anything when you are writing code but only few of the ways are the best!

I still don't understand which use cases are best solved by workflow engines (or rather their concept) than designing a good DI enabled application. I'm looking for any general characteristics of domain-neutral use cases, where work-flow engines are one of the the best options.

So my question is: What are general characteristics of a requirement which can be taken as a signal for opting for a good workflow engine and coding around it?

答:
From a HR business perspective, work flow engines are very important.

They provide a structured process, even if it is the same every time.

They provide transparency

Who requested the change,

When was it requested,

Who approved etc.

This transparency helps to drive the process and promotes ownership.

Assuming the forms are integrated and intelligent, supporting business logic, it also has a dramatic effect on timeline, processing efficiency and data quality. Security is also be a consideration and containing sensitive information in a secure system is much preferable to having paper forms lying around waiting to be signed. It is also much more mobile. After a recent implementation, one manager told me that it saved him a lot of hassle getting things posted to him for signing as he traveled a lot.

On behalf of HR: Long live workflow !!!

Title: When to Use workflow engines?


问:
JSON object and storage of nosql
I have read Would a NoSQL DB be more efficient than a relational DB for storing JSON objects? and am building a small test project in Asp.Net. I have a webapi up in Azure. It returns a List<Company> and Company is my object which has several properties and child list and a lat/long value.

```<code>//id, name etc.
public List<Certification> Certifications { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
public GeoCoordinate Cordinate // etc. GeoCoordinate is from System.Device reference
</code>```

I return this List of companies and use the JSON output.
Now internally, loading this list I load the complete list of companies out of a json file. and if there is no file, a file will be created. This is all good. But the Latitude and Longtitude is empty on the initial basis. So I fill it using googles reverse geocode. That works, but has a request limit. So I'd like to load the list and if lat/long is empty, retrieve the values from google's service and store it. But I am looking for a solution not to store the complete json list to a file again. And I am not looking for a relational database solution, because that is something that I have done enough. Now I have read about mongoDB. But it is a bit hard to set up on Azure. I have had Redis on Azure. What easy and fast solution do you recommend for me to store my list of objects? Do you even recommend it to store it as JSON? or something else? like XML? and use xpath to update values?
So I am looking for an architecture/design to update all lat/longs untill google gives the quota limit error and give it a go next try I access the list of companies.

ps. I do not want to store a list of Certification's. I am curious if I can keep it as property of company and store the complete company project.

答:
I'm gonna show how I would solve this using the Starcounter database to store the data and using it's internal web server to fetch the data as JSON models. The application model is automatically the database if [Database] attribute is set.

The database

```<code>[Database]
public class Company{
   public String Name;
   public String RegistrationNumber;
   ... and so on
   public IEnumerable<Certificate> Certificates{
         get{
            return Db.SQL("SELECT c FROM Certificate where c.Position=?",this);
         }
   }

   private Coordinate Coordinate;
   public double Latitude{
        get{
            if(Coordinate == null){
                 AssureCoordinates();
            }
            return Coordinate.Latitude;
         }
   }
   public double Longitute
        get{
            if(Coordinate == null){
                 AssureCoordinates();
            }
            return Coordinate.Longitute;
         }
   }

   private void AssureCoordinates(){
          ... fetch from whatever source and set to Coordinate
   }
</code>```

And then in the integrated web server I would define a JSON model for the Company:

```<code>{
     Name:"ACME Ltd",
     RegistrationNumber:"555-5555",
     Longitude:"123.4",
     Latitude:"123.4",
     Certificates:[
        {
            ... certifcates properties
        }],
     $:{DataType:"Company"},
     $Certificates:{DataType:"Certificate"
 }
</code>```

This JSON model will be automatically bound to the persistent data in the database upon request.

And lastly register the REST verb+URI to respond to:

```<code>Handle.GET("/company/?", (String registrationNumber) =>
{
    CompanyModel cModel = new CompanyModel();
    Company comp = ... find company in DB using SQL
    cModel.Data = comp;
return cModel;
});
</code>```

Now a JSON model of the requested company would be returned and all data is filled automatically from the database. The Coordinate will be fetched if not set upon first call to Long/Lat. You could of course also return a list of these Companies as well.

This setup will make your regular database act like a JSON source, and you can skip the regular web server as well.

Hope this helped you on how to solve this problem using a NoSQL database!

Title: JSON object and storage of nosql

Body:
I'm gonna show how I would solve this using the Starcounter database to store the data and using it's internal web server to fetch the data as JSON models. The application model is automatically the database if [Database] attribute is set.

The database

[Database]
public class Company{
   public String Name;
   public String RegistrationNumber;
   ... and so on
   public IEnumerable<Certificate> Certificates{
         get{
            return Db.SQL("SELECT c FROM Certificate where c.Position=?",this);
         }
   }

   private Coordinate Coordinate;
   public double Latitude{
        get{
            if(Coordinate == null){
                 AssureCoordinates();
            }
            return Coordinate.Latitude;
         }
   }
   public double Longitute
        get{
            if(Coordinate == null){
                 AssureCoordinates();
            }
            return Coordinate.Longitute;
         }
   }

   private void AssureCoordinates(){
          ... fetch from whatever source and set to Coordinate
   }

And then in the integrated web server I would define a JSON model for the Company:

{
     Name:"ACME Ltd",
     RegistrationNumber:"555-5555",
     Longitude:"123.4",
     Latitude:"123.4",
     Certificates:[
        {
            ... certifcates properties
        }],
     $:{DataType:"Company"},
     $Certificates:{DataType:"Certificate"
 }

This JSON model will be automatically bound to the persistent data in the database upon request.

And lastly register the REST verb+URI to respond to:

Handle.GET("/company/?", (String registrationNumber) =>
{
    CompanyModel cModel = new CompanyModel();
    Company comp = ... find company in DB using SQL
    cModel.Data = comp;
return cModel;
});

Now a JSON model of the requested company would be returned and all data is filled automatically from the database. The Coordinate will be fetched if not set upon first call to Long/Lat. You could of course also return a list of these Companies as well.

This setup will make your regular database act like a JSON source, and you can skip the regular web server as well.

Hope this helped you on how to solve this problem using a NoSQL database!


问:
How to maximise the features of MySQL when used with php
I asked this question a while back on SO (https://stackoverflow.com/questions/15506040/maximising-the-features-of-php-and-mysql-when-used-together) but it's a recurring topic, so I thought I'd ask in a different way over here.

Basically, we are stuck with the infamous php and MySQL combination (for various reasons), and are trying to produce applications which follow best-practice as much as possible. We notice that time and again, we are tightly coupling the application to the database and vice-versa, despite trying to adhere to SOLID principles.

One of the main reasons is to maximise the features of a relational database (such as strict datatypes, hierarchical data structures, relationships, enforcing foreign keys, firing triggers, etc.) This means that some of the application logic bleeds over into SQL. However, there are features that other RDBMS's offer which MySQL doesn't (such as CHECK constraint most notably) so, we end up using php to get round those.

This means we end up using php for some of things MySQL doesn't do well and we use MySQL to do things which aren't feasible in php.

So, even though every text book encourages programmers to keep things loosely coupled, does anyone have any examples of how to overcome limitations you have come across, or examples of other applications that mix the two up in a similar way?

答:
According to this answer, you can solve the CHECK CONSTRAINT problem in the database layer:

https://stackoverflow.com/a/14248038

Keep in mind that the best practices for an OOP project assume that your application reside in the oop code, and that the database exists to store data from those objects (through a vendor provided or custom ORM layer).  The expectation is that SQL is used mainly to translate objects into the database for permanent storage, not for application logic.

There are also best practices for SQL applications.  Many applications are driven almost entirely by a database, with heavy use of stored procedures, triggers, views and other SQL features which are coupled to that database.  In this type of application, the php code is mainly fetching data and handling user input, handling less of the application logic.

Both PHP/MySQL are widely used for rapid development, but neither would be mistaken for the 'head of the class' in best practice support in OOP/SQL respectively.  This sometimes causes the pain you describe when implementing features, as you have to mix the two types of applications mentioned above (which then couples the application together).  If that results in an acceptable application with better business results, it may be worth the tradeoff.

In the end, if the application can perform reliably and implement the required features under the current workflow, then the best choice is to save the architecture discussion for the next application.  If this can not be done is a reasonable manner, then consider what type of architecture you wish to have and work to migrate the application.


问:
Using GPL code with MPL code
I've done a spot of Googling, and all I can find is information on using code under the MPL in a larger GPL licensed project.
What I really want to know is: can I included GPL(v3) licensed code(/binaries) in a larger MPL(2.0) licensed project?

My understanding so far is that I can't, and that any project which uses GPL software must also be released under the GPL. Is this correct?

If this is correct, can I write software and release it under the MPL, even if it depends on a GPL library, as long as I don't distribute the GPL licensed parts with my MPL licensed parts?

And, if I then want to distribute both parts as a "larger work", how would the overarching GPL affect my MPL code?

答:
Disclaimer, this is similar to my other answer on MIT & GPL, but there are some nuances involved with MPL.

can I included GPL(v3) licensed code(/binaries) in a larger MPL(2.0) licensed project?

Short answer: No, you can't*.  They'll become subject to the copyleft.

* See the longer answer as this is one of the trickier ones

Long answer:

Reference 1 ) The Wikipedia article on license compatibility has a good section on GPL compatibility:

Many of the most common free software licenses, such as the original MIT/X license, ... are "GPL-compatible". That is, their code can be combined with a program under the GPL without conflict (the new combination would have the GPL applied to the whole).

[emphasis added]

Reference 2 ) And more explicitly from the FSF FAQ on GPL compatibility:

It means that the other license and the GNU GPL are compatible; you can combine code released under the other license with code released under the GNU GPL in one larger program.

And just for edification, here's the FSF's comments on various licenses

FSF has a number of comments on the MPL license.

Short version is that your combined work must be released as GPL.

Where it gets tricky

Let's say we have project Foo licensed under MPL, and project Bar licensed under GPL and which wants to use Foo.

Bar+Foo is allowed since the licenses are compatible, and the release of Bar+Foo must be GPL as Bar is GPL.  Foo, by itself and without Bar or Bar+Foo, is still available under the MPL license.  Said another way, Bar+Foo has no license impact upon Foo itself.

The resulting license of the project combination is a forward acting event for the combination only.  It is not a retroactive event.  MPL takes this a step further with section 3.3 and explicitly requires the owner of Bar+Foo to provide Foo's distribution in MPL form.

So if someone else wants to take Foo and do something else with it, they are still free to do so without the copyleft provision of the GPL.  However, if they take Bar+Foo, delete Bar and only use +Foo then they are still bound by the terms of the GPL since Bar+Foo was GPL'd.

In my opinion, this is about as close as a license can get to nullifying the viral effect of GPL. The owners of Foo are making sure that it continues to live and be advertised as MPL while still letting you do what you want with your GPL'd application.

You also asked:

If this is correct, can I write software and release it under the MPL, even if it depends on a GPL library, as long as I don't distribute the GPL licensed parts with my MPL licensed parts?

No, this is not correct.  It will be GPL since it depends upon a GPL library.

And, if I then want to distribute both parts as a "larger work", how would the overarching GPL affect my MPL code?

You'll distribute the broader work as GPL.

You'll also need to provide the smaller MPL work as MPL.

Title: Using GPL code with MPL code


问:
How do you put a price on your source code?
I was asked to sell the source code (along with existing users) of small utility app I created years ago. I've investigated how to put a price on the source code but so far haven't come up with a good solution.

I've searched the net, but haven't found anything useful. Then I came across a few others who also sold their source code with users, but their prices seem unrealistically high. For example, one person calculated price per user at about $200. He had 80 users and ended up selling the source with users for $30k. How did he come up with this price?

Can I find a good price with this formula:

(number of users x app price) + (app price x num of new users in one year)

?

If this is a good formula, how do you price source that doesn't yet have users?

答:
In theory, the price would be determined by the effort which was required to create the application. If a single person worked for two months non-stop (i.e. including weekends) to create the app and the average price per hour of a freelancer of this skill (minus all the taxes) is $200/hour, 200 × 8 × 30 × 2 = 96 000. This means that one can sell this app for $96 000.

In practice, the price is determined by the demand. If nobody wants the source code of your app, you can give it for free, it won't change anything. On the other hand, if a company with lots of money is hugely interested in your app, the price will grow consequently.

If you're face to face with a potential buyer who's strong at negotiation and has leverage on you (for example the buyer is a company which has enough potential to rewrite your app from scratch; you, on the other hand, urgently need money), then the price can drop to the extremes.

The fact that the price is determined by the demand also means that it involves a broad range of parameters, some being completely unrelated to the source code:

Is the code high or low quality?

Is there a good documentation?

Is it written using standards and internationally recognized practices?

Is it using popular third-party libraries?

Is there a support?

Is the code easy to implement in other applications?

Is the infrastructure (version control, bug tracking system, deployment in one step, etc.) set correctly and can be easily reused?

Is the application tested enough?

Is it reviewed by pairs?

Is it marketed enough?

Is it presented well? A dedicated website done by professional designers presenting many aspects of the source code as a product will inevitably help.

etc.

Another important point is to know exactly what's sold. There is a certain gap between selling the right to capitalize on the application by selling licenses to the customers, and selling the right to do whatever the buyer likes to do with the source code. Depending on the precise formulation of the contract, the price can vary a lot, because in one case, the buyer won't be able to do nearly anything, while in other cases, he will be able to create huge profits. Again, this is pure negotiation, similar to the negotiation in any other domain.


答:
Selling the source code for an app is very much like selling a business.

The standard formula is price = revenue * 3 + assets.

The multiplication of 3 is a factor of supply and demand. The more buyers a business has the higher the multiplier. When we hear about a business being purchased by ABC Corp in the news, it's often for a large figure. Those businesses can have a multiplier of 5 or higher.

For businesses that don't have a revenue history, then they depend upon an evaluation. The evaluation is an estimate of projected revenue and the multiplier is applied to that.

So we can calculate the multiplier for your example;

1.875 = 30000 / 16000 = 30000 / (200 * 80)

Assuming he sold all his licenses in 1 year, he (your example) would have a multiplier of 1.875 with no additional assets. That's not a very good deal for the programmer. Especially when you factor in future upgrades from those users adding to revenue.

Why is it not a good deal?

The buyer can recover his costs in less than 2 years. Most people take longer to pay off a car loan.

When we speak to the buyer in terms of setting a price, we discuss how long the buyer would like to recover his investment and start profiting from his purchase.

You are saying I'm giving up this source code, and its future revenue to you. The price is set based upon an estimate of what the future would be.

If you have not received any revenue from your source code, then you will have to argue with the buyer what the evaluation of its future revenue will be.

Title: How do you put a price on your source code?

Body:
I was asked to sell the source code (along with existing users) of small utility app I created years ago. I've investigated how to put a price on the source code but so far haven't come up with a good solution.

I've searched the net, but haven't found anything useful. Then I came across a few others who also sold their source code with users, but their prices seem unrealistically high. For example, one person calculated price per user at about $200. He had 80 users and ended up selling the source with users for $30k. How did he come up with this price?

Can I find a good price with this formula:

(number of users x app price) + (app price x num of new users in one year)

?

If this is a good formula, how do you price source that doesn't yet have users?


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
For me, the craziest (and quite possibly, funnest) was

See this 10 million lines of code in (out-dated web technology)?  Write
  a compiler to convert it to a working Asp.net site.

It never spit out a working version (of course, I tried to tell them it was impractical), but it was fun anyways.


问:
Using multiple Git repositories instead of a single one containing many apps from different teams?
I am migrating a 10-years-old big CVS repository to Git. It seemed obvious to split this multiple-projects repository into several Git ones. But the decision-makers are used to CVS, therefore their point of view is influenced by CVS philosophy.

To convince them to migrate from one CVS repo to different Git repositories I need to give them some arguments.

When I speak with mates working on Git repo for years, they say that using multiple Git repo is the way to use Git. I do not know really why (they give me some ideas). I am a newbie in this field so I ask here my question.

What are the arguments to use multiple Git repositories instead of a single one containing different applications and libraries from different teams?

I have already listed:

branches/tags impact the whole Git repository files => pollutes other team projects

4GB limit Git repo size but this is wrong

git annotate may be slower on bloat Git repo...

Eamon Nerbonne has noticed the related question:

Choosing between Single or multiple projects in a git repository?

The reason the team managers finally have accepted the split: the single Git repo (550 MB) was requiring 13 minutes to be cloned on Windows (one minute on Linux).

The bloat CVS repo split in 100 Git repositories:

each dead apps in one repo

each stabilized library in one repo (source code almost never changed any longer)

related apps/libs kept together in one repo

moved large files not used for compilation (config...) to other repos (Git does not like large files)

skipped other unrelevant files (*.jar, *.pcb, *.dll, *.so, *.backup ...)

Successfully installed the repo tool used by Android Open Source Project in order to handle all these Git repos:

easy installation on Linux

more difficult on Windows because of Cygwin and NTFS native symlinks requirements

答:
TL;DR; the equivalent of a git repository is a CVS module, not a CVS repository.

CVS is designed with a notion of modules being a subdivision of a repository, and it is common to use CVS repositories with several modules having a quite independent life.  As an example, it is easy to have branches specific to one module and not present in another.

git has not be designed with a notion of module, each git repository is limited to one module in CVS term.  When you create a branch, it is valid for the whole repository.

Thus, if you want to import a CVS repository with several modules in git, you better create a repository per module, especially if the modules have a more or less independent life and don't shares things like branch and labels.  (Due to different usage patterns of branches in CVS and git, you may even investigate the usefulness to have one repository per CVS branch; but for a migration from CVS to git, it is probable that your workflow will at the start be similar enough to a CVS workflow that it doesn't worth the pain).


问:
Designing new application from scratch, TDD, MVC, OOD based
I'm about to improve my skills in all that is related to designing applications from scratch using proper OOD principles, involving MVC pattern and using TDD approach to do it.

I have a project for that. I also finished reading a book by Matt Zandstra: PHP Objects, Patterns and Practice

And my question is still left unanswered...

How do I start designing from scratch? Should I start using TDD immediately? It doesn't feels comfortable when u have nothing implemented yet. Should I use code spaghetti just to build working prototype first, understand the scope and needs and only then rewrite all using proper OOD and TDD?

I'd love to get any advice, how to work towards something considered "RIGHT TO DO", or any book that will actually lay down things of how to build the applications form scratch, or design an architecture and dependencies, rather than just throwing lifeless implementation sample codes of Design patterns like Zandstra did.

Thanks!

UPD:
Basically, my question is:
Is it a good idea to immediately start new project from using TDD and proper OOD, or first write something that works using the most horrible and fastest ways and then refactor everything or rewrite from scratch after you got some idea of how you want your application to look like?

答:
There's a Lynda.com course called Foundations of Programming: Object-Oriented Design out there where the person giving the course says "when you sit in the front of a code editor, look at the blinking cursor and think now what do I do? the answer always is step away from the code and pick paper and pencil". He says that for a good reason: you can't develop something without understanding first what do you need to develop and how you are going to implement things.

In your question it seems that what you are doing is exactly go straight to the code editor and trying to use OOP without doing first what is called object oriented analysis and design (I've said it seems because I don't really know if you did this process before or not). The idea is that before trying to code something you must know what to code.

So there's a five steps approach that you can follow:

Gather the requirements

Describe the application

Identify the main objects

Describe the interactions

Create a class diagram

Once you did this, in the end you'll have a good class diagram that will point to you what to develop. Look that this will give you a notion of what the application looks like without having to develop a prototype first in another programing paradigm. Now, when developing each method, I recommend that you use TDD.

So, programming first in another paradigm and then changing later to OOP will be much more painful than starting the right way with OOP. There are good books on object oriented analysis and design out there and there's also this Lynda.com course. Obviously the books and the course are paid but it's worth to purchase this kind of material, since can help a lot in cases like that.


问:
Erlang and Go concurrent programming, objective differences between CSP and Actors?
I was looking into concurrent programming in Erlang and Go programming languages. As per my finding they are used Actor model and CSP respectively.

But still I am confused with what are the objective differences between CSP and Actors? is it just theoretical different only but the same concept?

答:
In practice, there is very little difference: both represent separate units of execution whose primary interface with the outside world is via messages.

The differences are in the implementation details of the languages. Here are a few such details:

Channels in Go are typed; if you want to send messages with different data, you need separate channels. With Erlang, one receive gets everything sent to the process and must pattern-match (in Go, you would use a select with multiple cases, so the code would look very similar, just with different channels).

Anyone can read or write a Go channel. In Erlang, anyone can send to a process, but only that process will receive. This becomes important if you want to divide a task between multiple workers: in Erlang you need to create a distribution process, while Go can simply share a channel.

Erlang provides a (mostly) transparent path to distributing processes on multiple hosts/VMs. Goroutines are confined to a single process (although there are libraries for distribution).

Error handling is very different. Erlang treats each process as independent: an error in one process (say divide-by-0) will not affect any other processes unless you explicitly link them (although something waiting for a message from the dead process will hang). Goroutines all run in the same process space; a divide-by-0 will take down the entire program.

In Erlang, data is immutable. This means that all communication between a process and the outside world takes place through messages. Go allows you to share state between goroutines (although you shouldn't).

This last point is, I think, the most important. While both use messages as the primary means of communication, Erlang makes much stronger guarantees about how and when state can change.


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
Our legacy VB6 code, you can open any Module or form code page and find a screen full of Public or Global #&@! variables declared at the top, being referenced from all over the @&!!(*!# program. ARGH!!!!

(Whew, I had to get that out :-) )


答:
Git migration help page from Eclipse suggests to reorganize the CVS/SVN directory tree into multiple Git repositories:

Now is a great time to refactor your code structure.
  Map the current CVS/SVN directories, modules, plugins, etc. to their new home in Git.
  Typically, one Git repository (.git) is created for each logical
  grouping of code -- a project, a component, and so on.

The arguments:

The trade-off here is that each additional Git repository
  adds extra overhead to your development process -
  all Git commands and operations happen at the level of a single Git repository.
  On the flip side, each repository user will have an entire copy
  of the repository history, making very large repositories cumbersome
  to work with for casual contributors.

Title: Using multiple Git repositories instead of a single one containing many apps from different teams?

Body:
I am migrating a 10-years-old big CVS repository to Git. It seemed obvious to split this multiple-projects repository into several Git ones. But the decision-makers are used to CVS, therefore their point of view is influenced by CVS philosophy.

To convince them to migrate from one CVS repo to different Git repositories I need to give them some arguments.

When I speak with mates working on Git repo for years, they say that using multiple Git repo is the way to use Git. I do not know really why (they give me some ideas). I am a newbie in this field so I ask here my question.

What are the arguments to use multiple Git repositories instead of a single one containing different applications and libraries from different teams?

I have already listed:

branches/tags impact the whole Git repository files => pollutes other team projects

4GB limit Git repo size but this is wrong

git annotate may be slower on bloat Git repo...

Eamon Nerbonne has noticed the related question:

Choosing between Single or multiple projects in a git repository?

The reason the team managers finally have accepted the split: the single Git repo (550 MB) was requiring 13 minutes to be cloned on Windows (one minute on Linux).

The bloat CVS repo split in 100 Git repositories:

each dead apps in one repo

each stabilized library in one repo (source code almost never changed any longer)

related apps/libs kept together in one repo

moved large files not used for compilation (config...) to other repos (Git does not like large files)

skipped other unrelevant files (*.jar, *.pcb, *.dll, *.so, *.backup ...)

Successfully installed the repo tool used by Android Open Source Project in order to handle all these Git repos:

easy installation on Linux

more difficult on Windows because of Cygwin and NTFS native symlinks requirements


问:
What makes it hard to monetize browser extensions?
With the monetization of mobile apps being so popular, I'm surprised that extension developers are still mostly relying on donations as their primary form of compensation for their software.

While this is, of course, not a problem, I find myself wondering why browser extensions and plugins are generally exempt from monetization unlike plugins designed for software like Visual Studio and Photoshop are very often available only with purchase.

What makes broswer extensions different, and has anyone had any success charging for a browser extension?

Relevant: http://www.quora.com/Monetization/How-do-browser-extensions-monetize

答:
It depends on what you mean by "monetized".

I use the NoScript extension for Firefox.  While this is free (as in beer) software, the author solicits donations and has links on his product site from project sponsors.

OTOH, the Firefox Add-ons site doesn't provide any obvious way to buy browser add-ons, so that is clearly an impediment for folks who would wish to sell them ...


答:
As other answers have pointed out, the demand for the product is the essential criterion, but that is very difficult to establish. An easier way to work out what the product is worth is to calculate what it would cost to redevelop. If yours is the only example of its type, this is what you would be competing against: the cost to the seller to develop the program itself (or pay for it to be developed). I wouldn't necessarily attempt to sell it at this price, but it might be considered as a lower bound.

There have been some studies on the total cost it would take to develop a codebase from scratch, mostly involving lines of code. See for example: http://en.wikipedia.org/wiki/COCOMO, or here for a concrete example.


答: I agree that communications is paramount, but I have experienced a failure in an excellent coder who wouldn't show other engineers the use of his processes. I was able to duplicate his processes and show them to others but without his help. He got fired because he wouldn't teach.</p>

Title: When being a technical genius is not enough to be a successful developer?

Body:
There has been a lot of discussion around the excellent question "Will high reputation in Stack Overflow help to get a good job?". I immediately agreed with JoshK that basically said "No" (I'll will explain why), but Joel chimed in with lot of convincing facts which made me upvote him as well.

My question is what other skills (other than being a technical genius) do you require from a developer? To get the job, or to keep it.

I believe being a genius is far from being enough. I have met many technical geniuses in various companies I have worked for that impressed me a lot, but sadly in lot of cases, they were simply fired after a few months or put in ivory towers (mainly because of internal mutiny from other developers). I've seen many in personal distress as a result of this which I understand.

That's why I'm a big fan of non-technical questions for technical positions. I like to know how the candidate will interact with others (including non-technical employees), how much consideration he will have for the business, if he will work for the desired outcome, and so on.

I would like to know what you require from your developers and WHY it's important (after all, you hire someone to write code, don't you? Why would you want him to be assertive?). Ideally, I'd like you to come up with an example question you would ask during interviews in support of your answer.