问:
How to model and query spatial responsibilites of company local branches
what are best practices, to model and query spatial responsibilities of company local branches?
My company has many local branches which are all in general responsible for 1 city. This is the easiest case. However, there are some exceptional cases. Here's a list of all possible cases:

branch a is responsible for city a (general case)

branch a is responsible for city a, b and c

branch a is responsible for disctricts 1 and 2 of city a, whereas branch b is responsible for districts 3, 4 and 5 of city a

branch a is responsible for city a and for Foostreet of district 2, whereas branch b is responsible for district 2 of city a

branch a is responsible for city a and for odd housenumbers of Foostreet of district 2, whereas branch b is responsible for district 2 of city a

branch a is responsible for city a for all customers whose surname begin with letters A-F, whereas branch b has G-K, and branch c has ....

branch a is responsible for city a in case of handling Foos, whereas branch b is responsible for city a in case of handling Bars

These are the possible responsibility cases, which could of course also be mixed. The planned system should provide the answer to the question: "Which branch is responsible for city a (or b or c ...)?". If there are exceptional cases, then the question has to be more specific.

Is it possible to provide hints like: "City a has more than one branch, please chose a district!" or "For which case are you asking? Responsible branch for handling Foos, Bars, ....?"

The question which would most likely to be asked is: "Which branch is responsible for Foostreet 345 in 12345 Foocity?"

My requirements are Java Enterprise and a mySQL Database. It may be possible to use MongoDB or Neo4j if it really makes more sense.

I already have database with every city, district, zipcode and street, with which the data could be "connected".

I hope this question doesn't sound like: "Please do my job for me.", but my experience in spatial domain modelling is almost zero.

答:
Since all your criteria are not strictly geographic, I think what you're looking for falls more closely under faceted search.  Faceted search allows the user to "drill down" until they get the information they want, in this case the responsible branch.  You see it most frequently on shopping sites.  You do a general search, then a list of criteria, or "facets," appears on the left side.  The user then chooses a price range, or a review rating, or a brand name, etc.  Searching for computers gives you a different list of facets than searching for clothing.

In your case the facets would be the city, the district, the street, odd or even house numbers, etc.  You may not be able to use solr's faceted search directly, but that should give you a good place to start.


问:
Why isn't the Microsoft Public License compatible with the GPL?
According to this GNU Project page, regarding Microsoft Public License (Ms-PL):

This is a free software license; it has a copyleft that is not strong, but incompatible with the GNU GPL.

They do not explain why it is incompatible. I cannot find any satisfactory answers nor explanations via Google.

答:
In general, the GPL states that you can use non-GPL licensed code in your GPL-licensed product provided that the non-GPL license does not impose more restrictions than the GPL. In other words, you can freely use 3-clause-BSD-licensed code in your GPL project. This doesn't change the license of the BSD-licensed code - the GPL is viral only to code that uses GPL-licensed code, not to code that is used by GPL-licensed code (that would be unreasonable and in general impossible). On the other hand, the 4-clause-BSD license contains an additional clause about advertising, which doesn't exist in the GPL, and so is incompatible.

I see two candidates for the offending clauses in the Ms-PL. One is 3c, which requires the preservation of not only copyright notices (that's pretty much universal across licenses), but also patent, trademark and attribution notices. The other is the second part of 3d, which imposes a restriction on the compiled form of the code that is not there in this form in the GPL. But IANAL, so I'm not sure about this.

Note also that the Ms-PL contains a patent provision similar to that of the Apache License, which makes it incompatible with the GPLv2, but not the GPLv3 (which added similar wording of its own). See the description on GNU's website: http://www.gnu.org/licenses/license-list.html#apache2

ContentLicense: CC BY-SA 3.0


问:
Is Ant still in the "mainstream" for Java builds?
We have been slowly replacing batch command files (windows .bat) which were simply jarring up the classes compiled in the developers IDE, with more comprehensive Ant builds (i.e. get from CVS, clean compile, jar, archive, email, etc.)

I've spent a lot of time learning (and debugging issues) with Ant, so I'm most comfortable using it for these tasks.  But I wonder if Ant is still in as wide usage as it was when I first started learning, or whether "the world has moved on" to something newer (and maybe slicker). (I've started to see more Maven build stuff distributed, which I've never used, for example.)

The practical import of this question, is whether I push new developers to learn Ant, or whether they should be learning something else for builds?

I'm never too on top of the trends, so it would be great to hear from other Java developers what they think is the best build tool, and what they think new developers should be learning.

答:
Maven has been on the rise for many years, and now I need to learn it. Things will always be changing, and to know that Ant is losing its position is not a bad thing.

Maven may only be the up and comer for a short time, but if it makes our job easier, then it is worth investing the time to learn.


问:
Some questions about ClearCase
I am a mercurial person. I even use it as an incremental backup tool. I used to use SVN and CVS.

In a recent project, I had to to use clearcase and encountered lots of issues with it. For example, I could not figure out how to recursively include a whole tree of code without writing a script or using awk or find. Is there a way to accomplish this easier?

I also believe (but not sure) that clearcase integrates issue/bug management with the code. I would not like to have the managing of my code revisioning tightly encumbered with the issues, any suggestions?

My further questions are:

Is clearcase in obsolence as a version control env? Is it likely that in the project I am working compelling me to use clearcase simply because it is a legacy project?

It gives me an impression that it is obsolete, over-engineered and should be phased out. Is that the current situation with clearcase among programmers?

Are there compelling reasons/features/functionality in clearcase that it is preferred over SVN, GIT or Mercurial?

Perhaps, there is a whole ecosphere of reasons why the project is using clearcase and that I need to drop my mercurial mentality and spend time getting immersed in the clearcase ecosphere I have yet to discover?

Is the lack of features in clearcase the reason for the lack of features in the clearcase GUIs?

答:
ClearCase is not going away anytime soon. There are thousands of companies using it, and IBM tells me they will continue to support it as long as their large clients continue to use it. But yes, it is showing its age. It does have a learning curve, but once you learn it, it is very powerful. Your comment on lack of features isn't accurate. ClearCase has a lot of great features, but you have to go through that learning curve to discover what it can do for you.

The reason a project is using ClearCase is because the company paid for it, and it is expensive. If a company has paid for ClearCase, they are not going to want to change directions and incur the cost of lost time for the planning, and switching of the tools. Switching SCM systems is costly from a time loss perspective, especially in a distributed development environment. Typically, when new projects spin up there is a discussion about changing tool sets. That is the best time for a company to make a move to something else.

Title: Some questions about ClearCase


问:
What type of projects should each of these projects be given their particular purposes?
I'm working in a creation of a new system that should be able to change the presentation layer without trouble, also be able to comport web-services, shop areas, internal control of data, creation of reports, multiple web portals, etc.

Following this post about the "benefits of multiple Projects and One Solution" on Stackoverflow also in some self-experience I came with the idea of the following structure.

TestProject.BLL (Business)

TestProject.DAL (Persistence (Mappings, Conventions etc))

TestProject.WEB (Presentation Layer)

TestProject.BASE (Framework)

But, after some search on the web, I found that those project are not always the type of "ASP.NET Web Application".

My question is, what are the types that I should create each project? Should I build them as "Windows Forms Application" or what?

答:
You want to create BLL, DAL and BASE as Class Library projects. You should ensure that no UI logic is included inside these projects, as you want them to be independant from the type of application you want to develop. Then create your presentation layer as a Windows Forms or a Web Application (or both!) and add references to your class libraries.

However, if you are not going to reuse any code outside of this single solution, then having multiple projects might be overkill. You may want to simply stick to folders if you do this only for organization purposes.


问:
Software failure due to maintenance oversights example/case study
I'm doing some investigation into the role of maintenance in software development and the use of metrics within the development cycle.

What I am asking is for a point in the right direction or possibly a direct example in which there has been software failures due to the oversight of maintenance costs.

More specifically I am looking for a case in which an implemented system has failed as the costs/effort for maintenance has been far too great as there has been poor or no projections from metrics.

I understand this is a very specific question, but I've been racking my brains thinking of all the software failures I know of and none of them fit the criteria.

答:
The U.S. Army's WARSIM project might be a good example.  From this Wikipedia article:

A decade after its original scheduled delivery date, WARSIM has yet to support a single Army training exercise, but is still being funded, largely to vindicate those who conceived of the system and defended it over the lifetime of its development. The WARSIM schedule slipped many times. Moreover, WARSIM has a clumsy architecture that requires enough servers to fill a small room, while earlier "legacy" wargames run efficiently on a single standard desktop workstation.

That same Wikipedia article also talks about the epic failure that was the Denver Airport's baggage handling system.  I'm sure if you research one or both of these projects, you'll find some good case study material on the subject of cost/maintenance oversights.


问:
How to deal with undesired commits that break long-running release builds?
We ran into an unfortunate situation at work recently and I've been wondering what we can do to avoid similar problems in the future.

We make embedded systems. The FPGA code is in one SVN repository while the firmware & software code is in a different repository. Building the firmware requires the built FPGA images, so these binary files are also stored in the firmware/software repo. The FPGA build can take 2-3 hours and may randomly fail. To my understanding, these late failures occur because of the complex timing issues in the FPGA logic. Developer errors such as bad syntax will cause the build to fail within minutes.

Because the builds take so long, the FPGA developers generally make their changes, build, give the new image to the firmware developers, and then commit to SVN. A few weeks ago, this caused a lot of issues as we were preparing for a release. One FPGA developer made a small change and started a build. Another FPGA developer made a commit (after he had been told that his changes did not need to be included in this release and that he should wait to commit). After this commit, the initial build failed. The first FPGA developer then had to revert the other's changes, commit his changes, and spend a significant amount of time inspecting the code in SVN to make sure it reflected the code used to build the image required for the firmware build before we tagged for the release.

If we were using git or another DVCS this wouldn't be a problem, since each FPGA developer could commit locally before building and push to a server after a successful build. Switching our version control is currently not an option. We're in the process of throwing more hardware at the problem of long FPGA builds and we're investigating whether the build time can be improved by changing settings in the build tools.

Is there anything else we can do to improve our processes so we don't repeat this situation or discover other problems with versioning and conflicts?

答:
One FPGA developer made a small change and started a build. Another FPGA developer made a commit (after he had been told that his changes did not need to be included in this release and that he should wait to commit). After this commit, the initial build failed. The first FPGA developer then had to revert the other's changes, commit his changes, and spend a significant amount of time inspecting the code in SVN to make sure it reflected the code used to build the image required for the firmware build before we tagged for the release.

The problem is that you are using a single branch for multiple purposes that are conflicting.  You are doing release packaging, low risk fixes, and high risk fixes in the same branch.

There is nothing fundamentally wrong with checking in code, its just that it needs to be checked in the right spot.  Yes, DCVS makes some aspects of this easier, though it is not the right answer for every solution.

Consider having the trunk or mainline (where you currently check everything in to) be the low risk fixes and low risk development spot - don't break things for other people.  Have another branch be the release branch.  Once the release is ready, merge all the changes from the mainline into the release branch and build from there.  You can still build from the mainline, but that is a dev/nightly release, not one that is ready.

Upon having the release build fail, either check the code into the trunk again and cherry pick (this is key - so that the second developer's code doesn't need to be reverted) that change into the release branch, or check it into the release branch and merge it back into the main line.  Different people will have different opinions on which of these is the best-est practice.

Advanced SCM Branching Strategies is a good read on this topic.

In the environment that I work on, there is a branch for the release (release), a branch for the dev build (the trunk), and a branch (or two or three - as necessary) for various high risk changes.  Each of these branches has a separate build in the build server.


问:
How do you name your private variables in C#?
What is the best practice, most commonly accepted naming conventions for private variables in C#?

private int myInteger;

private int MyInteger;

private int mMyInteger;

private int _myInteger;

private int _MyInteger;

Mysterious other option

Which do you use and why?  (My company is fairly new to C# and I would like to pick the most "industry accepted" method to try and get into our coding standard.)

答:
First off, PascalCasing is commonly reserved for public properties, consts, methods, etc of the class.  So I would skip 2 and 5.

Second, hungarian notation is discouraged in the .NET world, so (uh, I think) 3 is right out.  Assuming that's what is going on with 3.

That leaves with camelCasing and _camelCasing.  I typically use _camelCasing for class variables, and plain old camelCasing for variables scoped to a method or narrower.  Camel casing is the accepted standard used for method arguments, protected/private variable names and variables within a method or narrower scope.

I also like to prepend with the underscore so that my private variables are grouped in my intellisense. However, I only do this for variables scoped to a type.  Variables declared within a method or narrower scope I leave the underscore off.  Makes it easy to keep them separate and keep less used variables together.

ContentLicense: CC BY-SA 2.5


问:
How to interview someone you know well?
How would you interview someone you know well or someone you may even be friends with? What if you already know their strengths and weaknesses. I would prefer to avoid this situation by delegating this task to somebody else, but what if this is not an option. I feel like there is just too much personal feelings involved and it is almost impossible to be unbiased. If you have been in an similar situations, how did you handle them? </p>

答:
Who is asking you to interview this person and why? Knowing that will tell you all you need to know.

For example, maybe this person is your neighbour, you have seen each other in the street and been at each other's house for dinner, but you don't know "how many years of C++ experience do you have?" or "have you ever written a Disaster Recovery Plan?". That is probably a pretty easy interview to run. "Look, we're friends, I already know you have integrity and you're smart, I just need to ask you some technical things."

A different example, this is your college buddy, you worked on assignments together, you know a great deal about the technical skills and personality traits that would be coming into the team, and you think this person is a definite hire. But management wants to cover their backsides and insists on an interview. Well in this case there is nothing you can ask that will change your opinion, so you should ask someone else to lead the interview.

If you must go through the interview yourself, and you feel it's not going to help you learn anything, schedule this person LAST. By the time you have interviewed 5 or 6 other people, it may occur to you there are things you don't know about what it would be like to have your buddy (spouse? cousin? child?) join you on the team, and you actually have some good questions to ask and a decision to make.

Title: How to interview someone you know well?


问:
CoffeeScript and Named Functions
Elsewhere, an argument has arisen over the terminology of a named function in CoffeeScript. In particular someone referred to something like this:

```<code> foo = ->
    console.log("bar")
</code>```

as a named function. But its been objected that everything in CoffeeScript is anonymous functions and there are no named functions. This is certainly true, CoffeeScript only has function expressions which can then be stored in a variable. But I don't think that means it is wrong to call this a named function.

As I see it, it is a named function because its a function that has been given a name. True, its not a named function in the same way that some other languages have named functions, but I think its close enough that it's not inappropriate to call it a named function. To insist otherwise just seems to be nitpicking.

Am I out to lunch in thinking that insisting that this isn't a named function is just nitpicking?

答:
Am I out to lunch in thinking that insisting that this isn't a named function is just nitpicking?

No. After all, in terms of semantics, your function reference is stored in a variable, which you can refer to via a variable name.

Title: CoffeeScript and Named Functions


答:
It's worth noting that the user explicitly stated they were turning an "anonymous function into a named function", both terms having a strong, existing meanings and notably different functionalities in in the JavaScript world. Given the existing meaning, the were doing no such thing, and I pointed this out.

CoffeeScript is not so far removed from JavaScript that you should be redefining terms they both share to mean something else in one language. CoffeeScript doesn't exist in some bubble, removed from its JavaScript implementation the way you might argue that C++ is separated from Assembly. Knowing the difference between an anonymous function and a named function matters, because if you expect your "named" CoffeeScript function to behave like an actual named function, you're going to be disappointed:

```<code>doStuff() # I cause an error

# ... later

doStuff = (x,y) ->
  alert("Were I actually a named function, this would work!")
</code>```

The equivalent JavaScript would work fine, with a real named function:

```<code>doStuff(); // I work just fine!

// later....

function doStuff() {
  alert("I'm a real named function!")
}
</code>```

You might be right that I'm just "nitpicking", but so what? The subtle points in computer programming matter, and being "technically" correct is important. It's the difference between writing code that happens to work, and actually understanding why your code is correct.

Title: CoffeeScript and Named Functions

Body:
Elsewhere, an argument has arisen over the terminology of a named function in CoffeeScript. In particular someone referred to something like this:

```<code> foo = ->
    console.log("bar")
</code>```

as a named function. But its been objected that everything in CoffeeScript is anonymous functions and there are no named functions. This is certainly true, CoffeeScript only has function expressions which can then be stored in a variable. But I don't think that means it is wrong to call this a named function.

As I see it, it is a named function because its a function that has been given a name. True, its not a named function in the same way that some other languages have named functions, but I think its close enough that it's not inappropriate to call it a named function. To insist otherwise just seems to be nitpicking.

Am I out to lunch in thinking that insisting that this isn't a named function is just nitpicking?

Body:
It's worth noting that the user explicitly stated they were turning an "anonymous function into a named function", both terms having a strong, existing meanings and notably different functionalities in in the JavaScript world. Given the existing meaning, the were doing no such thing, and I pointed this out.

CoffeeScript is not so far removed from JavaScript that you should be redefining terms they both share to mean something else in one language. CoffeeScript doesn't exist in some bubble, removed from its JavaScript implementation the way you might argue that C++ is separated from Assembly. Knowing the difference between an anonymous function and a named function matters, because if you expect your "named" CoffeeScript function to behave like an actual named function, you're going to be disappointed:

doStuff() # I cause an error

# ... later

doStuff = (x,y) ->
  alert("Were I actually a named function, this would work!")

The equivalent JavaScript would work fine, with a real named function:

doStuff(); // I work just fine!

// later....

function doStuff() {
  alert("I'm a real named function!")
}

You might be right that I'm just "nitpicking", but so what? The subtle points in computer programming matter, and being "technically" correct is important. It's the difference between writing code that happens to work, and actually understanding why your code is correct.


答:
CoffeeScript is inexorably tied to JavaScript, and JavaScript differentiates between the following expressions:

```<code>function foo() { ... }
var foo = function () { ... }
</code>```

In fact, you can even write:

```<code>var foo = function bar () { ... }
</code>```

Since this difference matters in JavaScript, it makes sense to use the same terms when talking about CoffeeScript. However, CoffeeScript does not support anything like the function foo () syntax, so we can say it does not have "named" functions.

In a sense, the name is part of the function definition in the function foo() { ... }, where in the other case you just create a function and assign it to a variable. This is reflected, for example, in the (nonstandard) name property of functions: in the first case, foo.name will give you "foo" and in the second it will give you "".

Additionally, in JavaScript, these also differ in terms of how they get introduced to the scope: the first version is "hoisted" and available throughout its scope where the second definition is only available after it's assigned.

Basically, just think of it as JavaScript-specific jargon, which is transferred to CoffeeScript because CoffeeScript is so closely related to JS.

Title: CoffeeScript and Named Functions

Body:
CoffeeScript is inexorably tied to JavaScript, and JavaScript differentiates between the following expressions:

function foo() { ... }
var foo = function () { ... }

In fact, you can even write:

var foo = function bar () { ... }

Since this difference matters in JavaScript, it makes sense to use the same terms when talking about CoffeeScript. However, CoffeeScript does not support anything like the function foo () syntax, so we can say it does not have "named" functions.

In a sense, the name is part of the function definition in the function foo() { ... }, where in the other case you just create a function and assign it to a variable. This is reflected, for example, in the (nonstandard) name property of functions: in the first case, foo.name will give you "foo" and in the second it will give you "".

Additionally, in JavaScript, these also differ in terms of how they get introduced to the scope: the first version is "hoisted" and available throughout its scope where the second definition is only available after it's assigned.

Basically, just think of it as JavaScript-specific jargon, which is transferred to CoffeeScript because CoffeeScript is so closely related to JS.


问:
Derived Class Method Naming
I'm having a hard time coming up with a good naming convention for methods in derived classes that serve the same purpose as the methods in the base class. For example, if both the base class, and the derived class, need to initialize:

```<code>public class Foo()
{
    public void Initialize()
    {
        // base class initialization code here
        InitializeDerived();
    }

    // force derived classes to implement their own initialize method
    protected abstract void InitializeDerived();
}

public class Bar() : Foo
{
    protected override void InitializeDerived()
    {
        // initialization code here
    }
}
</code>```

InitializeDerived() seems clunky. The only other option I can think of is to make the base class Initialize() method virtual. Then the derived class could override it, using the same name, and call the base class Initialize() method first.

Is there a better way? A better naming convention?

This may be a better example, because constructors won't solve the problem here. In this example, we have a rules engine where the client code polymorphically calls Process() on each rule:

```<code>public class RuleBase()
{
    public void Process()
    {
        // base class processing code here
        ProcessDerived();
    }

    // force derived classes to implement their own process method
    protected abstract void ProcessDerived();
}

public class RuleValidateHeight() : RuleBase
{
    protected override void ProcessDerived()
    {
        // derived class processing code here
    }
}
</code>```

The consuming code:

```<code>foreach (Rule rule in rules)
{
    rule.Process()
}
</code>```

答:
Use constructors for this instead.

```<code>public class Foo
{
    public Foo()
    {
        // initialization code here
    }
}

public class Bar : Foo
{
    public Bar()
        : base() // base (Foo) constructor gets called first.
    {
        // initialization code for Bar goes here
    }
}
</code>```

There are many reasons why, but the most compelling one is that newing up an object this way guarantees that you get back an object that is fully initialized on construction.

Title: Derived Class Method Naming

Body:
Use constructors for this instead.

public class Foo
{
    public Foo()
    {
        // initialization code here
    }
}

public class Bar : Foo
{
    public Bar()
        : base() // base (Foo) constructor gets called first.
    {
        // initialization code for Bar goes here
    }
}

There are many reasons why, but the most compelling one is that newing up an object this way guarantees that you get back an object that is fully initialized on construction.


问:
Approaches for checking multiple conditions?
What is the best practice for checking multiple conditions, in no particular order?

The example in question needs to check four distinct conditions, in any order, and fail showing the correct error message.

The examples below use a C-like syntax.

Option 1: Check all at once

This method isn't preferred because the reasons why the condition failed aren't easy to discern.

if (A && B && C && D) {
    // continue here...
} else {
    return "A, B, C, or D failed";
}
```

<h2>Option 2: Nested Conditions</h2>

<p>In the past, I used to use nested conditional statements, like so. This can get really confusing.</p>

<pre class="lang-cs prettyprint-override"><code>if (A) {
    if (B) {
        if (C) {
            if (D) {
                // continue here...
            } else {
                return "D failed"
            }
        } else {
            return "C failed";
        }
    } else {
        return "B failed";
    }
} else {
    return "A failed";
}
</code>```

Option 3: Fail-early

This is the current method I use, which I like to call fail-early. As soon as a "bad" condition is hit, it returns.

if (!A) {
    return "A failed";
}

if (!B) {
    return "B failed";
}

if (!B) {
    return "C failed";
}

if (!D) {
    return "D failed";
}

// continue here...
```

<h1>Option 4: Collect Errors</h1>

<p>One last approach I can think of is a sort of <em>collection</em> of errors. If the conditions to test for are completely separate, one might want to use this approach.</p>

<pre class="lang-cs prettyprint-override"><code>String errors = "";
if (!A) {
     errors += "A failed\n";
}

if (!B) {
    errors += "B failed\n";
}

if (!C) {
    errors += "C failed\n";
}

if (!D) {
    errors += "D failed\n";
}

if (errors.isEmpty()) {
    // continue here...
} else {
    return errors;
}
</code>```

What are the best practices for checking multiple conditions? In terms of expectations, it ideally behaves like example 4, where details of all the failures are returned.

答:
The answer is... it depends.

Does any one of A, B, C, or D cause it not to work?  Does checking for A and failing make checking for B, C, or D impractical or redundant? Is it useful to report the collection of errors that were reported or just the first one detected?

Each of the options presented has its use in the proper situation.  There is no one error handling approach to rule them all.

ContentLicense: CC BY-SA 4.0


答:
It really depends on what kind of information you want back from the function. Let's break down what every option gives you :

You don't care which condition fails, you only want to know if they all succeed or not.

Clearly out of the way. Very bad formatting and readability because of code nesting. Does the same thing as #3 but uglier.

You get to know the first condition that failed.

You get to know every condition that failed.

Now it's really up to you to judge which option is the best, depending on the context and what information you really need.

Title: Approaches for checking multiple conditions?

Body:
What is the best practice for checking multiple conditions, in no particular order?

The example in question needs to check four distinct conditions, in any order, and fail showing the correct error message.

The examples below use a C-like syntax.

Option 1: Check all at once

This method isn't preferred because the reasons why the condition failed aren't easy to discern.

if (A && B && C && D) {
    // continue here...
} else {
    return "A, B, C, or D failed";
}
```

<h2>Option 2: Nested Conditions</h2>

<p>In the past, I used to use nested conditional statements, like so. This can get really confusing.</p>

<pre class="lang-cs prettyprint-override"><code>if (A) {
    if (B) {
        if (C) {
            if (D) {
                // continue here...
            } else {
                return "D failed"
            }
        } else {
            return "C failed";
        }
    } else {
        return "B failed";
    }
} else {
    return "A failed";
}
</code>```

Option 3: Fail-early

This is the current method I use, which I like to call fail-early. As soon as a "bad" condition is hit, it returns.

if (!A) {
    return "A failed";
}

if (!B) {
    return "B failed";
}

if (!B) {
    return "C failed";
}

if (!D) {
    return "D failed";
}

// continue here...
```

<h1>Option 4: Collect Errors</h1>

<p>One last approach I can think of is a sort of <em>collection</em> of errors. If the conditions to test for are completely separate, one might want to use this approach.</p>

<pre class="lang-cs prettyprint-override"><code>String errors = "";
if (!A) {
     errors += "A failed\n";
}

if (!B) {
    errors += "B failed\n";
}

if (!C) {
    errors += "C failed\n";
}

if (!D) {
    errors += "D failed\n";
}

if (errors.isEmpty()) {
    // continue here...
} else {
    return errors;
}
</code>```

What are the best practices for checking multiple conditions? In terms of expectations, it ideally behaves like example 4, where details of all the failures are returned.


问:
Designing an API for service operations with closely related parameters
I'm having trouble deciding how to design this service API.

```<code>public class GetCurrentValuesRequest
{
    public int ReferenceID { get; set; }
    public int[] FilterIDs { get; set; }
}

public class GetDefaultValuesRequest
{
    public int[] FilterIDs { get; set; }
}

public class GetValuesAsOfDateRequest
{
    public int ReferenceID { get; set; }
    public int[] FilterIDs { get; set; }
    public DateTime AsOf { get; set; }
}

public class GetValuesAsOfChangeSetRequest
{
    public int ReferenceID { get; set; }
    public int[] FilterIDs { get; set; }
    public long ChangeSetIDs { get; set; }
}

public class GetProposedValuesRequest
{
    public int ReferenceID { get; set; }
    public int[] FilterIDs { get; set; }
    public long ApprovalKey { get; set; }
}

public class GetValuesIfModifiedRequest
{
    public int ReferenceID { get; set; }
    public int[] FilterIDs { get; set; }
    public DateTime Since { get; set; }
}

public class GetValuesResponse
{
    public string[] Results { get; set; }
}

public class GetValuesIfModifiedResponse
{
    public string[] Results { get; set; }
    public bool IsModified { get; set; }
}

public interface IService
{
    GetValuesResponse GetValues(GetCurrentValuesRequest request);

    GetValuesResponse GetValues(GetDefaultValuesRequest request);

    GetValuesResponse GetValues(GetValuesAsOfDateRequest request);

    GetValuesResponse GetValues(GetValuesAsOfChangeSetRequest request);

    GetValuesResponse GetValues(GetProposedValuesRequest request);

    GetValuesIfModifiedResponse GetValuesIfModified(GetValuesIfModifiedRequest request);
}
</code>```

I've thought about changing it to have make the IfModified request / response subclasses of the simple GetValues request response and only including one GetValues call. The server would return a different response depending on the input request, but that requires user to call IService this:

```<code>var response = (GetValuesIfModifiedResponse)serviceClient.GetValues(new GetValuesIfModifiedRequest() { ... });
</code>```

I've also thought about placing IsModified in the simple GetValuesResponse, and only populating it if a GetValuesIfModifiedRequest is passed into it. But that seems a bit strange to include it in a result from a method which does not actually do anything with it. Also, it might throw of a user if they see it and expect to be able to use it in their code. bool? IsModified is better, but I'm not entirely sold on it just yet.

Any suggestions for how to best design this API?

答:
In my opinion, your sole request object should look something like this:

```<code>public class GetValuesRequest
{
    public int[] FilterIDs { get; set; }
    public DateTime SearchDate { get; set; }
    public SearchType SearchType { get; set; }
}

public enum SearchType
{
    AsOf,
    Since
}
</code>```

You can tweak this to your taste, but the point is that there is only one search date submitted, and the enum provides a switch mechanism between past and future.

You can then return an object thusly:

```<code>public class GetValuesResponse
{
    public string[] Results { get; set; }
    public CacheState CacheResult { get; set; }
}

public enum CacheState
{
    Modified,
    Unmodified,
    NotChecked
}
</code>```

Body:
In my opinion, your sole request object should look something like this:

public class GetValuesRequest
{
    public int[] FilterIDs { get; set; }
    public DateTime SearchDate { get; set; }
    public SearchType SearchType { get; set; }
}

public enum SearchType
{
    AsOf,
    Since
}

You can tweak this to your taste, but the point is that there is only one search date submitted, and the enum provides a switch mechanism between past and future.

You can then return an object thusly:

public class GetValuesResponse
{
    public string[] Results { get; set; }
    public CacheState CacheResult { get; set; }
}

public enum CacheState
{
    Modified,
    Unmodified,
    NotChecked
}


答:
This looks like you're trying to create a dynamic query over http. Have you looked at OData? Since you're using WCF, there is built-in support as of 4.0 I believe for implementing OData called WCF Data Services, all you have to do is return IQueryable from your service methods. For convenience, you can create helper queries on your client library that wraps around the OData queries. So your service interface would now look like

```<code>public interface IService
{
    IQueryable<Values> GetValues();
}
</code>```

And your client library would contain helper functions that call the service.

```<code>public class ServiceClient
{
   //Injected or initialized see docs under previous link on accessing a service
   private IService _service
   public IEnumerable<Values>GetFilteredValues(int[] filterIds)
   {
      //get the values matching passed in Ids.
      return from _service.GetValues().Where(v => filterIds.Contains(v.Id));
   }

   public IEnumerable<Values>GetFilteredValuesAsOf(int[] filterIds, DateTime asOf)
   {
      //get the values matching passed in Ids and created since the asOf date
      return from _service.GetValues().
             Where(v => filterIds.Contains(v.Id) && v.CreatedOn > asOf);
   }

}
</code>```

The beauty of this is that the query happens server side. If it is backed by a Database, the database handles it.

Title: Designing an API for service operations with closely related parameters

Body:
I'm having trouble deciding how to design this service API.

```<code>public class GetCurrentValuesRequest
{
    public int ReferenceID { get; set; }
    public int[] FilterIDs { get; set; }
}

public class GetDefaultValuesRequest
{
    public int[] FilterIDs { get; set; }
}

public class GetValuesAsOfDateRequest
{
    public int ReferenceID { get; set; }
    public int[] FilterIDs { get; set; }
    public DateTime AsOf { get; set; }
}

public class GetValuesAsOfChangeSetRequest
{
    public int ReferenceID { get; set; }
    public int[] FilterIDs { get; set; }
    public long ChangeSetIDs { get; set; }
}

public class GetProposedValuesRequest
{
    public int ReferenceID { get; set; }
    public int[] FilterIDs { get; set; }
    public long ApprovalKey { get; set; }
}

public class GetValuesIfModifiedRequest
{
    public int ReferenceID { get; set; }
    public int[] FilterIDs { get; set; }
    public DateTime Since { get; set; }
}

public class GetValuesResponse
{
    public string[] Results { get; set; }
}

public class GetValuesIfModifiedResponse
{
    public string[] Results { get; set; }
    public bool IsModified { get; set; }
}

public interface IService
{
    GetValuesResponse GetValues(GetCurrentValuesRequest request);

    GetValuesResponse GetValues(GetDefaultValuesRequest request);

    GetValuesResponse GetValues(GetValuesAsOfDateRequest request);

    GetValuesResponse GetValues(GetValuesAsOfChangeSetRequest request);

    GetValuesResponse GetValues(GetProposedValuesRequest request);

    GetValuesIfModifiedResponse GetValuesIfModified(GetValuesIfModifiedRequest request);
}
</code>```

I've thought about changing it to have make the IfModified request / response subclasses of the simple GetValues request response and only including one GetValues call. The server would return a different response depending on the input request, but that requires user to call IService this:

```<code>var response = (GetValuesIfModifiedResponse)serviceClient.GetValues(new GetValuesIfModifiedRequest() { ... });
</code>```

I've also thought about placing IsModified in the simple GetValuesResponse, and only populating it if a GetValuesIfModifiedRequest is passed into it. But that seems a bit strange to include it in a result from a method which does not actually do anything with it. Also, it might throw of a user if they see it and expect to be able to use it in their code. bool? IsModified is better, but I'm not entirely sold on it just yet.

Any suggestions for how to best design this API?

Body:
This looks like you're trying to create a dynamic query over http. Have you looked at OData? Since you're using WCF, there is built-in support as of 4.0 I believe for implementing OData called WCF Data Services, all you have to do is return IQueryable from your service methods. For convenience, you can create helper queries on your client library that wraps around the OData queries. So your service interface would now look like

public interface IService
{
    IQueryable<Values> GetValues();
}

And your client library would contain helper functions that call the service.

public class ServiceClient
{
   //Injected or initialized see docs under previous link on accessing a service
   private IService _service
   public IEnumerable<Values>GetFilteredValues(int[] filterIds)
   {
      //get the values matching passed in Ids.
      return from _service.GetValues().Where(v => filterIds.Contains(v.Id));
   }

   public IEnumerable<Values>GetFilteredValuesAsOf(int[] filterIds, DateTime asOf)
   {
      //get the values matching passed in Ids and created since the asOf date
      return from _service.GetValues().
             Where(v => filterIds.Contains(v.Id) && v.CreatedOn > asOf);
   }

}

The beauty of this is that the query happens server side. If it is backed by a Database, the database handles it.


答:
The answer depends hugely on what language you're using and what you are going to do as a consequence of the errors.

For example, in Scala, and assuming that I want to report every error so that they can all be fixed at once, I'd probably do something like

val (yes, no) = List(
  (A, "A failed"),
  (B, "B failed"),
  (C, "C failed"),
  (D, "D failed")
).partition(_._1)
if (!no.isEmpty) Some(no.map(_._2)) else None
```

<p>where I first group my conditions and error messages, then sort them into two groups--the successes and the failures--and return those error messages if there was something, and otherwise return a sentinel value saying--in this case--that everything's okay.</p>

<p>But this relies critically on Scala's ability to quickly group and map and manipulate collections and containers.  In Java, I would write the exact same code in the more verbose (and less convenient to check, as I now need to query <code>errors.size()</code> to know whether I have failed anything):</p>

<pre class="lang-java prettyprint-override"><code>ArrayList<String> errors = new ArrayList<String>();
if (!A) errors.add("A failed");
if (!B) errors.add("B failed");
if (!C) errors.add("C failed");
if (!D) errors.add("D failed");
return errors;
</code>```

If we only need the first error, in Java I'd do fail-fast while in Scala I might

List(A,B,C,D).zipWithIndex.find(!_._1).foreach{ x => return x._2 }
```

assuming I was okay with the number of the item that went bad as a return code.

So the answer is really: you've got the important different styles, but how exactly to implement them most efficiently/least painfully is going to depend a lot on your tools.

Body:
The answer depends hugely on what language you're using and what you are going to do as a consequence of the errors.

For example, in Scala, and assuming that I want to report every error so that they can all be fixed at once, I'd probably do something like

val (yes, no) = List(
  (A, "A failed"),
  (B, "B failed"),
  (C, "C failed"),
  (D, "D failed")
).partition(_._1)
if (!no.isEmpty) Some(no.map(_._2)) else None

where I first group my conditions and error messages, then sort them into two groups--the successes and the failures--and return those error messages if there was something, and otherwise return a sentinel value saying--in this case--that everything's okay.

But this relies critically on Scala's ability to quickly group and map and manipulate collections and containers.  In Java, I would write the exact same code in the more verbose (and less convenient to check, as I now need to query errors.size() to know whether I have failed anything):

ArrayList<String> errors = new ArrayList<String>();
if (!A) errors.add("A failed");
if (!B) errors.add("B failed");
if (!C) errors.add("C failed");
if (!D) errors.add("D failed");
return errors;

If we only need the first error, in Java I'd do fail-fast while in Scala I might

List(A,B,C,D).zipWithIndex.find(!_._1).foreach{ x => return x._2 }

assuming I was okay with the number of the item that went bad as a return code.

So the answer is really: you've got the important different styles, but how exactly to implement them most efficiently/least painfully is going to depend a lot on your tools.


问:
Are there any reasons not to accept a software deliverable as a virtual machine?
This is a question about logistics, not a technical question.

My company has outsourced some embedded software work.  Specifically, we have payed a contractor to develop an embedded system for us since we do not have adequate in-house knowledge to do it ourselves (we only have desktop application developers).

So, the contractors have finished the software and they have asked if they may deliver it to us in a virtual machine.  The VM is a Windows 8 machine containing the pre-configured CodeWarrior IDE with the source code as a CodeWarrior project.  The idea is that this will allow us to make code changes within the VM that is already configured for further development of this project.

Are there any drawbacks to doing this as opposed to having them walk us through how to configure our own development machines to make code changes to the project?  The only problem I can foresee is the VM running slowly and it taking a long time to rebuild the project when we make code changes.  But on the other hand, I like the idea of getting a pre-configured embedded system development environment so I don't have to add yet another IDE on my desktop application dev machine.

I can't really think of a good reason why not to accept a VM deliverable, but I just wanted to run it by this community in case there's something I'm missing.

答:
I don't think there's a problem with this, I've seen content management systems that install as VMs, and from what you say the contractors have given you the ability to maintain and extend the application yourselves.

However, as other posters have noted there are two things I would to do. First, make sure that when installing the VM, put it on a machine that's separate from your network. You wouldn't download an unknown EXE from the internet and install it on your machine.

Second, if possible keep this isolated copy as reference for setting the in-house version. I say if possible because I don't know the business pressures you are under. Ultimately, it'll be your firm's IT department / programmers that'll be responsible for this application. So, the more you know about it the better.


问:
Should I tell the interviewer I already know the answer to the question being asked?
In a programming interview if I am asked a question I already know the answer for, such as giving an algorithm for a particular problem. Should I disclose that to the interviewer? This issue only makes sense when there's a novelty aspect to the question.

One example is "How would you reverse each word in a string, but not their order?". There also seems to be a division between easier stuff, that you are "supposed" to know, such as my example and harder more contrived problems.

Whats your policy and rationale for dealing with this issue?  If you are already familiar with the question/brainteaser, should you disclose this in addition to answering the question?  Is there any ethical dilemma involved with not disclosing your prior knowledge of the question?

答:
I think telling the interviewer only applies to those goofy "gotcha" questions, like the round manhole and other stuff like that. Questions where once you know the answer it's completely obvious.

Reversing strings, etc, don't have an obvious "gotcha" solution that you can explain in 3 seconds if you know it.


问:
Continuous "Platform" Integration?
We have accumulated a large codebase of somewhat-well-document projects, many of which aren't actively being used, but that we want to be able to start using again quickly if necessary.

What is the best way to automatically make sure that these projects stay in working condition as the dependencies backing different projects are upgraded?

These dependencies tend to be large, open-source and external, such as OpenCV and FFMPEG.

Between consecutive versions, they offer Warnings during compilation about the use of recently-deprecated functions; jump more than a few version, though, and updating becomes a significantly more challenging task.

答:
There is an entire book dedicated to the concept of Continuous Delivery. (In fact, my Amazon search tells me that there are several. The idea is pretty simple. Create a test environment that closely matches your target deployment environment (using virtualization makes this a less daunting task). When you make a build, test the build within that environment. Once the build is validated, capture the configuration of that environment. Treat that deployment as a deliverable itself in other words.

If you have full control of where the application will be deployed, your job is done, promote the test environment to production and move on to the next phase.

If you are building an application for use by external users, it's a bit more difficult. In Linux, you can take advantage of apt and rpm to create packages that bring down the appropriate dependencies with them. So if your newest build relies on libGTK 4.6, (an example I'm not sure if there even is a libGTK 4.6) you can specify that within your package and you're golden.

On Windows, things get a little tricker. But the book I linked to also discusses options for addressing those scenarios.

Title: Continuous "Platform" Integration?


问:
Exposing a Disposing event
I'm implementing a .NET class which implements IDisposable.  After being disposed, the object's state is invalid and so nobody should be accessing it, of course.

There are some situations where two essentially independent systems have access to the same instance of this class.  One essentially "owns" the object but the other is charged with interacting with the object in a persistent manner.

If the "owner" opts to get rid of the object by calling Dispose on it, the other system needs to know about this because otherwise it may try to interact with an invalid object.  It is not always convenient to have the owner inform the other system to stop using the object, because the owner itself may not know about this other system.

I do have the class implementing an IsDisposed property, but there are situations where polling this would become impractical and it would be preferable for the "non-owner" to instead receive notification that the object is disposed.

To this end I figured that implementing a Disposing event on the class would be a good solution, but this leads to some design questions:

Is the instance considered to already have been disposed at the time the event is raised?  (My guess would be that it should be regarded as alive until the handlers finish.)

How should the object react to further manipulation that occurs inside the event handlers?  (My guess is react in the usual manner for a living object since it is still alive.)

What if a handler itself calls Dispose on the object?  (We could either explicitly ignore re-entrant calls or just assume that well-behaved handlers won't do this.)

Should the Disposed event still be raised in the event of the object being finalized without having ever been explicitly disposed?  (I can't think of a case off hand where such an event would actually be needed, and it definitely has the potential to cause problems.)

I'm wondering if there is any established wisdom on how this pattern should be designed in general, or any examples I should be aware of where trouble is likely.

答:
Linq to SQL had a related issue, having to do with lazy evaluation.  If data was requested after the DataContext was disposed (which can happen if the query is lazily evaluated), an exception was thrown.

The solution was to not dispose of the data context, and allow the garbage collector to collect it naturally.  See http://leedumond.com/blog/about-disposing-the-datacontext/

Strictly speaking, you do not need the dispose pattern unless you are holding unmanaged resources.  Unmanaged resources are not automatically cleaned up by the garbage collector, so you have to do that yourself.  Of course, this hasn't prevented some very smart people from abusing the using pattern for fun and profit.

All that said, I don't see any reason why you couldn't fire an event from the Dispose() method.  You can pass the object being disposed through the event handler and, as long as your event handler doesn't hold onto the object for too long, dispose of your managed resources when the handler returns.

Title: Exposing a Disposing event


答:
Well, this is going to be easier if you can call Process from the derived class, and work your way up the inheritance tree instead of down:</p>

```<code>public class Bar: Foo
{
    public override void Process()
    {
         base.Process();  // optional
         // Process Derived Rule here.
    }
}
</code>```

Title: Derived Class Method Naming

Body:
I'm having a hard time coming up with a good naming convention for methods in derived classes that serve the same purpose as the methods in the base class. For example, if both the base class, and the derived class, need to initialize:

```<code>public class Foo()
{
    public void Initialize()
    {
        // base class initialization code here
        InitializeDerived();
    }

    // force derived classes to implement their own initialize method
    protected abstract void InitializeDerived();
}

public class Bar() : Foo
{
    protected override void InitializeDerived()
    {
        // initialization code here
    }
}
</code>```

InitializeDerived() seems clunky. The only other option I can think of is to make the base class Initialize() method virtual. Then the derived class could override it, using the same name, and call the base class Initialize() method first.

Is there a better way? A better naming convention?

This may be a better example, because constructors won't solve the problem here. In this example, we have a rules engine where the client code polymorphically calls Process() on each rule:

```<code>public class RuleBase()
{
    public void Process()
    {
        // base class processing code here
        ProcessDerived();
    }

    // force derived classes to implement their own process method
    protected abstract void ProcessDerived();
}

public class RuleValidateHeight() : RuleBase
{
    protected override void ProcessDerived()
    {
        // derived class processing code here
    }
}
</code>```

The consuming code:

```<code>foreach (Rule rule in rules)
{
    rule.Process()
}
</code>```

Body:
Well, this is going to be easier if you can call Process from the derived class, and work your way up the inheritance tree instead of down:

public class Bar: Foo
{
    public override void Process()
    {
         base.Process();  // optional
         // Process Derived Rule here.
    }
}


答:
The name of the method should say what the method does, instead of just saying where the method appears. Possible names would be:

```<code>ProcessRuleSpecifics
ProcessAfterInitialization
ResumeProcess
TerminateProcess
</code>```

and so on

Title: Derived Class Method Naming

Body:
The name of the method should say what the method does, instead of just saying where the method appears. Possible names would be:

ProcessRuleSpecifics
ProcessAfterInitialization
ResumeProcess
TerminateProcess

and so on


答:
I'm pretty sure it's in the Framework Design Guidelines somewhere, but what I've observed is that whenever an object gives you a Disposable, it does not interact with it anymore. Usually, there is a static method call that is responsible for creating and handing the disposable to you.

There are two options you have here:

Your "owner" should never expose the IDisposable and should instead act as an Adapter over it. (In other words the client calls the "owner" who then delegates the calls to the IDisposable).

Your "owner" should be a factory and should just be responsible for creating an instance of the IDisposable, doing any additional configuration, and handing it to the client never storing a reference to it.

Title: Exposing a Disposing event

Body:
I'm implementing a .NET class which implements IDisposable.  After being disposed, the object's state is invalid and so nobody should be accessing it, of course.

There are some situations where two essentially independent systems have access to the same instance of this class.  One essentially "owns" the object but the other is charged with interacting with the object in a persistent manner.

If the "owner" opts to get rid of the object by calling Dispose on it, the other system needs to know about this because otherwise it may try to interact with an invalid object.  It is not always convenient to have the owner inform the other system to stop using the object, because the owner itself may not know about this other system.

I do have the class implementing an IsDisposed property, but there are situations where polling this would become impractical and it would be preferable for the "non-owner" to instead receive notification that the object is disposed.

To this end I figured that implementing a Disposing event on the class would be a good solution, but this leads to some design questions:

Is the instance considered to already have been disposed at the time the event is raised?  (My guess would be that it should be regarded as alive until the handlers finish.)

How should the object react to further manipulation that occurs inside the event handlers?  (My guess is react in the usual manner for a living object since it is still alive.)

What if a handler itself calls Dispose on the object?  (We could either explicitly ignore re-entrant calls or just assume that well-behaved handlers won't do this.)

Should the Disposed event still be raised in the event of the object being finalized without having ever been explicitly disposed?  (I can't think of a case off hand where such an event would actually be needed, and it definitely has the potential to cause problems.)

I'm wondering if there is any established wisdom on how this pattern should be designed in general, or any examples I should be aware of where trouble is likely.


答:
In game programming I'm pretty used to the prefix 'On' so that you can think of the base class generating an 'event' when something is about to happen.

```<code>protected override void OnInitialize() { /*code here*/ }
protected override void OnProcess() { /*code here*/ }
</code>```

This is called the Template Method Pattern, by the way.

As Martin comments below, other useful 'event' prefixes include Pre and Post. In a game context you'd typically have PreUpdate OnUpdate PostUpdate.

Title: Derived Class Method Naming

Body:
In game programming I'm pretty used to the prefix 'On' so that you can think of the base class generating an 'event' when something is about to happen.

protected override void OnInitialize() { /*code here*/ }
protected override void OnProcess() { /*code here*/ }

This is called the Template Method Pattern, by the way.

As Martin comments below, other useful 'event' prefixes include Pre and Post. In a game context you'd typically have PreUpdate OnUpdate PostUpdate.


答:
Tell them someone else is doing the interview, but you're going to be sitting in. Then get someone else to come in and pretend to be the person in charge of the interview. You can give your fake interviewer a list of questions to ask, and still jump in yourself if you feel the need to.

Use whatever excuse you want to explain your presence, but make it clear that you will not be in charge of the interview and are not the person they need to impress to get the job. You could tell them its a training/learning exercise for you, or that you are there to access their technical skills since the interviewer isn't familiar with the language you're discussing.

It also gives you a convenient excuse if you decide to hire a different candidate.... just say you weren't the one in charge of making the final decision.

Title: How to interview someone you know well?

Body: How would you interview someone you know well or someone you may even be friends with? What if you already know their strengths and weaknesses. I would prefer to avoid this situation by delegating this task to somebody else, but what if this is not an option. I feel like there is just too much personal feelings involved and it is almost impossible to be unbiased. If you have been in an similar situations, how did you handle them? </p>


问:
How many `malloc` calls is too many? If any?
I'm implementing a system in C, implemented partially as a library. The library does most of the memory management itself, with the application layer just having to call *_destroy functions on the top-level objects.

While checking for memory leaks, I noticed that the number of calls to malloc seemed quite high, relative to the size of the application code. The performance of the code seems fine, but I've been bitten by "fast enough" code before when trying to scale.

The number of allocations roughly matches the number of objects created, including child objects of the top-level ones. So creating a single top-level object might trigger 7 malloc calls, since it needs one for itself and then a couple for it's children that may also need a few children.

Unfortunately, I'm relatively new to C programming, though generally experienced as a programmer, and have no idea whether or these numbers are normal or not.

So what would a good rule-of-thumb be for number of allocations? I know that less would generally be better, but changing the code to allow it would introduce complexity that I'm not willing to add without a significant increase in performance.

Also, should I worry about the performance of malloc/free or is that the realm of real-time performance (games etc.)?

答:
The usual answer for this thing is to wait until you can measure if there's a problem.

My experience has been that malloc() is rarely an issue, but perhaps I also do more CPU-intensive work than you do, so malloc() isn't in the critical path.

Definitely some people are constrained by the malloc performance. See, for example, https://github.com/blog/1422-tcmalloc-and-mysql , where github switched to using TCMalloc for MySQL and got a 30% performance improvement. There's more discussion at http://www.reddit.com/r/programming/comments/18zija/github_got_30_better_performance_using_tcmalloc/ .

TCMalloc is one of several malloc replacements. Another is jemalloc, and a third is nedmalloc.

So, if you think it's a problem (eg, because profiling shows that you're stuck in malloc/free often) then try one of those out and see if it improves things.

If it's a concern now, then perhaps you can think about how your code is structured. The biggest improvement is to realize that you don't need to think of "one structure = one malloc."

For example, I once wrote a parser for a tab-separated document. While I could have turned each row and field into its own string, it was faster to scan the document, count the number of rows and columns, and do a single malloc for the row/field pointers. Then in the second step, scan the document again, assign the correct pointers to the head of each field, and replace the tabs and newlines with a NUL to get proper NUL-terminated strings for the field.

This meant that my parser now "owned" the document string, which was acceptable. And it reduced the complexity of the code, even if the malloc performance wasn't critical.


问:
What's the next level of abstraction?
Since programming languages initially only used lines of code executed sequentially, and it evolved into including functions which were one of the first levels of abstraction, and then classes and objects were created to abstract it even further; what is the next level of abstraction?

What's even more abstract than classes or is there any yet?

答:
New forms of abstraction hide low-level work from you. Named procedures and functions hide program addresses from you. Objects hide dynamic memory management and some type-dependent "if statements".

I'd suggest that the next level of practical abstractions that will hide low-level drudgery from you are those of functional reactive programming. Look at "signals" in something like http://elm-lang.org/ which hide the callbacks and update dependencies you would have to explicitly manage in javascript. FRP can hide a lot of the complexity of inter-process, and inter-machine communication that's needed in large-scale internet applications and high-performance parallelism too.

I'm pretty sure that this is what we're all going to get excited about in the next 5 years or so.

Title: What's the next level of abstraction?


答: Set theory -- as partially implemented in relational databases, but also in statistics languages like SAS and R, provide a different but arguably higher level of abstraction than OO.</p>

Title: What's the next level of abstraction?

Body:
Since programming languages initially only used lines of code executed sequentially, and it evolved into including functions which were one of the first levels of abstraction, and then classes and objects were created to abstract it even further; what is the next level of abstraction?

What's even more abstract than classes or is there any yet?


问:
Genetic Algorithm - solving a matrix with hard and soft constraints
I'm writing a Genetic Program that I need some advice on for crossover operations. The GP is attempting to find the best solution for a matrix that has hard row constraints and softer column constraints.

For a given solution in the population, the rows contain a random combination of object type ids from a fixed set. The GP is trying to find a solution where, after the rows are laid out, if you tally the id's in each column, the number of each type must fall within a recommended range for that id. I wrote a fitness function that allows me to grade the solution on how close it comes to the columns constraints - 100% being all the columns fall within specs.

Since fitness is tied to columns it seems logical that the crossover operation should grab columns of two parents to create a candidate offspring.  Should a multipoint crossover be a better way to go?  My concern is a crossover operation, almost certainly,  will break the row contraints.

Thanks for any advice.

答: Hmmm... When I took a class on GA's and EA's, multipoint crossover was not necessarily better than single point crossover or even mutation and no crossover.  In this case it seems that multipoint cross over may generate invalid rows and I'm assuming that means your evaluation function can't calculate a meaningful statistic.  Given that, your idea to cross two matrixes by swapping whole rows seems like a good idea.  Your algorithm might be more exploratory if you can mutate rows safely.  </p>


问:
Portability: Python's C/C++ libraries/extensions vs JRuby's Java libraries
I've had some discussion with colleagues who chose to go with JRuby along the following line of argumentation:

JRuby can make use of anything that is available in Java, ergo such programs are more portable bc Java is more portable.

Arguably, the breadth, capability and speed of C/C++ libraries that have been wrapped for Python is still better than what is available in Java. But since this is C/C++, all the problems with portability reappear this way - or so their argument went.

Have you ever had such a problem? that is, problem with portability of Python's extensions?

Personally, I have never found this to be a problem, but YMMV, while theoretically and potentially this is a problem. I'm curious of your experiences.

答:
This is almost an impossible question to answer in the abstract.  It depends on what type of programming your doing (systems, enterprise, application) and your definition of portability.

At my current job they did try JRuby precisely because it had the promise of playing nicely with the JVM (before I got there).  They ditched because, practically speaking, they found coding calls to Java somewhat cumbersome and switched to Groovy.  I've also, anecdotally, had problems running pure Ruby libraries in JRuby - for whatever reason.  But writing portable C is not easy.  I used to run MRI Ruby on Solaris and there were some native libraries that required a lot of tweaking before they compiled.

You might find more libraries for interfacing with "enterprise" software and "enterprise" crap... err... systems in Java than in C/C++.  But as @MrFox pointed out - Java ain't no systems language.  If your definition of portable is runs on Linux and Mac OSX, a lot of Python wrappers have worked for me with little or no problem (except for some SciPy related stuff).  (I will admit I am a python dilettante and if I were more hard core I might run into more edge cases).  If your definition of portable includes OpenVMS and zVM, then Java is your best bet.


问:
What is the proper way to pass the parameters into a MVC system?
I am trying to learn java servlet/jsp with the MVC concept and built the simplest MVC application. Now I want give more detail to it to enhance my understanding.

If I would need to register a new row in a table in the database, how should we pass the various value of column into the system?

For example, the user might want to register a new event in his planner and the detail of the event involves the 'where', 'when', 'who', 'detail', etc. Should pass all this long value from the servlet's parameter, i.e: the http link?

```<code>String accNo = request.getParameter("account_number");
String a = request.getParameter("...");
String b = request.getParameter("...");
String c = request.getParameter("...");
String d = request.getParameter("...");
</code>```

To illustrate my view that it is really unprofessional to show all the parameter on the link:

```<code>http://localhost:8080/domain1/servlet1?param1=55555555555555&param2=666666666666666666666666666666666666666666666666666666666666&param3='Some random detail written by user.........................'
</code>```

Is there other way to pass them?

答:
Parameter passing at multiple levels:

As an example, Spring MVC binds similarly named request parameters (whether post body parameters or url query string parameters) to parameters on the controller method.  That breaks the parameters out of their representation in the HTTP request and makes them reasonable Java parameters to a method.  If you're passing data to services in your model from your controller there are three avenues of thought.

The first is to pass model objects which you fill out from the parameter data and pass them to your services.  Given that you are probably using some sort of O/R mapper like JPA or Hibernate, you will need to merge those objects into the hibernate session or jpa persistence context.  However, you have more tightly coupled your models to your controllers.

Second is to pass simple Java types to keep your services and your controllers more loosely coupled.  For complex objects with several fields, this is a pain.  Also, when you have several int parameters in a row, the chance you might flip two by accident is pretty good.

The third options is to define a data transfer object which is passed to the service method, which in turn manipulates your model.  The DTO could contain fields that you might map to two or more objects in your model, but now your controller logic is only coupled to the DTO and you could still evolve your model independently of the Controller.

Okay, so that takes the data from HTTP land through the controller to your model.  That's the current "best practice" way to build Java applications but may not be the best for your application.  (However, it probably is since it works for a large majority of applications).

As far as where to put those values (request body or parameters) it might be helpful to think in terms of REST.  Generally, when you have a form to add new data or to update data, you will send the parameters in the post body.  You can think of operations as being "dangerous" (they alter the state of your application) or "safe" (they change nothing).  (Note that incidental changes like logging don't count.)  Operations can also be idempotent - meaning they can be executed more than once and the state of the system is the same as it was after the first invocation.

Dangerous, non-idempotent operations should be a POST.  Dangerous but idempotent operations should be a DELETE or PUT.  (Note that some browsers only support POST, so you can just stick with POST).  The parameters should be encoded in the POST body.  You generally wouldn't use query string parameters.

Safe, idempotent operations should be a GET.  It is perfectly acceptable to encode additional parameters in the URL string to facilitate the operation of the GET.  For example, if searching by the username, adding ?username=the+user as a query parameter is fine.  Or to distinguish records ?id=23.  Some people believe that URLs can be restful only if they include the identifying component as part of the document path /users/23, but I don't believe that's correct since /users?id=23 is just as unique as /users/23.  (And I don't recall it from Fielding's dissertation - but I have lousy memory).


答:
It's not always the malloc and free performance that is an issue.  You can run into problems with cache locality (or rather a lack of cache locality), and that can really hit performance if you are doing a lot of processing on the data.

If you are worried you could switch to a memory-pooled scheme for all, most, or some parts of your API.  I'm sure there are plenty of tools out there to do this in a generic way, but more often than not the pooling requirements of an application are so basic that it's trivial to implement yourself.

Unfortunately, you are the best judge of whether pooling will benefit your application, and whether it is worth the effort and increased complexity.  Just remember, a pool can be as simple as a large char buffer.

Just watch out for memory alignment issues (like don't start objects at non-aligned memory addresses).

A classic argument I like to give for memory pools is a 2D array...

So often, you see people allocate a chunk for the row pointers, and then loop through allocating each row...  You have to do more error handling, the 'delete' function is a pain, and at the end of it you get a matrix whose row index and individual rows could be fragmented across your address space.

Yet, all you really needed to do was allocate one block of memory with enough space for a bunch of pointers and the 2D data segment, then index it.  It's not technically a pool, but it is smarter use of memory.

Title: How many `malloc` calls is too many? If any?

Body:
I'm implementing a system in C, implemented partially as a library. The library does most of the memory management itself, with the application layer just having to call *_destroy functions on the top-level objects.

While checking for memory leaks, I noticed that the number of calls to malloc seemed quite high, relative to the size of the application code. The performance of the code seems fine, but I've been bitten by "fast enough" code before when trying to scale.

The number of allocations roughly matches the number of objects created, including child objects of the top-level ones. So creating a single top-level object might trigger 7 malloc calls, since it needs one for itself and then a couple for it's children that may also need a few children.

Unfortunately, I'm relatively new to C programming, though generally experienced as a programmer, and have no idea whether or these numbers are normal or not.

So what would a good rule-of-thumb be for number of allocations? I know that less would generally be better, but changing the code to allow it would introduce complexity that I'm not willing to add without a significant increase in performance.

Also, should I worry about the performance of malloc/free or is that the realm of real-time performance (games etc.)?


问:
What is a good measure of testing/tester efficiency?
I am about to participate in a discussion with management regarding measuring our testing efficiency as a QA organization. The main reason behind this is that half of our team is contracted out and our business would like to provide some metrics of how effective/efficient we are, so that we have basis data on which to negotiate contract parameters with the service agreement of our contractors.

I have poked around a little and most of the opinion I have found on this subject revolves around developer efficiency: lines of code, story points delivered, defects introduced, etc.

But what about testers? Our testing is mostly requirements based, and a mix of manual, semi-automated, and automated testing (not because we haven't gotten around to automating everything, but because some things are not automatable in our test system).

答:
Many ways to measure performance in development and testing phases during project execution. We used below measures in our projects.
Development performance measured by 4 popular Code metrics(Maintainability index, Cyclometric complexity, Depth of inheritance, Class couplings). For C# will get it in Microsoft Visual Studio.
For test coverage Ncover/Ndepend is very useful.
Testing performance measured by no of development bugs -rolling over by last 4 sprints
System testing bugs rolling over last 4 sprints.
No of automation test passed in particular release/Features delivered.</p>


问:
What endpoints should I provide, if any, to permit connectivity testing for my web services?
What endpoints should I provide, if any, to permit connectivity / availability testing for my web services / Web API?

TL;DR

I am developing both the server and client in an enterprise environment. The client will interface with the server via an RESTful Web API. I would like to provide an indication to the user that they have correctly entered the Web API's root URL correctly. I would also like to implement connectivity monitoring of the API in the future.

None of the public APIs (Facebook, Twitter etc) that of have looked have a dedicated end point for connectivity testing. There are a number of web sites that provide availability monitoring of public APIs. One of them, Watchmouse, reported they preform their availability testing by actually exercising the API (logging in, perform an action, and testing the results).

On the other hand calling the root URL for CouchDB returns and configurable message and the CouchDB version.

Should I provide dedicated endpoints for connectivity / availability testing? If so what endpoints? Or should I just exercise existing endpoints?

答:
I include a method like this in all of my web services

```<code>string GetVersion()
</code>```

Which just returns the version of the running assembly on the server. It provides an easy way to ping the service to ensure it is running. As a side effect, it actually  gives you some useful information about the server.

It's obviously not as good as actually exercising the API, but its easy enough to add to any existing service.

Personally, I don't think there's any need to define anything more than that. If you want to test the functionality service, then you will need to use the actual service methods.

Body:
I include a method like this in all of my web services

string GetVersion()

Which just returns the version of the running assembly on the server. It provides an easy way to ping the service to ensure it is running. As a side effect, it actually  gives you some useful information about the server.

It's obviously not as good as actually exercising the API, but its easy enough to add to any existing service.

Personally, I don't think there's any need to define anything more than that. If you want to test the functionality service, then you will need to use the actual service methods.


问:
How to deal with undesired commits that break long-running release builds?
We ran into an unfortunate situation at work recently and I've been wondering what we can do to avoid similar problems in the future.

We make embedded systems. The FPGA code is in one SVN repository while the firmware & software code is in a different repository. Building the firmware requires the built FPGA images, so these binary files are also stored in the firmware/software repo. The FPGA build can take 2-3 hours and may randomly fail. To my understanding, these late failures occur because of the complex timing issues in the FPGA logic. Developer errors such as bad syntax will cause the build to fail within minutes.

Because the builds take so long, the FPGA developers generally make their changes, build, give the new image to the firmware developers, and then commit to SVN. A few weeks ago, this caused a lot of issues as we were preparing for a release. One FPGA developer made a small change and started a build. Another FPGA developer made a commit (after he had been told that his changes did not need to be included in this release and that he should wait to commit). After this commit, the initial build failed. The first FPGA developer then had to revert the other's changes, commit his changes, and spend a significant amount of time inspecting the code in SVN to make sure it reflected the code used to build the image required for the firmware build before we tagged for the release.

If we were using git or another DVCS this wouldn't be a problem, since each FPGA developer could commit locally before building and push to a server after a successful build. Switching our version control is currently not an option. We're in the process of throwing more hardware at the problem of long FPGA builds and we're investigating whether the build time can be improved by changing settings in the build tools.

Is there anything else we can do to improve our processes so we don't repeat this situation or discover other problems with versioning and conflicts?

答:
I would recommend using a code review system in addition to your source control system.  This would enforce that each commit would have to be reviewed and approved by other members of the team before being accepted to a repository.   Other benefits would include improved knowledge sharing and development process transparency. </p>

<p>edit:
Slowing things down is a worry but if you choose the right software review tool and use it correctly it can be fast and greatly beneficial. slightly slowing the development process down in the short term in this manner would spare long debugging/fixing sessions when something silly gets into the central repository, saving time in the long term.  </p>

Body:
I would recommend using a code review system in addition to your source control system.  This would enforce that each commit would have to be reviewed and approved by other members of the team before being accepted to a repository.   Other benefits would include improved knowledge sharing and development process transparency.

edit:
Slowing things down is a worry but if you choose the right software review tool and use it correctly it can be fast and greatly beneficial. slightly slowing the development process down in the short term in this manner would spare long debugging/fixing sessions when something silly gets into the central repository, saving time in the long term.


问:
What exactly is a Search Engine Indexer. Where to start building one?
For one of the projects at uni we were given the task to create a custom, niche search engine. My colleges and I split the tasks amongst each other so that we can tackle the overall project more easily. My part is to create the indexer. I already read the wikipedia page on search engine indexers and some other related articles but I'm still struggling to understand exactly how it works and how it looks.

To me it is obvious that it is not just a regular table with an index and a descrption column. So my question would be, what is a search engine indexer comprised of, how does it architecture look, and where to start from in building one?

答:
At its core, a search engine index is simply an index that supports full text search. The most simple way to do that is a simple inverted index, i.e. for each word that occurs in any of the documents you have indexed, store a list of references to all the documents that contain this word.

For a university project, that's probably enough, but of course there's infinite room for improvement. You can combine multiple search words using AND and OR logic, and have a weight for each document depending on where and how often a word appears in it. That's the state of WWW search engines circa 1998, before Google revolutionized it with their PageRank algorithm. Since then, they've had hundreds (if not thousands) of people working on improving it continuously.

Additionally, to support an index for the entire WWW (or even a small part of it), you need a distributed architecture, something like MapReduce.


问:
OO Design: hint EntityManager to preload some datasets
say I have an EntityManager that can read(PK) a dataset from the DB and return it.

I have an application that will process multiple records, iterate over them and for each, use the EntityManager to read each record.

Therefore it would be nice to inform that EntityManager about the coming workload so it is able to preload the necessary data more efficiently.

How would you integrate such optional hints into a clean, SoC OO-Design?

Thanks alot

答:
I think it's not responsibility of EntityManager (ActiveRecord object I guess) to care about workload.

Add another object, which will preload entities to the cache storage in case of coming workload, then add class EntityManagerCached which will override method read() to check cache storage first and then read from DB.

Words like "manager" in the class name is a warning sign.


问:
Java serialization - advantages and disadvantages, use or avoid?
Serialization is used for persistence in Java. It may be okay to persist a few objects using serialization. But, for a large number of objects, ORM, Database etc might be better. It seems that serialization is useful only for small jobs. May be I am wrong. So please tell me
what are the advantages of serialization over non-serialization methods ? When should it be used and when should it be avoided ?

This question came to my mind after seeing DZone article Is Object Serialization Evil?

And these are the lines that gave rise to my question:

If you look at Java and its session objects, pure object serialization is used. Assuming that an application session is fairly short-lived, meaning at most a few hours, object serialization is simple, well supported and built into the Java concept of a session. However, when the data persistence is over a longer period of time, possibly days or weeks, and you have to worry about new releases of the application, serialization quickly becomes evil. As any good Java developer knows, if you plan to serialize an object, even in a session, you need a real serialization ID (serialVersionUID), not just a 1L, and you need to implement the Serializable interface. However, most developers do not know the real rules behind the Java deserialization process. If your object has changed, more than just adding simple fields to the object, it is possible that Java cannot deserialize the object correctly even if the serialization ID has not changed. Suddenly, you cannot retrieve your data any longer, which is inherently bad.

Now, may developers reading this may say that they would never write code that would have this problem. That may be true, but what about a library that you use or some other developer no longer employed by your company? Can you guarantee that this problem will never happen? The only way to guarantee that is to use a different serialization method.

答:
Serialization and an ORM / database are different things, although there is some overlap.

A serialized object represents all of the information needed to "thaw" a persisted object and repopulate its data. An ORM and database persist data to a database. A class can have fields of information that are not stored in the database by the ORM, for example computed field.

Additionally, serialization and an ORM are solving different problems. Serialization solves the problem of persisting an object graph to a stream (memory, file system, etc). An ORM handles the mapping of pieces of information to database columns and the retrieval and instantiation of objects, in addition to providing niceties such as searching and lazy loading.

Use an ORM when you want to persist data to a database for situations where you're dealing with large amounts of data or need reporting, searching / querying, warehousing or other things that databases are good at. Use serialization when you want to save a representation of your data structure(s) to disc.


答:
Serialization is mostly used in two areas:

prototyping of persistence

pretty much every object graph can quickly be made serializable, for quick proof-of-concepts or quick-and-dirty applications this might be faster than setting up a real ORM layer or other persistence system

short term storage of almost-arbitrary objects:

Applications servers, for example, have a tendency to persist session information using serialization. This has the advantage that the values in the session can be almost any type (as long as its serializable).

For almost all other uses, the drawbacks you (and the article) mentions are too big: the exact format is hard to keep stable, class changes can easily make your serialized data unreadable, reading/writing the data in non-Java code is almost impossible (or at least a lot harder than necessary).

JAXB and similar technologies provide similar functions with a similarly low cost, while reducing some of the problems.

Title: Java serialization - advantages and disadvantages, use or avoid?

Body:
Serialization is used for persistence in Java. It may be okay to persist a few objects using serialization. But, for a large number of objects, ORM, Database etc might be better. It seems that serialization is useful only for small jobs. May be I am wrong. So please tell me
what are the advantages of serialization over non-serialization methods ? When should it be used and when should it be avoided ?

This question came to my mind after seeing DZone article Is Object Serialization Evil?

And these are the lines that gave rise to my question:

If you look at Java and its session objects, pure object serialization is used. Assuming that an application session is fairly short-lived, meaning at most a few hours, object serialization is simple, well supported and built into the Java concept of a session. However, when the data persistence is over a longer period of time, possibly days or weeks, and you have to worry about new releases of the application, serialization quickly becomes evil. As any good Java developer knows, if you plan to serialize an object, even in a session, you need a real serialization ID (serialVersionUID), not just a 1L, and you need to implement the Serializable interface. However, most developers do not know the real rules behind the Java deserialization process. If your object has changed, more than just adding simple fields to the object, it is possible that Java cannot deserialize the object correctly even if the serialization ID has not changed. Suddenly, you cannot retrieve your data any longer, which is inherently bad.

Now, may developers reading this may say that they would never write code that would have this problem. That may be true, but what about a library that you use or some other developer no longer employed by your company? Can you guarantee that this problem will never happen? The only way to guarantee that is to use a different serialization method.


问:
Programming with Dyslexia
I have very severe Dyslexia along with Dysnomia and Dysgraphia. I have known about it since I was a child. My reading and writing skills are pretty crippled, but I have learned to deal with it.

However, with today's IDEs, I find it very easy to stay focused and in the zone when I code. But when I write text (like this post) I find it much harder to stay focused.

In general, do dyslexics find it easier to read and write code compared to general reading and writing? What types of tricks and tools do dyslexics use to help them master programming better than normal reading and writing?

答:
I've recently discovered that I'm dyslexic (at age 26) and am starting out in programming, studying a software engineering degree at university (after previously dropping out of a civil engineering degree at the same university in the final year when the course became assignment/report heavy - I now understand why).

I've been reading a lot (at my slow pace) as to what dyslexia is and why/how/where it affects us and I believe I can explain why we can still program well, despite how text heavy it is.

Dyslexic process their thoughts in pictures (well not pictures like on the wall, more like 3d video where you can move the camera and thus it's point of view around, I think of it as an internal world where I have the powers of 'god' (geez that sounds egotistical but I don't mean it that way) ie; I can instantly change everything about it with my thoughts.

Anyway, we can process words just fine, so long as we can firmly anchor/tether those words to an 'image', words like cat, hat, hit, run, jump, vertical, fluffy, hard etc are no problem at all, we can easily 'picture' what that is, the words we trip over are things like 'are' 'to' 'the' 'a' things where if someone asked you to draw that word (not write the word, actually draw a picture of it) you wouldn't know where to start.

In programming there are no such words, they all refer to either a process or an object, once we've learnt what the object or process is and our minds have formed a visualisation of it we're away. This site does a good job of explaining what I'm on about:

http://www.davisdyslexia.com/disorientation.html#tricky

BTW if trying to read the bold text in the middle of the page BEFORE running the mouse over it makes you dizzy or feel weird and you have trouble getting threw it, you might well be dyslexic. I've gotta push forwards threw the sentences to their end before i can make any sense of what's being described, i feel dizzy when reading it too.

One thing I'm struggling with is explaining to my math lecturer that I need real examples and not general solutions to learn, when he talks about a n by n matrix I can't picture a thing, I need to work with a 3x3 or 4x4 and then I can transfer the learnings/processes to all sizes of matrices. He remains adamant that general solutions are the only way for what he calls 'true' learning sigh.

Title: Programming with Dyslexia


问:
What problems can be solved using Generics?
I haven't used Generics in C# for a long while. Every time I think I need to use them I either go in the wrong direction and give up or find that I don't really need them. I feel that I'm missing out or ignoring a technique which could be useful and powerful.

I'm aware of how generics are meant to be used (or at least I think I am). If you have three methods that are all doing the same thing with different types, then using generics enables you to have just one method that will work with these three types.

EDIT (in response to comment)

Are there any code smells or patterns that I should be looking out for?

Note I use List<> a lot, so I'm not ignoring generics in the the standard library. It's just that I've not written custom code using Generics for a while.

答:
As Microsoft says (and others have said in the comments), the most common place to use generics is when you want to define an operation on a list of objects, but don't care too much about the specific types of the objects in the list.

The classic example is sorting a list.

One code smell that possibly indicates the use of generics may improve matters is (from Jeff Atwood):