答:
You're focusing on that one interface, but you have at least four different customization points available to you:

The interface itself.

The code that implements the interface.

The code that calls Add.

ImyBase and its derivatives.

You haven't provided enough information about the latter two, but that's likely where your solution is, since you've been unable to find a satisfactory solution using only the first two.  Some possible solutions are:

Look into using parameterized classes or methods (the ones with <Type>) to restrict the types while still avoiding duplication.

Move some functionality from your concrete classes implementing Add to the ImyBase objects.  Generally, container-like objects benefit from being as generic as possible, only doing container stuff and nothing else.

Try moving Add to the ImyBase object.  Sometimes reversing who gets added to whom simplifies the code, or at least helps open your eyes to other possibilities, which is why it is useful as an exercise.

You're on the right track with your criteria for a good design.  You should be able to find a solution that uses the type system instead of a manual check.

Title: Interface method signature not restrictive enough

Body:
I wrote a piece of code at my job sometime ago. While writting the code I wrote few interfaces who would allow me to add more flexibility and at that time I was also trying to understand OOP concept more deeper. So in the interface I wrote I have a method signature similar to this :

```<code>void Add(ImyBase objToAdd)
</code>```

And then I have few class implementing this interface. But what is bothering me is that I find myself doing this kind of thing pretty often in this Add method

```<code>public void Add(ImyBase objToAdd)
{
    if(!(objToAdd is ImyBaseDeviation))
        throw new ArgumentException("blablabla");

    //do stuff
}
</code>```

At the time it was a smell to me but I didn't really bothered with it simply because I'm solo on this projet and this piece of code is only used within my compagny and there only 2 IT guys in there (me + some one else) and this is not near to change. Anyway I recently came back to that piece of code and from my previous reading (actually more than that but this one is pretty similar) it now actually really look bad to me and I'm trying to figure out the best way to improve this piece of code.

I don't like the code as it stand now because the interface allow more than the concrete type generally allow so basically the concret implementation doesn't respect the contract given by the interface.

I tough of a few solutions

First simply delete the Add method from the interface since anyway calling Add have a high chance to throw an exception. So to call Add you need the concret type anyway. So here the object would still have a Add method but with the accepted type as a parameter.

Secondly add a method who would look something like this in the interface

```<code>bool IsValidToAdd(ImyBase objToTest)
</code>```

But that doesn't satisfy me.

So I'm seeking advise from more advance people like you to help me to figure out what would be the best way to implement this so it stay the cleanest possible.

Sorry I'm not a native anglophone so if my question need editing or grammar fixing please go ahead. Thank you


问:
Where can I find "SVN for Git Users" resources?
So I took a job where the firm uses SVN (but will be moving to Git sometime in the future). The problem is that I don't know SVN. I've tried numerous Google queries and all I can ever find are SVN->Git tutorials, "Why is Git better than SVN" blogs, and a particular "cheat sheet" that gives (some) comparable commands...

Short of reading the O'Reilly book on SVN, what are the brief (but not too brief) instructions to SVN for Git users?

答:
Use git svn if possible. I have been in your situation and after half a year of frustration I switched to git svn and have been happy since then.

Git svn lets you use the repository locally and committing to the SVN server is then handled by a git svn rebase which rebases your local changes onto the subversion trunk and then git svn dcommit which commits the rebased commits.

Maybe it is not optimal for advanced Subversion usage, but since you are using git locally everything is fine.

When using git clone you should not clone the subversion root folder but your target directory directly (clone trunk). This will make git run a lot faster, otherwise your working copy can become huge.

Disclaimer: I do not know how the situation is when you want to create Subversion branches, etc. The teams I worked with did not use branches (just me local git branches).

ContentLicense: CC BY-SA 3.0


答:
The canonical reference is the Subversion RedBook. Regardless of your past skills, read this from fresh and you'll get all the usage information you need. Its not difficult or completely alien, most people say SVN is a lot easier to understand than git so you should be fine with just a little bit of reading the main commands. The basic usage chapter should get you up and running without problem.

There are 2 main differences:

commit = push to central repo. There is no rebase or local commit, no pulls either.

branching is by directory. Best to think of the entire repo as a directory structure, branching is like making a symlink with copy-on-write semantics. Whereas in git you branch the entire repo and switch between them so the new branch 'overlays' your working copy, with SVN you can swap pieces of your repo out. Generally people branch on a top-level folder (usually called branches) so switching becomes much more like git's 'overlay' style of working.

Branching is trivial, merging is nowhere near as bad as DVCS apologists want to make out, especially if you stick to the "standard" trio of top-level folders (called trunk, branches and tags).

There are a few bits that SVN beats git in, sparse directories comes to mind - where you checkout only part of your repo. When you need more parts, you update only what you need. If you have a huge repo (eg a core product and loads of plugins) this is brilliant.

There are a few bits that are not as good as git, the dreaded tree conflict comes to mind - where you have a conflict at directory level (ie someone's deleted a file you've edited)

If you're on Windows, use TortoiseSVN. It rocks majorly.

Title: Where can I find "SVN for Git Users" resources?

Body:
So I took a job where the firm uses SVN (but will be moving to Git sometime in the future). The problem is that I don't know SVN. I've tried numerous Google queries and all I can ever find are SVN->Git tutorials, "Why is Git better than SVN" blogs, and a particular "cheat sheet" that gives (some) comparable commands...

Short of reading the O'Reilly book on SVN, what are the brief (but not too brief) instructions to SVN for Git users?


问:
How to (or should I) have one assert per test with object comparisons?
I've recently read The Art of Unit Testing by Roy Osherove which I found very useful for helping me establish how to define a good unit test.

One key aspect of the guidelines Roy puts forward are to make sure that one test only tests one thing, which is part of the following guidelines he puts forward:

Make sure the test tests one thing only (p. 179)

Make sure the test verifies only on a single call to a mock object. Verifying multiple calls on a mock object is either over specification or testing multiple things.

One good way to help achieve this is by having a single assert in each unit test.

However if the unit test is to validate the behaviour of a method returning an object which specific properties, how can this be verified with a single assert? It seems the possible answers are:

Don't, just use multiple asserts to validate each expected property of the returned object

Override Object.Equals and Object.GetHashCode (In C#) so that the two objects can easily be compared.

Use a framework that allows for two objects to be compared (For example http://comparenetobjects.codeplex.com/ in C#)

答:
I think there's too much ideology in unit testing. 1 assert per test is such an example.

Unit testing is about testing a unit, ie one thing. So if you have a class with 5 properties on it, its perfectly acceptable to hit all 5 props to see if they work. If any of them fail, the test fails.

It makes no difference to attempt to test each of the 5 properties in individual tests - if any one of them fails, you gain nothing. (I assume you write enough info to tell which assertion has failed, and some logging or other diagnostics to tell why it failed). In short, your object failed and you have to fix it. If you need more detail that that, you need a lot more detail than you get from a single assertion anyway.

What I wouldn't do is try to test many objects in a single test.

Find a sweet spot between too many unit tests and overly large unit tests.


问:
Progressive Enhancement vs. Single Page Apps
I just got back from a conference in Boston called An Event Apart.

A really popular theme amongst the speakers was the idea of progressive enhancement - a site's content should go in the HTML, and JavaScript should only be used to enhance behavior.

The arguments that the speakers gave for progressive enhancement were very compelling. Not only is it a solid pattern for supporting older browsers, and devices on a network with low bandwidth, but HTML fails much more gracefully than JavaScript (i.e. markup that is not supported is just ignored, while if a browser throws an exception while executing your script - you are hosed).

Jeremy Keith gave a particularly insightful talk about this.

But what about single page web apps like Backbone and Angular? The whole design behind these frameworks seems to push the developer toward moving content out of the HTML, and into something like a JSON API.

I can not seem to gel these two design patterns: progressive enhancement vs. single page web apps. Are there instances when one is better than the other? Or are they not even antagonistic technologies, and I am missing something here with my mental model?

答:
I think it depends how far you want to go with Progressive Enhancement - it's a design paradigm rather than a hard-and-fast set of rules.

If you're using a SPA framework, I think allowing Javascript is a given. However the Javascript you write to enhance your page must be smart enough to deal with whatever HTML the framework can create.

You can also benefit from other PE techniques such as taking advantage of the latest CSS features for a recent browser release, or HTML5 to HTML4 degradation.


答:
The other answer is a great, pragmatic answer. I will take a different stance, however.

While I agree that asserting one thing can be more general than people often make it out to be, in your particular situation, you have mentioned the correct answer.

.Equals() and .GetHashCode() exist. Your object has them. They are currently useless. Any solution other than implementing them is leaving a potential weak point later on. Object comparisons are important, and likely to be reused. Moreover, having the methods you call actually do useful things is highly beneficial.

While it may seem like a waste as you don't intend to reuse them, that argument does not apply to these two methods because they are a fundamental part of the language.

Title: How to (or should I) have one assert per test with object comparisons?

Body:
I've recently read The Art of Unit Testing by Roy Osherove which I found very useful for helping me establish how to define a good unit test.

One key aspect of the guidelines Roy puts forward are to make sure that one test only tests one thing, which is part of the following guidelines he puts forward:

Make sure the test tests one thing only (p. 179)

Make sure the test verifies only on a single call to a mock object. Verifying multiple calls on a mock object is either over specification or testing multiple things.

One good way to help achieve this is by having a single assert in each unit test.

However if the unit test is to validate the behaviour of a method returning an object which specific properties, how can this be verified with a single assert? It seems the possible answers are:

Don't, just use multiple asserts to validate each expected property of the returned object

Override Object.Equals and Object.GetHashCode (In C#) so that the two objects can easily be compared.

Use a framework that allows for two objects to be compared (For example http://comparenetobjects.codeplex.com/ in C#)


问:
Zero Day Exploit Ethics/Etiquette
What are my responsibilities, as a developer, if I stumble upon a zero day exploit in a widely used third party piece of software?

Should the developer only tell the third party to limit the affect?

What if the third party doesn't come clean to all its user base, who else should be alerted?

What are the responsibilities of the third party software providers to alert their user base of vulnerabilities in their software?

答:
Your question covers law, ethics and self preservation. I personally think in a perfect world you would tell the software producer and they should have two months to patch it after which you should submit it to a vulnerability database. The software producer should be receptive and grateful and possibly even work with you to patch the problem and test the patch.

Unfortunately, we don't live in a perfect world. Software companies have a tendency of seeing disclosure as an attack and have a tendency to sue. Even private disclosure carries risks.

What I would do is research how the company has acted in the past. If they reacted negatively I might submit the information anonymously and leave it at that. If they are more receptive I would get in contact with them and submit the information being as nonthreatening as possible, working with them to decided how to proceed.

I would avoid giving a hostile, litigious company my details and I would not advise just dropping it onto the internet.

Title: Zero Day Exploit Ethics/Etiquette


问:
Why don't languages include implication as a logical operator?
It might be a strange question, but why there is no implication as a logical operator in many languages (Java, C, C++, Python Haskell - although as last one have user defined operators its trivial to add it)? I find logical implication much clearer to write (particularly in asserts or assert-like expressions) then negation with or:</p>

```<code>encrypt(buf, key, mode, iv = null) {
    assert (mode != ECB --> iv != null);
    assert (mode == ECB || iv != null);
    assert (implies(mode != ECB, iv != null)); // User-defined function
}
</code>```

答:
For me, the big problem with implies comes when the initial condition is false; for example: "If the sun is green, then I am a fruit bat." True!

In formal logic it just works to assign "True" to the value when the condition of the implication isn't met. But in programming, that could lead to counter-intuitive and surprising results.

I actually think the example @Heinzi gives above:

```<code>if (sun.color() == "green") then assert(me.species() == "fruitbat")
</code>```

Is much easier to understand, and less prone to errors due to misunderstanding the logic.

In the context of testing, I'd just halt the moment my assumptions became false:

```<code>assert(sun.color() == "green")
assert(me.species() == "fruitbat")
</code>```

So, to @Eric Lippert's point, as a programmer I don't know when I'd use an implies operator. The "False is True" behavior seems useful in the context of mathematical, formal logic, but could lead to unexpected results in program logic.

...

No one has mentioned the common "?" operator, where "A ? B : true" is the same as "implies". But while formal logic assigns true to the "else" condition, "?" lets the developer assign that explicitly.

In formal logic, using "true" works out, but in programming, if the condition is false, then the better answer is more like "null" or "void" or "skip", or even maybe false.

I think someone would have to make the case why "implies" is a more useful operator than "?", or "if" statements, or just regular program flow.

Body:
For me, the big problem with implies comes when the initial condition is false; for example: "If the sun is green, then I am a fruit bat." True!

In formal logic it just works to assign "True" to the value when the condition of the implication isn't met. But in programming, that could lead to counter-intuitive and surprising results.

I actually think the example @Heinzi gives above:

if (sun.color() == "green") then assert(me.species() == "fruitbat")

Is much easier to understand, and less prone to errors due to misunderstanding the logic.

In the context of testing, I'd just halt the moment my assumptions became false:

assert(sun.color() == "green")
assert(me.species() == "fruitbat")

So, to @Eric Lippert's point, as a programmer I don't know when I'd use an implies operator. The "False is True" behavior seems useful in the context of mathematical, formal logic, but could lead to unexpected results in program logic.

...

No one has mentioned the common "?" operator, where "A ? B : true" is the same as "implies". But while formal logic assigns true to the "else" condition, "?" lets the developer assign that explicitly.

In formal logic, using "true" works out, but in programming, if the condition is false, then the better answer is more like "null" or "void" or "skip", or even maybe false.

I think someone would have to make the case why "implies" is a more useful operator than "?", or "if" statements, or just regular program flow.


问:
How do I find average bits per symbol using huffman code?
I'm trying to write a program in c for Huffman coding, but I am stuck. For input I have:

```<code>Sample input:
4      // here I scan how many letters I have
A 00   // and for everyone I scan how they are coded in string down
B 10
C 01
D 11
001010010101001011010101010110011000 //this is a suboptimal huffman code
</code>```

So first I have to decode this string, and to find out how many times every letter         appear. And I already do that. But now I have to find out how many bits have every letter using huffman tree, and in the output I have to print the average bit per symbol.

The output for this example here have to be:

```<code>Sample output
1.722
</code>```

So now, how to find out how many bits have every letter with huffman coding?

答:
Once you have the Huffman coding tree, the optimum code for each symbol is given by the path to the symbol in the tree.

For instance, let's take this tree and say that left is 0 and right is 1 (this is arbitrary) :

```<code>/ \
A  \
   /\
  B  \
     /\
     C D
</code>```

Path to A is left, therefore its optimum code is 0, the length of this code is 1 bit.
Path to B is right, left, its code is 10, length 2 bits.
C is right, right, left, code 110 ,3 bits, and D right, right, right, right, code 1111, 4 bits.

Now you have the length of each code and you already computed the frequency of each symbol.
The average bits per symbol is the average across these code lengths weighted by the frequency of their associated symbols.

Body:
Once you have the Huffman coding tree, the optimum code for each symbol is given by the path to the symbol in the tree.

For instance, let's take this tree and say that left is 0 and right is 1 (this is arbitrary) :

/ \
A  \
   /\
  B  \
     /\
     C D

Path to A is left, therefore its optimum code is 0, the length of this code is 1 bit.
Path to B is right, left, its code is 10, length 2 bits.
C is right, right, left, code 110 ,3 bits, and D right, right, right, right, code 1111, 4 bits.

Now you have the length of each code and you already computed the frequency of each symbol.
The average bits per symbol is the average across these code lengths weighted by the frequency of their associated symbols.

OwnerDisplayName: Grapsus


问:
Implementing a first basic interpreter: what should I learn first?
I'm about to implement my own very simple programming language, and an interpreter to execute code in that language.

The language will be very basic. Example code:

```<code>var x = 3
if x > 2 print x
if x < 2 print "hello"
</code>```

The language wouldn't feature anything more complex than single-line if statements. This is because it's the first time I'm attempting something like this, so I'm starting small.

The interpreter will be written in Java, and thus execute the code with Java operations.

My question is this:

I know that the topic of creating compilers and interpreters is very complex. But since I'm new to this, I believe I should start with basic techniques and approaches.

What should I learn before starting to work on this project? Especially what kind of knowledge regarding parsing and interpreting should I learn before starting?

Is it enough to just 'break down the text into substrings, and then more substrings', or should I learn more advanced techniques and apply them?

The knowledge and experience I acquire are meant to allow me to later build more knowledge on top of it when I continue learning and implementing interpreters. But shouldn't be 'too much' for a first attempt.

答:
Its going to depend a bit on the path you take for your interpreter.  But the first thing you might want to try creating is a basic mathematical expression evaluator, because ultimately that can form the core of an interpreter.  Calculating statements like (8 * 4) + 10 and ((10 + 2) * (11 / 5)).  This will get you exposed to parsing code, breaking everything into tokens, stacks, and other concepts without completely overwhelming you.

Once you have it working with math expressions, extend it with functions.

(8 * 4) + max( 5, 10)

Then data types

"this" + "that"

That's a fairly large project, and should get you a good feeling for all that's involved.

For starters, look at the Shunting Yard Algorithm


答:
I believe single page web-apps and progressive enhancement are almost antagonists. If the html is computed on the client from data retrieved from a json api, it can hardly degrade gracefully. It can however offer a richer and more pleasant user interface.

You can set up a bot which will crawl you application and save a static version. This technique can be used to serve HTML to browsers without javascript (used by blind people or search engine bots). This is an investement, so it really comes down to your requirements.

Are you making an HR management web-app for a specific compagny? You don't need graceful degradation, and a SPA may be more simple to build. The company may enforce the usage of a specific browser, so you may have less tests to do.

Are you making a public website for an association with accessibility requirements and search engine visibility needs? Then consider building the HTML on your server. Or making an SPA with a static version, depending on your budget.

Title: Progressive Enhancement vs. Single Page Apps

Body:
I just got back from a conference in Boston called An Event Apart.

A really popular theme amongst the speakers was the idea of progressive enhancement - a site's content should go in the HTML, and JavaScript should only be used to enhance behavior.

The arguments that the speakers gave for progressive enhancement were very compelling. Not only is it a solid pattern for supporting older browsers, and devices on a network with low bandwidth, but HTML fails much more gracefully than JavaScript (i.e. markup that is not supported is just ignored, while if a browser throws an exception while executing your script - you are hosed).

Jeremy Keith gave a particularly insightful talk about this.

But what about single page web apps like Backbone and Angular? The whole design behind these frameworks seems to push the developer toward moving content out of the HTML, and into something like a JSON API.

I can not seem to gel these two design patterns: progressive enhancement vs. single page web apps. Are there instances when one is better than the other? Or are they not even antagonistic technologies, and I am missing something here with my mental model?


问:
How to pick the testing values for parameterized tests for stateless functions?
When writing (parameterized) tests for stateless functions, how do I determine the most ideal set of values to test with?

I'm writing a class with mathematical functions in C#, and I want to write unit tests for them. Today I want to write this function (really!):

```<code>int Clamp(int value, int lowerBound, int upperBound)
{
    // TODO: Implement.
    return 0;
}
</code>```

As good TDD practice dictates, I'm writing the unit tests first and the implementation later. I can write a parameterized test for this stateless function, but have to decide on the best set of values to test with.

My current strategy for picking testing values is:

For each parameter, I can pick values from the whole set of 32-bit signed integers. I'm not using randomly generated values as that would make the test non-repeatable. To test the corner cases, I pick -1, 0, 1, but also the −2147483648 (minimum 32-bit signed integer) and 2147483647 (maximum 32-bit signed integer). I would also need to pick a 'normal' value, for example, 42, to make sure I'm not only testing corner cases. Is one normal value enough? And a negative one, let's say -63. Did I miss any?

```<code>−2147483648, -63, -1, 0, 1, 42, 2147483647
</code>```

If any of the three parameters can have any of just these seven values, I'll end up with 343 tests for one function! Before I'm going to write 343 tests, I really have to ask:

Are these the right values to test with? In general, what strategy can I use to pick the most effective values to use?

答:
Test Driven Development principles suggest that you test cases cover a range of conditions, not only testing over a range of valid input, but testing for handling of error conditions as well.

So first start testing how it handles invalid / valid input, to see if it correctly handles erroneous input,

That includes:

Simple known good case (PASS)

Simple known "bad" input (FAIL)

Based on the underlying datatype, values at boundaries for that datatype (e.g. INT_MAX, INT_MIN, a string of maximum or minimal length including the empty string)

With numerical values, testing a signed value

Testing values over a complete range of input values, beyond what makes sense for the application usage. If you assumes the parameter is normally going to be between 1 and 10, how does it handle 1000000 or -10? This can be tricky to comprehensively test for floating point in particular.

The extensiveness of testing is determined on factors such as how widespread usage is (i.e. is it an one-off usage at the moment versus inclusion in a common library), how critical are failures? (user loses a casual game versus vehicle's brakes cease to function)

If any of the three parameters can have any of just these seven values, I'll end up with 343 tests for one function! Before I'm going to write 343 tests,

Don't confused tests with test cases, test cases should be thought of as mere data.

You should write code that loops through those test cases that may be stored as external CSV text files, and see if they match the expected outcome. Break the cases into lists of "good" (expect to pass) values and "bad" (expect to fail) values and simply test whether the function behaves (PASS/FAIL) as expected give the combination of input data (all cases with valid input should pass, all cases with any invalid input should fail), without verifying the correctness of the output.

Then for a set or subset of interesting input values you can compare the output values to the expected output values, that are normally generated independently of the code being developed (e.g. for many simpler cases for numeric calculations a spreadsheet can be used), making sure to handle floating point comparisons sanely.

If you generate the test case data automatically, then the number of test cases only becomes a factor once the execution speed is an issue, an increasingly rare issue when testing at function test.

In the case of your example function, where for any input the output should be valid, then you can simple test the correctness of the output given the particular combination of input values.

It does help force you to limit the numbers of parameters to a function, which is normally a good thing as it limits the functions to do one thing well, and not become a ugly monster of special cases based on those additional values.


问:
Large MySQL Batch Inserts From PHP: Run insert from script, or save as SQL file?
We have a large dataset that's current residing in many, many spreadsheets.

I've been tasked with getting part of that data into our MySQL DB.

When all is said and done, I will probably be inserting somewhere around 3 million rows.

I intend to collect the inserts into batches of about a quarter-million or so (parsing through it with PHP).

Initially, my plan was to just run/send those batch INSERTs straight from my script.

More recently, though, I thought about actually writing out the INSERTs to .sql files for later importing.

I tried to google around on this a little ... didn't find much.

Are there any real pro's/con's one way or the other?

If not, I'm inclined to stick with my original plan.

Otherwise, I'm completely open to suggestions.

答:
The only major plus I see one way or the other is that by making the .sql files, if some problem occurs and you have to blow away the database and re-do the import process, you don't have to re-run your scripts against the spreadsheets.  Or looking at it another way, you can test the process on a test server before doing the actual import.

But if this is just a one time thing, ultimately, either would suffice.


问:
Why don't more languages have the ability to compare a value to more than one other value?
Consider the following:

```<code>if(a == b or c)
</code>```

In most languages, this would need to be written as:

```<code>if(a == b or a == c)
</code>```

which is slightly cumbersome and repeats information.

I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea.

Why don't more languages offer it? Is there performance or syntax issues?

答:
In languages with macros, it's easy to add something like that if it's not already there. Consider Racket

```<code>(define-syntax-rule (equal-any? a b ...)
  (or (equal? a b) ...))
(equal-any? "a" "b" "a")
> #t
</code>```

In other languages without metaprogramming, maybe you can reformulate that as set/list membership checking perhaps:

```<code>if a ∈ {b, c}
</code>```

Body:
In languages with macros, it's easy to add something like that if it's not already there. Consider Racket

(define-syntax-rule (equal-any? a b ...)
  (or (equal? a b) ...))
(equal-any? "a" "b" "a")
> #t

In other languages without metaprogramming, maybe you can reformulate that as set/list membership checking perhaps:

if a ∈ {b, c}


答:
Some languages do have such features. E.g. in Perl6 we can use Junctions, which are “superpositions” of two values:

if $a == any($b, $c) {
    say "yes";
}

# syntactic sugar for the above
if $a == $b | $c {
    say "yes";
}
```

<p>Junctions allow us to express operations on a set of data quite succinctly, similar to the way scalar operations distribute over collections in some languages. E.g. using Python with numpy, the comparison can be distribute over all values:</p>

<pre class="lang-py prettyprint-override"><code>import numpy as np
2 == np.array([1, 2, 3])
#=> np.array([False, True, False], dtype=np.bool)
(2 == np.array([1, 2, 3])).any()
#=> True
</code>```

However, this only works for selected primitive types.

Why are junctions problematic? Because operations on a junction distribute over the contained values, the junction object itself behaves like a proxy for method calls – something few type systems aside from duck typing can handle.

Type system problems can be avoided if such junctions are only allowed as special syntax around comparison operators. But in this case, they are limited so much that they don't add sufficient value to be added to any sane language. The same behavior could be expressed using set operations or spelling out all comparisons manually, and most languages do not believe in adding redundant syntax if there is already a perfectly fine solution.

Title: Why don't more languages have the ability to compare a value to more than one other value?

Body:
Consider the following:

```<code>if(a == b or c)
</code>```

In most languages, this would need to be written as:

```<code>if(a == b or a == c)
</code>```

which is slightly cumbersome and repeats information.

I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea.

Why don't more languages offer it? Is there performance or syntax issues?

Body:
Some languages do have such features. E.g. in Perl6 we can use Junctions, which are “superpositions” of two values:

if $a == any($b, $c) {
    say "yes";
}

# syntactic sugar for the above
if $a == $b | $c {
    say "yes";
}

Junctions allow us to express operations on a set of data quite succinctly, similar to the way scalar operations distribute over collections in some languages. E.g. using Python with numpy, the comparison can be distribute over all values:

import numpy as np
2 == np.array([1, 2, 3])
#=> np.array([False, True, False], dtype=np.bool)
(2 == np.array([1, 2, 3])).any()
#=> True

However, this only works for selected primitive types.

Why are junctions problematic? Because operations on a junction distribute over the contained values, the junction object itself behaves like a proxy for method calls – something few type systems aside from duck typing can handle.

Type system problems can be avoided if such junctions are only allowed as special syntax around comparison operators. But in this case, they are limited so much that they don't add sufficient value to be added to any sane language. The same behavior could be expressed using set operations or spelling out all comparisons manually, and most languages do not believe in adding redundant syntax if there is already a perfectly fine solution.


答:
In most languages, this should be trivially achievable by writing an In function, so why make it a part of the actual language?

Linq, for example, has Contains().

Alright, for all you pedants, here's my implementation in C#:

```<code>public static bool In<T>(this T obj, params T[] values)
{
    for(int i=0; i < values.Length; i++)
    {
        if (object.Equals(obj, values[i]))
            return true;
    }
    return false;
}
</code>```

Body:
In most languages, this should be trivially achievable by writing an In function, so why make it a part of the actual language?

Linq, for example, has Contains().

Alright, for all you pedants, here's my implementation in C#:

public static bool In<T>(this T obj, params T[] values)
{
    for(int i=0; i < values.Length; i++)
    {
        if (object.Equals(obj, values[i]))
            return true;
    }
    return false;
}


答:
Because it's a non-problem, and solving it brings basically zero benefit, but implementing it brings non-zero cost.

Existing range-based functions and such that practically every language does offer can work perfectly well in this situation if it scales to a size where a == b || a == c won't cut it.


答:
"if(a == b or c)" works in most languages: if a == b or if c is not negative, null, or zero.

Complaining that it's verbose misses the point: you shouldn't be piling a dozen things into a conditional. If you need to compare one value to an arbitrary number of other values, then build a subroutine.


问:
Languages on a resume: Is it better to put "C/C++" or "C, C++"?
I'm graduating in a couple of weeks, and my resume (as expected) lists the languages that I've had experience with. Previously I've put "C/C++", however back then I didn't have that much experience with these two languages as I do now.

Now that I've formally learned these two languages, it has become evident to me (and anyone who really knows these languages) that they are similar, and completely disimilar at the same time. Sure, most C code is compilable C++ code, but syntax and incorporation of library functions is pretty much where these similarities end. In most non-trivial problems, chances are that the desirable C++ solution will be different from the desirable C solution.

My question:

Will recruiters take note or care about whether you put "C/C++" as opposed to "C, C++"? Will they assume a lack of knowledge of the workings of either because of the inclusion of the first form, or perhaps see the inclusion of the second form as a potential "resume beefer" (listing them as 2 languages, instead of "one")?

Furthermore, for jobs that you've applied to that were particularly interested in these two langauges, did the interview process include questions about the differences between C programming and C++ programming (so, about actual programming techniques, not only the extra paradigms in the latter)?

答:
Probably doesn't matter

At least not to recruiters.  Most recruiters will probably treat them as the same thing or at least a variation of the same thing.  The more technically advanced are probably not paying attention to such a minor detail.

However, I would worry about "resume beefing" if you had a description for each.  If you include a description for the languages you list, list them together and include a partial sentence for each.

ContentLicense: CC BY-SA 2.5


答:
The syntax issue is – that it requires syntax.

Whatever syntax your language has, people using the language have to learn it.  Otherwise they run the risk of seeing code and not knowing what it does.  Thus it's generally considered a good thing if a language has a simple syntax that cleanly handles a lot of cases.

In your specific example, you are trying to take an infix operator (a function that takes two arguments but is written Argument1 Operator Argument2) and trying to extend it to multiple arguments.  That doesn't work very cleanly because the whole point of infix operators, to the extent that there is one, is to put the operator right in between the 2 arguments.  Extending to (Argument1 Operator Argument2 MagicallyClearSymbol Argument3...) doesn't seem to add a lot of clarity over Equals(Arg1,Arg2,...).  Infix is also typically used to emulate mathematical conventions that people are familiar with, which wouldn't be true of an alternate syntax.

There would not be any particular performance issues associated with your idea, other than that the parser would have to deal with a grammar with another production rule or two, which might have a slight effect on the speed of parsing.  This might make some difference for an interpreted or  JIT compiled language, but probably not a big difference.

The bigger problem with the idea is just that making lots of special cases in a language tends to be a bad idea.


问:
What specifications in software development are relevant to the clients?
Say your company develops software, and a client wants you to handle their development. It just so happens, that they have their own IT-team, but it is fully tied up, so they outsource to you.

The project is in a quotation phase, and your client's Head of IT now asks for a requirement specification (SRS), an architectural specification, and so on. The Head of IT wants to know functions, modules and other decisions that will be in construction.

Other than the SRS for analysis, is your company obliged to provide these specifications, even before the project has been confirmed?

答:
Looking at it from a business perspective, I don't think this is a matter of obligation. Since the project has not been confirmed yet, and no contract has been signed, you are not obliged to provide anything.

However, it is in your interest to present your [potential] client with whatever you think will optimize your chances of getting the contract.

I think that since the client has its own IT department, it may be interested in more technical details than other clients, as it has more relevant experience, and (at least believes he) has more tools to evaluate you as a service provider by you answering those questions.

I also think that by building a rapport with the head of IT, by engaging him in an amicable and serious conversation, even if you don't provide concrete answers to his specific questions (since you did not yet put in your full effort on thinking about them) and only giving him your state of mind and thoughts about your possible architecture, you would be able to convince him that you will be able to come up with satisfying results, and continuous communication on progress.

What the head of IT is probably most anxious about is that he outsources work he knows he is capable of doing to someone else. This is loss of control on his side. His worst case scenario is that at the end of this project, X months from today, he will be left with a dwindling budget, and lousy code he will have to clean up and re-write.

If you give him sense of control by open communication, he will be more receptive to letting you have your contract, and will also reflect less stress on you while the project is in progress.


问:
UML Diagram for Locations of Components
I am about to deploy a new project that will have different components being deployed on different servers and in different web sites/technologies/etc. I was just wondering what would be the best way to communicate this with the business?

I want to show that Service X will exist on server Y as a Windows Service and Service Z will exist on server Q as a .NET web service etc.

答: I would use a Deployment diagram as the following.

Title: UML Diagram for Locations of Components


问:
Why do some embedded projects shun cross-compiling?
As I've been getting into embedded systems I've noticed that some projects (Arch Arm and OpenBSD for example) frown upon cross compiling. What is the reasoning for this? Is a cross-compiled binary somehow different from a natively compiled one?

OpenBSD suggests that building on the hardware ensures that the system is fully functional (and also self-hosting) and that makes complete sense. But do people actually develop and compile kernel drivers on the hardware they are developing for? It sounds very time consuming.

From OpenBSD FAQ:

"Cross-compiling tools are in the system, for use by developers bringing up a new platform. However, they are not maintained for general use."

-http://www.openbsd.org/faq/faq5.html#ProbXComp

I'll see if I can hunt down the IRC log where a developer from ArchLinux Arm told me that they don't cross compile, though they seem to have updated their info on cross-compiling with DistCC: http://archlinuxarm.org/developers/distcc-cross-compiling

答:
For projects like Arch Linux ARM and OpenBSD that are trying to build and maintain a complicated, interactive user environment, a strong preference for doing "native builds" (in OpenBSD terminology) forces developers to "eat their own dogfood" and minimizes the MxN problem of maintaining M code generators in N environments.

For an embedded systems project with one target environment and application code under the control of a small group of developers, that reasoning doesn't apply.


答:
I think you have to learn at least two main concepts in order to successfully implement your basic interpreter : language processing and expression evaluation.

You might be able to get somewhere with manual string operations, but it will be tedious and probably have serious limitations or bugs. To right way to do it is to use a language processing library. The purpose of this kind of software is to transform the source code into an easy to use memory representation called Abstract Syntax Tree. For example 3 * (5 + 1) will be transformed into a tree like this :

```<code>     *
    / \
   3   +
      / \
     5   1
</code>```

There is a little bit of theory to understand in order to successfully implement this transformation. But the skill will be reusable for full-featured complex languages or domain specific languages. For Java, ANTLR is a pretty common library for language recognition, you should check it out : http://www.antlr.org/

The second skill will be about evaluating the AST. You need to learn about tree-like data structures and how to work with them. This will enable you to evaluate the AST and obtain the result and perform the actions requested by the program. Here is a very simple example of kind of code that you will need to write in order to evaluate the AST above :

```<code>def evaluate(tree):
    if tree.label == "*":
        return evaluate(tree.left) * evaluate(tree.right)
    elif tree.label == "+":
        return evaluate(tree.left) + evaluate(tree.right)
    else:
        return int(tree.label)
</code>```

To go further you may also try to write a compiler instead of an interpreter. The first step is the same, but instead of evaluating the nodes of the tree, you'll have to output some kind of machine code that will do the job afterwards.
Real hardware assembly can be difficult, but JVM bytecode is pretty simple and has a decent performance. There are libraries that can handle the binary aspect of it for you. For example ASM : http://asm.ow2.org/ This is how JVM languages work in general.

Good luck !

Title: Implementing a first basic interpreter: what should I learn first?

Body:
I'm about to implement my own very simple programming language, and an interpreter to execute code in that language.

The language will be very basic. Example code:

```<code>var x = 3
if x > 2 print x
if x < 2 print "hello"
</code>```

The language wouldn't feature anything more complex than single-line if statements. This is because it's the first time I'm attempting something like this, so I'm starting small.

The interpreter will be written in Java, and thus execute the code with Java operations.

My question is this:

I know that the topic of creating compilers and interpreters is very complex. But since I'm new to this, I believe I should start with basic techniques and approaches.

What should I learn before starting to work on this project? Especially what kind of knowledge regarding parsing and interpreting should I learn before starting?

Is it enough to just 'break down the text into substrings, and then more substrings', or should I learn more advanced techniques and apply them?

The knowledge and experience I acquire are meant to allow me to later build more knowledge on top of it when I continue learning and implementing interpreters. But shouldn't be 'too much' for a first attempt.

Body:
I think you have to learn at least two main concepts in order to successfully implement your basic interpreter : language processing and expression evaluation.

You might be able to get somewhere with manual string operations, but it will be tedious and probably have serious limitations or bugs. To right way to do it is to use a language processing library. The purpose of this kind of software is to transform the source code into an easy to use memory representation called Abstract Syntax Tree. For example 3 * (5 + 1) will be transformed into a tree like this :

     *
    / \
   3   +
      / \
     5   1

There is a little bit of theory to understand in order to successfully implement this transformation. But the skill will be reusable for full-featured complex languages or domain specific languages. For Java, ANTLR is a pretty common library for language recognition, you should check it out : http://www.antlr.org/

The second skill will be about evaluating the AST. You need to learn about tree-like data structures and how to work with them. This will enable you to evaluate the AST and obtain the result and perform the actions requested by the program. Here is a very simple example of kind of code that you will need to write in order to evaluate the AST above :

def evaluate(tree):
    if tree.label == "*":
        return evaluate(tree.left) * evaluate(tree.right)
    elif tree.label == "+":
        return evaluate(tree.left) + evaluate(tree.right)
    else:
        return int(tree.label)

To go further you may also try to write a compiler instead of an interpreter. The first step is the same, but instead of evaluating the nodes of the tree, you'll have to output some kind of machine code that will do the job afterwards.
Real hardware assembly can be difficult, but JVM bytecode is pretty simple and has a decent performance. There are libraries that can handle the binary aspect of it for you. For example ASM : http://asm.ow2.org/ This is how JVM languages work in general.

Good luck !


答:
Usually, you want to keep your syntax at a minimum and instead allow such constructs to be defined in the language itself.

For example, in Haskell you can convert any function with two or more arguments into an infix operator using backticks. This allows you to write:

```<code>if a `elem` [b, c] then ... else ...
</code>```

where elem is just a normal function taking two arguments - a value and a list of values - and checks whether the first is an element of the second.

What if you want to use and instead of or? In Haskell, you can just use the following instead of waiting for the compiler vendor to implement a new feature:

```<code> if all (== a) [b, c] then ... else ...
</code>```

Body:
Usually, you want to keep your syntax at a minimum and instead allow such constructs to be defined in the language itself.

For example, in Haskell you can convert any function with two or more arguments into an infix operator using backticks. This allows you to write:

if a `elem` [b, c] then ... else ...

where elem is just a normal function taking two arguments - a value and a list of values - and checks whether the first is an element of the second.

What if you want to use and instead of or? In Haskell, you can just use the following instead of waiting for the compiler vendor to implement a new feature:

 if all (== a) [b, c] then ... else ...


问:
How to enforce implementation of interface to behave a certain way
Suppose you had the following interface

```<code>public interface IUserRepository
{
    User GetByID(int userID);
}
</code>```

How would you enforce implementers of this interface to throw an exception if a user is not found?

I suspect it's not possible to do with code alone, so how would you enforce implementers to implement the intended behavior?  Be it through code, documentation, etc.?

In this example, the concrete implementation is expected to throw a UserNotFoundException

```<code>public class SomeClass
{
    private readonly IUserRepository _userRepository;

    public SomeClass(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public void DisplayUser()
    {
        try
        {
            var user = _userRepository.GetByID(5);
            MessageBox.Show("Hello " + user.Name);
        }
        catch (UserNotFoundException)
        {
            MessageBox.Show("User not found");
        }
    }
}
</code>```

答:
This is a language feature that was intentionally omitted from C#.  Quite simply, it's entirely possible for an IUserRepository.GetByID to fail for some other reason entirely than the user not being found, so you don't want to require a specific error when such cannot happen.  You have two options if for whatever reason you want to enforce this behavior:

Define the User class so that it itself throws the exception if it's improperly initalized.

Write unit tests for IUserRepository that explicitly test for this behavior.

Note that neither of those options is "include it in the documentation."  Ideally, you should do that anyway, especially as documentation is where you can explain why you want to enforce a particular error type.


答:
You can't. That's the thing about interfaces - they allow anyone to implement them at any time. There's an infinite number of potential implementations for your interface, and you can't force any of them to be correct. By choosing an interface, you've forfeited your right to enforce that a particular implementation be used all throughout the system. Heck, what you have isn't even an interface, it's a function. You're writing code that passes functions around.

If you need to go this route then you'll simply have to clearly document the specification that implementations must conform to and trust that no one will deliberately break that specification.

The alternative is to have an abstract data type, which translates into a class in Java/C#-like languages. The problem is that mainstream languages have weak support for ADTs and you can't switch the implementation of the class without file system tomfoolery. But if you've willing to live with that, you can ensure that there's only one implementation in the system. That's a step up from interfaces, where your code may break at any time, and when it does you'll have to figure out which implementation of the interface broke your code and where it came from.

EDIT: Note that even IL hacks won't allow you to ensure the correctness of certain aspects of an implementation. For example, it's implicitly assumed that GetByID must either return a value or throw an exception. Someone could write an implementation that simply goes into an endless loop and does neither. You can't prove during runtime that the code loops forever - if you manage to do this, you've solved the Halting Problem. You might be able to detect trivial cases (e.g. recognize a while (true) {}) but not an arbitrary piece of code.

Title: How to enforce implementation of interface to behave a certain way

Body:
Suppose you had the following interface

```<code>public interface IUserRepository
{
    User GetByID(int userID);
}
</code>```

How would you enforce implementers of this interface to throw an exception if a user is not found?

I suspect it's not possible to do with code alone, so how would you enforce implementers to implement the intended behavior?  Be it through code, documentation, etc.?

In this example, the concrete implementation is expected to throw a UserNotFoundException

```<code>public class SomeClass
{
    private readonly IUserRepository _userRepository;

    public SomeClass(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public void DisplayUser()
    {
        try
        {
            var user = _userRepository.GetByID(5);
            MessageBox.Show("Hello " + user.Name);
        }
        catch (UserNotFoundException)
        {
            MessageBox.Show("User not found");
        }
    }
}
</code>```


答:
If you work together with the developers that you want to implement the exception-throwing behaviour, then you could possibly write unittests (for them) to check if an exception is thrown if you try to get a user who does not exist.

You therefore need to know which methods to test. I'm not familiar with C# but you could maybe use reflection to search for all classes implementing the IUserRepository and test them automatically so even if a developer adds another class it will be tested when the tests are run.

But that is only what you could do in practice if you really suffer from developers doing the implementations wrong you have to work with. In theory interfaces are not for defining how the business logics has to be implemented.

I'm looking forward for other answers as this is really an interesting question!


问:
How and when should I design a simple mark-up language parser?
I want to write a simple markup language with its rendering engine.

First, I am not completely sure when I should try this... I am only 12... But I am competent in C++ having learned through the Web and books.

I am also good with JavaScript, PHP and HTML. I am currently learning Ruby and Haskell for a change.

I understand all low-level and high-level concepts. But the only thing that had always confused me is how people design these parsers to understand and compile or interpret things like markup languages and programming languages.

My question is when should I start writing a simple rendering engine for an even simpler markup language?

More like the custom xml-like custom languages frameworks use for their interface (Qt uses a .ui file that is similar to XML to define their forms).

Am I up to design something like that? Any good papers, articles or books to read?

Preferred Languages: C++, JavaScript, Haskell, Ruby

答:
For your specific circumstance, I'd just go ahead and try to write a parser if you have the spare time. I'd advise starting with XML-based parsers, as these are the simplest (as the syntax tree is already neatly written for you in the XML file).

For the more general question of when it's valid to write a parser, I'd argue that the following must be true:

The inputs to the parser change often, and it would take longer to make the changes to the hardcoded equivalent parser outputs than it would to change the parser inputs

The parser tackles a finite, well-understood problem domain, which changes both rarely and gives notice of changes

The total time it would take to write the the hardcoded equivalents to all the parsers outputs from all its input files is greater than the amount of time it will take to write the parser itself

The language dealt with by the parser is simpler or more convenient for its end-user than the language the equivalent hardcoded output would be written in

This may seem a tad opinion-based and complex, but my reasoning is essentially that a parser takes a very long time to write well. In order for the parser to pay off its debt (in terms of time taken to write it), it must be dealing with a problem domain where the alternative to the parser would be to write a lot of code to deal with each potential input to the parser. So let's run through the above beliefs with the example of HTML and HTML parsers:

HTML pages do indeed change often, and it would take longer to change the visual tree as written in C++ than it does to change the visual tree as written in HTML. To change the location of a div in HTML, or to change its style, one can simply cut-and-paste the existing div somewhere else in the tree, and one can simply apply a new css class. Doing the equivalent in C++ would be a lot harder, because it wouldn't be anywhere near as easy as just cutting and pasting the same code to some other part of the C++ file.

The HTML specification is finite and well understood. It's well known when the specification will change, because W3C convenes many meetings prior to each change. This means that the writers of HTML parsers know when it's about to change, so they can be prepared for changes and don't waste large amounts of time anticipating changes in the problem domain. The fact the problem domain is well understood and finite also gives parser-writers a good basis from which to say that their parser is complete i.e. an HTML parser is complete when it handles all of the known HTML elements that it will read. Imagine attempting to write a parser for something that changes constantly, and is vaguely defined; how would you ever know your parser was complete?

Similarly to point 1, imagine attempting to write a web page as a set of C++ instructions. Coming up with a consistent way of handling the layouts of elements on the screen would take longer than writing a simple div! Additionally, given the fact that there's ~2.51 billion web pages, imagine the loss of time of writing each web page in its own C++ files, with its own frameworks. If a parser saves huge amounts of time over the alternative choice, and the parser will be used often, then it's a good sign that the parser may be a net positive.

Again, if web pages were written in C++ then the pool of people capable of writing them would be severely diminished. Not to be snobby, but I think we can all agree C++, with its numerous complex pitfalls and segfaults, is a lot harder than HTML. If only inveterate C++ developers could write web pages, then I'd hazard a guess that we sure as heck wouldn't have ~2.51 billion web pages.

As a bit of personal anecdata, my company has written a parser for a client which takes XML and uses that XML to read and write data to and from SQL stored procedures into spreadsheets. The client is able to understand something like:

```<code><Workbook name="SomeWorkbook">
    <Sheet name="SomeWorksheet">
        <DataCell range="A1" name="employee" input="SPGetEmployees" />
        <DataCell range="A2" name="salary" input="SPGetEmployees" />
        <DataCell range="B3" name="total" input="SPGetEmployees" />
        <DataCell range="B4" name"isApproved" output="SPApproveWorksheet" />
    </Sheet>
    <DataSources>
        <DataSource direction="input" type="SP" database="someDatabase" name="SPGetEmployees">
            <Parameters>
                <Parameter name="financialYear" type="DateTime" isDataCell="false" />
            </Parameters>
        </DataSource>
        <DataSource direction="output" type="SP" database="someDatabase" name="SPApproveWorksheet">
            <Parameters>
                <Parameter name="isApproved" type="Bit" isDataCell="true" />
            </Parameters>
        </DataSource>
    </DataSources>
</Workbook>
</code>```

because it all looks familiar to them in their job role (semi-technical systems administrators), but the client definitely wouldn't understand the C# code that would otherwise generate this workbook. Their data sources for their worksheets change often, too, and it's quicker to change some XML than it is to change a lot of C# code. The problem domain is also well understood, because we're just reading and writing from some well-understood data sources to some well-understood outputs (Excel files), so we can write an XML-based language which provides for all the client's needs and doesn't have to be changed very often.

I'll leave you with this final caution from xkcd on the topic of optimizations such as parsers: http://xkcd.com/1205/

Body:
For your specific circumstance, I'd just go ahead and try to write a parser if you have the spare time. I'd advise starting with XML-based parsers, as these are the simplest (as the syntax tree is already neatly written for you in the XML file).

For the more general question of when it's valid to write a parser, I'd argue that the following must be true:

The inputs to the parser change often, and it would take longer to make the changes to the hardcoded equivalent parser outputs than it would to change the parser inputs

The parser tackles a finite, well-understood problem domain, which changes both rarely and gives notice of changes

The total time it would take to write the the hardcoded equivalents to all the parsers outputs from all its input files is greater than the amount of time it will take to write the parser itself

The language dealt with by the parser is simpler or more convenient for its end-user than the language the equivalent hardcoded output would be written in

This may seem a tad opinion-based and complex, but my reasoning is essentially that a parser takes a very long time to write well. In order for the parser to pay off its debt (in terms of time taken to write it), it must be dealing with a problem domain where the alternative to the parser would be to write a lot of code to deal with each potential input to the parser. So let's run through the above beliefs with the example of HTML and HTML parsers:

HTML pages do indeed change often, and it would take longer to change the visual tree as written in C++ than it does to change the visual tree as written in HTML. To change the location of a div in HTML, or to change its style, one can simply cut-and-paste the existing div somewhere else in the tree, and one can simply apply a new css class. Doing the equivalent in C++ would be a lot harder, because it wouldn't be anywhere near as easy as just cutting and pasting the same code to some other part of the C++ file.

The HTML specification is finite and well understood. It's well known when the specification will change, because W3C convenes many meetings prior to each change. This means that the writers of HTML parsers know when it's about to change, so they can be prepared for changes and don't waste large amounts of time anticipating changes in the problem domain. The fact the problem domain is well understood and finite also gives parser-writers a good basis from which to say that their parser is complete i.e. an HTML parser is complete when it handles all of the known HTML elements that it will read. Imagine attempting to write a parser for something that changes constantly, and is vaguely defined; how would you ever know your parser was complete?

Similarly to point 1, imagine attempting to write a web page as a set of C++ instructions. Coming up with a consistent way of handling the layouts of elements on the screen would take longer than writing a simple div! Additionally, given the fact that there's ~2.51 billion web pages, imagine the loss of time of writing each web page in its own C++ files, with its own frameworks. If a parser saves huge amounts of time over the alternative choice, and the parser will be used often, then it's a good sign that the parser may be a net positive.

Again, if web pages were written in C++ then the pool of people capable of writing them would be severely diminished. Not to be snobby, but I think we can all agree C++, with its numerous complex pitfalls and segfaults, is a lot harder than HTML. If only inveterate C++ developers could write web pages, then I'd hazard a guess that we sure as heck wouldn't have ~2.51 billion web pages.

As a bit of personal anecdata, my company has written a parser for a client which takes XML and uses that XML to read and write data to and from SQL stored procedures into spreadsheets. The client is able to understand something like:

<Workbook name="SomeWorkbook">
    <Sheet name="SomeWorksheet">
        <DataCell range="A1" name="employee" input="SPGetEmployees" />
        <DataCell range="A2" name="salary" input="SPGetEmployees" />
        <DataCell range="B3" name="total" input="SPGetEmployees" />
        <DataCell range="B4" name"isApproved" output="SPApproveWorksheet" />
    </Sheet>
    <DataSources>
        <DataSource direction="input" type="SP" database="someDatabase" name="SPGetEmployees">
            <Parameters>
                <Parameter name="financialYear" type="DateTime" isDataCell="false" />
            </Parameters>
        </DataSource>
        <DataSource direction="output" type="SP" database="someDatabase" name="SPApproveWorksheet">
            <Parameters>
                <Parameter name="isApproved" type="Bit" isDataCell="true" />
            </Parameters>
        </DataSource>
    </DataSources>
</Workbook>

because it all looks familiar to them in their job role (semi-technical systems administrators), but the client definitely wouldn't understand the C# code that would otherwise generate this workbook. Their data sources for their worksheets change often, too, and it's quicker to change some XML than it is to change a lot of C# code. The problem domain is also well understood, because we're just reading and writing from some well-understood data sources to some well-understood outputs (Excel files), so we can write an XML-based language which provides for all the client's needs and doesn't have to be changed very often.

I'll leave you with this final caution from xkcd on the topic of optimizations such as parsers: http://xkcd.com/1205/


问:
As an interviewer, asking a candidate to find errors in small sample code. Is this fair?
We've been interviewing on and off for about two years, and I've run this by about 30 candidates. I wrote some 20 lines of code which perform a relatively basic operation, but has a bunch of errors in it. None of them are syntax errors. Errors range from bad memory management, incorrect data types, multithreading problems, misuse of keywords, and a couple functional errors that would give undesired output.

People get really nervous during this question. Is it a fair question to be asking? The goal is to get an idea of their comfort level with the language (Objective C has some very strange behaviors, and most applicants we get are relatively inexperienced in ObjC specifically as compared to other languages), as well as see their ability to recognize logical problems in otherwise foreign code.

Once a candidate has made a first pass, I often will point to specific lines that have remaining errors on them and see how much hand-holding it takes to get a correct identification and/or fix from them.

At our company, this is a real world scenario, as programmers would be thrust straight into a 100k line app and given bugs to fix, and we need people that are comfortable with working with the code of 6 other programmers.

However, today, another of our interviewers told me he hated this problem (I didn't quite understand what his reason was, admittedly). Is this something I should continue asking, or should I look for alternate avenues?

答:
This is perfectly fair. Reading code is inherently easier than writing code, so checking if they can do the most basic of professional tasks is a pretty important part of an interview. For junior candidates it may be tough to expect them to debug something on paper, as they're likely reliant on debuggers still. If you could have the broken program on a computer, that might be better.

I don't buy the whole "pressure situation is unfair" argument either. Clients and/or bosses will inevitably be breathing down your candidate's throat when some critical issue is found. How they work under pressure is part of evaluating how they'll do at the job.

All that said, some good people won't do well at this sort of thing. They're not critical, or they are more deliberate (or collaborative), or they're simply inexperienced with your particular problem (simple or not).

That doesn't make it less fair - you just need to be sure to account for other things as well.


答:
C, C++

I don't like C/C++, because though C++ is technically a superset of C, to do it right, you have to do things differently. C/C++ makes you look like someone who knows C and knows that a C++-compiler accepts C, too.

Title: Languages on a resume: Is it better to put "C/C++" or "C, C++"?

Body:
I'm graduating in a couple of weeks, and my resume (as expected) lists the languages that I've had experience with. Previously I've put "C/C++", however back then I didn't have that much experience with these two languages as I do now.

Now that I've formally learned these two languages, it has become evident to me (and anyone who really knows these languages) that they are similar, and completely disimilar at the same time. Sure, most C code is compilable C++ code, but syntax and incorporation of library functions is pretty much where these similarities end. In most non-trivial problems, chances are that the desirable C++ solution will be different from the desirable C solution.

My question:

Will recruiters take note or care about whether you put "C/C++" as opposed to "C, C++"? Will they assume a lack of knowledge of the workings of either because of the inclusion of the first form, or perhaps see the inclusion of the second form as a potential "resume beefer" (listing them as 2 languages, instead of "one")?

Furthermore, for jobs that you've applied to that were particularly interested in these two langauges, did the interview process include questions about the differences between C programming and C++ programming (so, about actual programming techniques, not only the extra paradigms in the latter)?


答:
There is no way to require an implementation to throw an exception through an interface, even in languages like Java where you can declare that a method could throw an exception.

There may be a way to ensure (to some degree but not absolutely) that an exception is thrown. You can create an abstract implementation of your interface. You can then implement the GetUser method as final in the abstract class, and use the strategy pattern to call another, protected member of the subclass and throw an exception if it returns anything other than a valid user (like null). This can still fall down if, say, the other developer returns a null object type User, but they would really have to work to subvert the intent here. They could also just reimplement your interface, also bad, so you may consider replacing the interface entirely with the abstract class.

(Similar results can be achieved using delegation instead of subclassing with something like a wrapping decorator.)

Another option could be to create a conformance test suite that all implementing code must pass to be included. How effective this is depends on how much control you have over the other code's linking into yours.

I also agree with others that clear documentation and communication are a given when a requirement like this is expected but cannot be completely enforced in code.

Code examples:

Subclass method:

```<code>public abstract class ExceptionalUserRepository : IUserRepository
{
    public sealed User GetUser(int user_id)
    {
        User u = FindUserByID(user_id);
        if(u == null)
        {
            throw new UserNotFoundException();
        }
        return u;
    }

    // subclasses implement this method instead
    protected abstract User FindUserByID(int user_id);
    // More code here
}
</code>```

Decorator method:

```<code>public sealed class DecoratedUserRepository : IUserRepository
{
    private readonly IUserRepository _userRepository;

    public DecoratedUserRepository(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public User GetUser(int user_id)
    {
        User u = _userRepository.GetUser(user_id);
        if(u == null)
        {
            throw new UserNotFoundException();
        }
        return u;
    }

    // More code here
}

public class SomeClass
{
    private readonly IUserRepository _userRepository;

    // They now *have* to pass in exactly what you want
    public SomeClass(DecoratedUserRepository userRepository)
    {
        _userRepository = userRepository;
    }
    // More code
}
</code>```

A last quick point I want to make that I forgot before is that by doing any of these, you are tying yourself to a more specific implementation, meaning implementing developers get that much less freedom.

Body:
There is no way to require an implementation to throw an exception through an interface, even in languages like Java where you can declare that a method could throw an exception.

There may be a way to ensure (to some degree but not absolutely) that an exception is thrown. You can create an abstract implementation of your interface. You can then implement the GetUser method as final in the abstract class, and use the strategy pattern to call another, protected member of the subclass and throw an exception if it returns anything other than a valid user (like null). This can still fall down if, say, the other developer returns a null object type User, but they would really have to work to subvert the intent here. They could also just reimplement your interface, also bad, so you may consider replacing the interface entirely with the abstract class.

(Similar results can be achieved using delegation instead of subclassing with something like a wrapping decorator.)

Another option could be to create a conformance test suite that all implementing code must pass to be included. How effective this is depends on how much control you have over the other code's linking into yours.

I also agree with others that clear documentation and communication are a given when a requirement like this is expected but cannot be completely enforced in code.

Code examples:

Subclass method:

public abstract class ExceptionalUserRepository : IUserRepository
{
    public sealed User GetUser(int user_id)
    {
        User u = FindUserByID(user_id);
        if(u == null)
        {
            throw new UserNotFoundException();
        }
        return u;
    }

    // subclasses implement this method instead
    protected abstract User FindUserByID(int user_id);
    // More code here
}

Decorator method:

public sealed class DecoratedUserRepository : IUserRepository
{
    private readonly IUserRepository _userRepository;

    public DecoratedUserRepository(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public User GetUser(int user_id)
    {
        User u = _userRepository.GetUser(user_id);
        if(u == null)
        {
            throw new UserNotFoundException();
        }
        return u;
    }

    // More code here
}

public class SomeClass
{
    private readonly IUserRepository _userRepository;

    // They now *have* to pass in exactly what you want
    public SomeClass(DecoratedUserRepository userRepository)
    {
        _userRepository = userRepository;
    }
    // More code
}

A last quick point I want to make that I forgot before is that by doing any of these, you are tying yourself to a more specific implementation, meaning implementing developers get that much less freedom.


答:
Some languages do offer this -- to an extent.

Maybe not as your specific example, but take for example a Python line:

```<code>def minmax(min, max):
    def answer(value):
        return max > value > min
    return answer

inbounds = minmax(5, 15)
inbounds(7) ##returns True
inbounds(3) ##returns False
inbounds(18) ##returns False
</code>```

So, some languages are fine with multiple comparisons, as long as you're expressing it correctly.

Unfortunately, it doesn't work quite like you'd expect it to for comparisons.

```<code>>>> def foo(a, b):
...     def answer(value):
...         return value == a or b
...     return answer
...
>>> tester = foo(2, 4)
>>> tester(3)
4
>>> tester(2)
True
>>> tester(4)
4
>>>
</code>```

"What do you mean it returns either True or 4?" -- the hire after you

One solution in this case, at least with Python, is to use it slightly differently:

```<code>>>> def bar(a, b):
...     def ans(val):
...             return val == a or val == b
...     return ans
...
>>> this = bar(4, 10)
>>> this(5)
False
>>> this(4)
True
>>> this(10)
True
>>> this(9)
False
>>>
</code>```

EDIT: The following would also do something similar, again in Python...

```<code>>>> def bar(a, b):
...     def answer(val):
...             return val in (a, b)
...     return answer
...
>>> this = bar(3, 5)
>>> this(3)
True
>>> this(4)
False
>>> this(5)
True
>>>
</code>```

So, whichever language you're using, it may not be that you cannot do it, just that you must first take a closer look at how the logic actually works. Typically it's just a matter of knowing what you're 'actually asking' the language to tell you.

Body:
Some languages do offer this -- to an extent.

Maybe not as your specific example, but take for example a Python line:

def minmax(min, max):
    def answer(value):
        return max > value > min
    return answer

inbounds = minmax(5, 15)
inbounds(7) ##returns True
inbounds(3) ##returns False
inbounds(18) ##returns False

So, some languages are fine with multiple comparisons, as long as you're expressing it correctly.

Unfortunately, it doesn't work quite like you'd expect it to for comparisons.

>>> def foo(a, b):
...     def answer(value):
...         return value == a or b
...     return answer
...
>>> tester = foo(2, 4)
>>> tester(3)
4
>>> tester(2)
True
>>> tester(4)
4
>>>

"What do you mean it returns either True or 4?" -- the hire after you

One solution in this case, at least with Python, is to use it slightly differently:

>>> def bar(a, b):
...     def ans(val):
...             return val == a or val == b
...     return ans
...
>>> this = bar(4, 10)
>>> this(5)
False
>>> this(4)
True
>>> this(10)
True
>>> this(9)
False
>>>

EDIT: The following would also do something similar, again in Python...

>>> def bar(a, b):
...     def answer(val):
...             return val in (a, b)
...     return answer
...
>>> this = bar(3, 5)
>>> this(3)
True
>>> this(4)
False
>>> this(5)
True
>>>

So, whichever language you're using, it may not be that you cannot do it, just that you must first take a closer look at how the logic actually works. Typically it's just a matter of knowing what you're 'actually asking' the language to tell you.


问:
Classes shouldn't call other classes?
I've just finished reading The Art of Unit Testing, by Roy Osherove.  It was an interesting book, but I'm having trouble with something he mentions near the end (section 11.2.2):

Identifying "roles" in the application and abstracting them under interfaces is an
  important part of the design process. An abstract class shouldn’t call concrete classes,
  and concrete classes shouldn’t call concrete classes either, unless they’re data objects
  (objects holding data, with no behavior). This allows you to have multiple seams in
  the application where you could intervene and provide your own implementation.

Specifically, I don't understand what he means when he says that concrete classes shouldn't call concrete classes.  Consider the following examples in C#:

```<code>double roundedAge = Math.Floor(exactAge);
</code>```

Is this not considered a call to a class because Math.Floor is a static method?  Or is Osherove saying that the line of code above is bad design?  Another example:

```<code>using (StreamReader reader = new StreamReader(path))
{
    // do things
}
</code>```

Is this bad design due to the use of a StreamReader?  Or is this instance of StreamReader simply an object that holds data, as described in the quote above?

Rather than starting a discussion on whether or not it's bad practice to have classes call other classes, my goal here is to try and better understand what Osherove means in the passage I've quoted.  Does he really mean that the code in the two examples above should be avoided?  Thanks in advance for any replies.

EDIT: Below is an illustration from the book which is possibly elucidating.

答:
The first example does not apply since it is essentially an arithmetic expression. You seldom write unit tests for arithmetic operations; when you do, your approach would be quite different.

In the second example, your code is using the concrete class. This means that the code inside the curly braces is harder to test since you are binding the StreamReader at compile time. What the author is describing is to defer the binding of reader as late as possible. When you do that, it becomes possible to test the use of reader with less pain.

That being said, many of the code mocking tools do a sufficiently good job to allow substitution of the mocked item for the real thing. This is the intent of the prescription: keep as many useful "seams" as you can in your code, because you do all of your testing at the seams.

Title: Classes shouldn't call other classes?


答:
You never said what Clamp() is supposed to do, so I'm assuming that it returns value, unless it is outside of the range, in which case it returns one of the two bounds.

I don't see any reason to think that -1, 0, or 1 are corner cases.  They may often be corner cases, but there's no reason they'd act strangely in this function.  If you want a 'normal' value, 42 or -63 works, but there is no need for both of them, unless you suspect that > and < don't work properly on negative numbers in C#.  (I don't think you need to worry about that.)

So we could just use −2147483648, 'a normal value', and 2147483647.  (We could even say that testing with the max/min integer values aren't really necessary.  Presumably, C# > and < work up to the minimum and maximum; there isn't any danger of integer overflow.)

There are 6 permutations of 3 values, so we're down to 6 testcases.  6 testcases is not much, and we can easily just write them down and use them, but we don't know for certain that we've selected test cases that cover everything (all we've done so far is reduce the original set of test cases to something smaller).

If we want to be sure we've caught all the cases that matter, we could reduce the massively large set of input values (4 billion cubed) by partitioning them into equivalence classes.  Then we only need 1 test per equivalence class, since the equivalence class would be defined as a set of inputs that all act alike.

The value of Clamp(a, b, c) depends on whether a is in the range, or above it, or below it.  There should be 3 equivalence classes: [a < b and a < c], [a > b and a > c], and otherwise.  The return value will be b, c, or a, respectively.  This tells us not only what the tests should be, but how to write the code.

(There is one little thing that we haven't run into: what if the lower bounds is higher than the upper bounds.  What I said in the previous paragraph applies if the assumption I made up at the top is right, but not if it isn't.  It can be fixed easily, though, by swapping b and c or by returning Clamp(a, c, b) if b > c.)

Title: How to pick the testing values for parameterized tests for stateless functions?

Body:
When writing (parameterized) tests for stateless functions, how do I determine the most ideal set of values to test with?

I'm writing a class with mathematical functions in C#, and I want to write unit tests for them. Today I want to write this function (really!):

```<code>int Clamp(int value, int lowerBound, int upperBound)
{
    // TODO: Implement.
    return 0;
}
</code>```

As good TDD practice dictates, I'm writing the unit tests first and the implementation later. I can write a parameterized test for this stateless function, but have to decide on the best set of values to test with.

My current strategy for picking testing values is:

For each parameter, I can pick values from the whole set of 32-bit signed integers. I'm not using randomly generated values as that would make the test non-repeatable. To test the corner cases, I pick -1, 0, 1, but also the −2147483648 (minimum 32-bit signed integer) and 2147483647 (maximum 32-bit signed integer). I would also need to pick a 'normal' value, for example, 42, to make sure I'm not only testing corner cases. Is one normal value enough? And a negative one, let's say -63. Did I miss any?

```<code>−2147483648, -63, -1, 0, 1, 42, 2147483647
</code>```

If any of the three parameters can have any of just these seven values, I'll end up with 343 tests for one function! Before I'm going to write 343 tests, I really have to ask:

Are these the right values to test with? In general, what strategy can I use to pick the most effective values to use?


答:
I would usually write C/C++ as a habit, but:

some pedantic recruiter might think you wrongly assume they are the same (unlikely...I hope),

there's a higher likelihood that C, C++ gets parsed to the elements C and C++ than C/C++... which might matter when recruiters try to match your profile to requirements for a role.

So try to have maybe C/C++ in your general description and then C and C++ separated elsewhere.

That's only an advice, I have no strong proof to follow that, but (many) recruitment agencies have a fairly keyword-oriented approach.

Once you're past the recruiting agency, the real recruiter in your target company will (hopefully, if not filtered by non-technical HR people) know that you don't necessarily imply that C and C++ are in the same basket, so I really think of it only as a parsing problem.

The same applies to variants of Java and its platforms and specifications, which even had the bad taste of changing naming conventions over time to end up with: Java SE, JavaSE, JSE, J2SE, Java EE, JavaEE, JEE, J2EE, etc...


问:
Is it correct to ask contributers to rebase their pull requests on github
I maintain a relatively popular github repo.

When a pull request is good to merge I usually ask the author to rebase it to a single commit before I merge it (especially when there have been multiple small edits).

Is this good git practice?
Is this acceptable/standard GitHub etiquette?

So some benefits:

I get a nice clean commit history in the commit logs

I don't need to alter the commit myself

It delegates some of the work

Some possible drawbacks:

I'm not sure if this is good etiquette

I'm not sure if this is a good git practice

I've usually already asked for a few other changes - this is one more and I don't want to discourage contributors.

答:
As far as Git is concerned, it's something of a holy war whether you should simply merge branches or rebase commits on the latest version of the branch you are merging into. There's plenty of conversations about which is better if you do a quick search on Programmers.SE.

As to the etiquette behind it, lets deal with this from a practical perspective. When dealing with new code coming from someone else it's always best to get them to either merge the latest changes from the branch or freshly rebase it before merging to ensure a clean merge. Remember, they wrote the code so they are usually by far the most qualified to deal with any merge/rebase conflicts. I personally don't see a problem with it, and see this request all the time from other people. For me, if there's no conflicts then I'll often just do it myself since it's a two second update that git can apply itself. But if there's conflicts then I will always ask the original author of the code to deal with it themselves.

Also, for GitHub (at the minimum) specifically, they will display a link to your CONTRIBUTING file above any PR attempts so that makes a good place to outline your expectations and many projects do include that they will only merge up to date branches.