问:
Google is good or bad for programmer?
Recently I was being interviewed by a company and faced one question. The interviewer asked me a question and at that time I didn't know the answer but if I had been asked about just 4 months ago, I could have answered it.

The question was from new language that I learned just 4 months ago. But I just get overview of the language and just get started working on that. Whenever I face difficultly, I google it. That means we do not have to memorize the whole programming language book! So in that situation I felt that Google screwed my job!

Not talking subjectively, Is it good to google all the time?

答:
It depends. If you only worked in a language for 4 months, it's not necessarily unreasonable to need to google certain things, depending on how much time you spent on the language and how experienced a developer you are. With experience, you start picking up new languages faster. In your specific situation, it's hard to say if the interviewer was too picky without knowing the question you were asked.

In general, though, it's definitely okay to look up information online if you're stuck, but don't use the ability to do that as an excuse to stop learning and remembering important aspects of whatever language you're working in.

Title: Google is good or bad for programmer?


问:
When I test out the difference in time between shifting and multiplying in C, there is no difference. Why?
I have been taught that shifting in binary is much more efficient than multiplying by 2^k. So I wanted to experiment, and I used the following code to test this out:

```<code>#include <time.h>
#include <stdio.h>

int main() {
    clock_t launch = clock();
    int test = 0x01;
    int runs;

    //simple loop that oscillates between int 1 and int 2
    for (runs = 0; runs < 100000000; runs++) {

    // I first compiled + ran it a few times with this:
    test *= 2;

    // then I recompiled + ran it a few times with:
    test <<= 1;

    // set back to 1 each time
    test >>= 1;
    }

    clock_t done = clock();
    double diff = (done - launch);
    printf("%f\n",diff);
}
</code>```

For both versions, the print out was approximately 440000, give or take 10000. There was no (visually, at least) significant difference between the two versions' outputs. So my question is, is there something wrong with my methodology? Should there even be a visual difference? Does this have something to do with the architecture of my computer, the compiler, or something else?

答:
Multiplication is a combination of shifts and additions.

In the case you've mentioned, I don't believe it matters whether the compiler optimises it or not - "multiply x by two" can be implemented as either:

Shift bits of x one place to the left.

Add x to x.

These are each basic atomic operations; one isn't faster than the other.

Change it to "multiply x by four", (or any 2^k, k>1) and it's a little different:

Shift bits of x two places to the left.

Add x to x and call it y, add y to y.

On a basic architecture, it's simple to see that the shift is more efficient - taking one vs. two operations, since we cannot add y to y until we know what y is.

Try the latter (or any 2^k, k>1), with appropriate options to prevent your from optimising them to be the same thing in implementation. You should find the shift is faster, taking O(1) compared to the repeated addition in O(k).

Obviously, where the multiplicand is not a power of two, a combination of shifts and additions (one where the number of each is non-zero)  is necessary.

ContentLicense: CC BY-SA 3.0


问:
Should I group all of my .js files into one large bundle?
One of the difficulties I'm running into with my current project is that the previous developer spaghetti'd the javascript code in lots of different files.  We have modal dialogs that are reused in different places and I find that the same .js file is often loaded twice.

My thinking is that I'd like to just load all of the .js files in _Layout.cshtml, and that way I know it's loaded once and only once.  Also, the client should only have to download this file once as well.  It should be cached and therefore shouldn't really be a performance hit, except for the first page load.

I should probably note that I am using ASP.Net bundling as well and loading most of the jQuery/bootstrap/etc from CDN's.

Is there anything else that I'm not thinking of that would cause problems here?  Should I bundle everything into a single file?

答:
Depending on the size of the application, it might be worthwhile to modify your app to use modules with an AMD loader, such as RequireJS.

By moving your code into separate modules and letting an AMD loader manage the dependencies, your code should become more organized and prevent the issue of you having to manually load files. You can use this for files that are hosted on your server, as well as files being served from a CDN.

Also, here's an article explaining how to use RequireJS with an ASP.NET app:

Using Require.js in an ASP.NET MVC application


问:
"Proceed if true" vs "stop if false" in if statements
While I was writing a private helper method in Java, I needed to add a check for a precondition that would cause the method to do nothing if not met. The last few lines of the method were just off the bottom of the editing area in the IDE, so in an epic display of laziness, I wrote the check like this:

```<code>function(){
    if (precondition == false){
        return;
    }
    //Do stuff
}
</code>```

as to opposed finding the end of the block to write a more "traditional" statement like this:

```<code>function(){
    if (precondition == true){
        //Do stuff
    }
}
</code>```

This made me wonder: is there a reason to avoid my version in favor of the other, or is it just a stylistic difference? (Assuming they are used in such a way that they are meant to be functionally equivalent)

答:
Those are called Guard Clauses.  They're actually desirable.  They are one of several techniques that can be used to decompose complex nested if conditions into simpler (and easier to follow) logic.

As an example, this code:

```<code>public Foo merge (Foo a, Foo b) {
    if (a == null) return b;
    if (b == null) return a;
    // complicated merge code goes here.
  }
</code>```

Replaces the more complicated, but having a single exit point:

```<code>public Foo merge (Foo a, Foo b) {
    Foo result;
    if (a != null) {
      if (b != null) {
        // complicated merge code goes here.
      } else {
        result = a;
      }
    } else {
      result = b;
    }
    return result;
  }
</code>```

http://c2.com/cgi/wiki?GuardClause

Body:
Those are called Guard Clauses.  They're actually desirable.  They are one of several techniques that can be used to decompose complex nested if conditions into simpler (and easier to follow) logic.

As an example, this code:

public Foo merge (Foo a, Foo b) {
    if (a == null) return b;
    if (b == null) return a;
    // complicated merge code goes here.
  }

Replaces the more complicated, but having a single exit point:

public Foo merge (Foo a, Foo b) {
    Foo result;
    if (a != null) {
      if (b != null) {
        // complicated merge code goes here.
      } else {
        result = a;
      }
    } else {
      result = b;
    }
    return result;
  }

http://c2.com/cgi/wiki?GuardClause


问:
Several enum classes that declare constants with the same names
I'm working on a Java library for sorts for Magic: the Gathering.  Well, without going into a lot of detail, in the game there are five different colors of magic: white, blue, black, red, and green.  That's easy enough, that's a textbook example of an enum.  However, there's a problem: there are several variations on these colors.  There are your standard variants, the "monocolored hybrid" variants, and the "Phyrexian" variants (don't ask).  So, my question is, which of these is a better approach?

Idea 1:

```<code>enum Symbol {
  WHITE,
  BLUE,
  BLACK,
  RED,
  GREEN,

  MONOCOLORED_HYBRID_WHITE,
  MONOCOLORED_HYBRID_BLUE,
...
  PHYREXIAN_WHTIE,
  PHYREXIAN_BLUE,
...
}
</code>```

Idea 2:

```<code>interface Symbol {
  method1()
  method2()
...
}
enum Primary implements Symbol {
  WHITE,
  BLUE,
...
}
enum MonocoloredHybrid implements Symbol {
  WHITE,
  BLUE,
...
}
enum Phyrexian implements Symbol { ...
</code>```

I've been using the first way for a while, but I've been starting to think the second way might be better.  It shows more clearly that these classes of symbols are different, yet still compatible, since they implement the same interface.  It will cause a little bit of boilerplate code (just a couple fields), but my main issue is I have three enum constants called WHITE.  Now, I'd always be referencing them by their class name, e.g., Primary.WHITE, but this still seems a little awkward. But perhaps it's better than the "Smurf naming" I'd have to do in the first technique.  (I also can't use them in EnumMap/ EnumSet in the second way, but I think I'm okay with that.)

So, which is the better approach?  Is it okay to have a bunch of enum classes all declaring constants with the same name?  Is there a third alternative that's even better?

答:
This can get confusing... and Magic The Gathering is one that loves to do exceptions to rules.  Trying to codify them can often be a challenge.

On the "MonoColored Hybrid" read this and this. And then this for Phyrexian mana.

However, this can boil down to something that is rather sensible.. and doesn't stick too much in a single enum or confuse the next person with an inheritance tree of enums.  Enums really 'want' to be simple things, so let them be so.  The simpler they are, the easier they are to use, and its a good thing to use enums.

A card has some cost.  The good old fashioned lighting bolt is just "R".  This is a List of some sort.  It could even be empty as in the case of 0 cost artifacts (unless you want to do null object).  But its a List.

Each element of the list is a SpellCost object.

A SpellCost would then be composed of:

An EnumMap of costs.  The Enum that backs the map would be:

```<code>enum Mana {
  WHITE,
  BLUE,
  BLACK,
  RED,
  GREEN,
  COLORLESS
}
</code>```

And then you would have the EnumMap be as a EnumMap<Mana, Integer>.  Something that was a "R/2" for "Red or two colorless" could then be specified in the EnumMap as: mana.put(Mana.RED,1); mana.put(Mana.COLORLESS,2);  This also handles cards that are described as "R/W G" (such as Naya Hushblade - because not all cards are monocolored hybrids).

The EnumMap and EnumSet are two of forgotten collections that are really nice once you realize what they are and do.  They give you type safe entries in a map and are backed by either a simple array or a bitfield.  The type safety on it can prevent a number of bugs associated with bitfields.  And the type safety on the map is something to think about whoever you've got a Map<String, Object> and wonder what happens when there's a typo in the String.

Phyrexian mana is then an attribute of the SpellCost.  Its a int (though you could do it as a boolean later and yell YAGNI in my general direction).  Currently the definition of the cost is "mana or two life" but I wouldn't count on that being the case forever and locking yourself into a boolean now... well.

So, you've got:

```<code>public class SpellCost {
    EnumMap<Mana, Integer> mana;
    int lifeCost;

    ...
}
</code>```

And then write the associated methods for it.  You might want to write a container for the cost itself rather than leaving it as a bare List so that you can have appropriate methods against it.

The key design points for this is that it keeps the enum simple as enums aught to be.  Any of the complexity of the business logic is kept within the SpellCost class (and possibly the container class too).

Body:
This can get confusing... and Magic The Gathering is one that loves to do exceptions to rules.  Trying to codify them can often be a challenge.

On the "MonoColored Hybrid" read this and this. And then this for Phyrexian mana.

However, this can boil down to something that is rather sensible.. and doesn't stick too much in a single enum or confuse the next person with an inheritance tree of enums.  Enums really 'want' to be simple things, so let them be so.  The simpler they are, the easier they are to use, and its a good thing to use enums.

A card has some cost.  The good old fashioned lighting bolt is just "R".  This is a List of some sort.  It could even be empty as in the case of 0 cost artifacts (unless you want to do null object).  But its a List.

Each element of the list is a SpellCost object.

A SpellCost would then be composed of:

An EnumMap of costs.  The Enum that backs the map would be:

enum Mana {
  WHITE,
  BLUE,
  BLACK,
  RED,
  GREEN,
  COLORLESS
}

And then you would have the EnumMap be as a EnumMap<Mana, Integer>.  Something that was a "R/2" for "Red or two colorless" could then be specified in the EnumMap as: mana.put(Mana.RED,1); mana.put(Mana.COLORLESS,2);  This also handles cards that are described as "R/W G" (such as Naya Hushblade - because not all cards are monocolored hybrids).

The EnumMap and EnumSet are two of forgotten collections that are really nice once you realize what they are and do.  They give you type safe entries in a map and are backed by either a simple array or a bitfield.  The type safety on it can prevent a number of bugs associated with bitfields.  And the type safety on the map is something to think about whoever you've got a Map<String, Object> and wonder what happens when there's a typo in the String.

Phyrexian mana is then an attribute of the SpellCost.  Its a int (though you could do it as a boolean later and yell YAGNI in my general direction).  Currently the definition of the cost is "mana or two life" but I wouldn't count on that being the case forever and locking yourself into a boolean now... well.

So, you've got:

public class SpellCost {
    EnumMap<Mana, Integer> mana;
    int lifeCost;

    ...
}

And then write the associated methods for it.  You might want to write a container for the cost itself rather than leaving it as a bare List so that you can have appropriate methods against it.

The key design points for this is that it keeps the enum simple as enums aught to be.  Any of the complexity of the business logic is kept within the SpellCost class (and possibly the container class too).


答:
If you test for precondition equal false or true in Java, that means the precondition is a boolean value, so just use it directly:

```<code>if (precondition) {

if (!precondition) {
</code>```

Skipping out of a function early is a nice way to keep code readable without a lot of nesting. But if you have a long list of preconditions, it might be hard to find the actual code, so it can be better to extract the real working code into an own method that gets called after the check succeeds:

```<code>void someFunction() {
    if (!precondition1) return;
    if (!precondition2) return;
    if (!precondition3) return;
    doStuff();
}

void doStuff() {
    //do stuff
}
</code>```

For smaller checks the positive version should be preferred as it is easier to read.

Title: "Proceed if true" vs "stop if false" in if statements

Body:
While I was writing a private helper method in Java, I needed to add a check for a precondition that would cause the method to do nothing if not met. The last few lines of the method were just off the bottom of the editing area in the IDE, so in an epic display of laziness, I wrote the check like this:

```<code>function(){
    if (precondition == false){
        return;
    }
    //Do stuff
}
</code>```

as to opposed finding the end of the block to write a more "traditional" statement like this:

```<code>function(){
    if (precondition == true){
        //Do stuff
    }
}
</code>```

This made me wonder: is there a reason to avoid my version in favor of the other, or is it just a stylistic difference? (Assuming they are used in such a way that they are meant to be functionally equivalent)

Body:
If you test for precondition equal false or true in Java, that means the precondition is a boolean value, so just use it directly:

if (precondition) {

if (!precondition) {

Skipping out of a function early is a nice way to keep code readable without a lot of nesting. But if you have a long list of preconditions, it might be hard to find the actual code, so it can be better to extract the real working code into an own method that gets called after the check succeeds:

void someFunction() {
    if (!precondition1) return;
    if (!precondition2) return;
    if (!precondition3) return;
    doStuff();
}

void doStuff() {
    //do stuff
}

For smaller checks the positive version should be preferred as it is easier to read.


答:
Well, ... human memory and instincts work faster than Google. But then again, we cannot commit everything to memory (human brain just doesn't work that way - you remember in the lower circles only the things you need momentarily).

Google however is great as a replacement for paper books, manuals, everything really. And makes searching those (like you would in the ol' days) a breeze. So yes, it is good.

But one must remember, it is just a tool - like any other. No good programmer relies on it to just pop up solutions, so he can go like that from day to day. After all, what's on Google has already been done - and understanding of matter leads to doing stuff that yet haven't.

ContentLicense: CC BY-SA 2.5

Title: Google is good or bad for programmer?

Body:
Recently I was being interviewed by a company and faced one question. The interviewer asked me a question and at that time I didn't know the answer but if I had been asked about just 4 months ago, I could have answered it.

The question was from new language that I learned just 4 months ago. But I just get overview of the language and just get started working on that. Whenever I face difficultly, I google it. That means we do not have to memorize the whole programming language book! So in that situation I felt that Google screwed my job!

Not talking subjectively, Is it good to google all the time?


答:
The only possible downsides to bundling all of your JS into one file that I can think of are:

Some of the your files may not "play well" together. Eg if one file is missing a semicolon at the end then bundling another file onto the end might break things. This has happened to me more than once.

Some files might depend on being in a particular path, and your one bundle can only be in the one spot. You might have to move around a bunch of images or css files or modify the JS files so that the relative paths are correct.

There might be conflicting libraries (maybe one page uses jquery 1.7 and another 1.10)

Changing one file will result in the whole bundle being regenerated with a new URL.

One very large initial download. If there's not a lot of JS commonality amongst pages then you could argue that it's a large overhead hit that could be spread across requests.

Having said all that, I say go for it. I don't think the above are much of a concern.  You'll very quickly see what the issues will be :)

Title: Should I group all of my .js files into one large bundle?

Body:
One of the difficulties I'm running into with my current project is that the previous developer spaghetti'd the javascript code in lots of different files.  We have modal dialogs that are reused in different places and I find that the same .js file is often loaded twice.

My thinking is that I'd like to just load all of the .js files in _Layout.cshtml, and that way I know it's loaded once and only once.  Also, the client should only have to download this file once as well.  It should be cached and therefore shouldn't really be a performance hit, except for the first page load.

I should probably note that I am using ASP.Net bundling as well and loading most of the jQuery/bootstrap/etc from CDN's.

Is there anything else that I'm not thinking of that would cause problems here?  Should I bundle everything into a single file?


问:
Am I doing TDD wrong when multiple tests can fail for the same reason?
Assume a method with the following declaration

```<code>public IList<Location> GetLocations() { ... }
</code>```

I write (at least) the following tests

Check to see if the method returns an empty collection if no locations are found.

Check to see if the method returns the correct number of locations.

Check to see if the data in the locations the method return is correct.

However, all the tests above will fail if the method returns null. I feel like a single error should only result in one unit test failure, but at the same time I do not see how to avoid it  in a scenario like this. Is this just the way it works; sometimes multiple tests will fail for the same reason?

答:
I disagree with Infer-On's answer. Indeed, though not always achievable in practice, one should strive for having a single error cause just one test to fail.

The main fallacy of your assumptions is in your list of behaviors. There is one crucial test missing from your list based on the information you provided:

```<code>0. Check to see if the method returns null when circumstance x occurs.
</code>```

This is the one and only test where your method should be allowed to return null. If it returns null in the other 3 tests you have listed, then those tests are not testing what they claim.

First, you need to make sure your behaviors (tests) are correctly stating what they want. Roy Osherove in The Art of Unit Testing goes into this in copious detail but to be very brief, he purports a test name should be of the form <method> <scenario> <behavior>. And, in fact, your first test abides by this, just in a slightly different order, which is perfectly fine (and the way I tend to do it, as it happens). Here I have separated out the components in your test name:

```<code>1. <method> <returns an empty collection> <if no locations are found>
</code>```

But your second and third tests are missing the scenario.

```<code>2. <method> <returns the correct number of locations> <when what??>
3. <method> <returns correct location data> <when what??>
</code>```

Let's say that the scenario (the "when what??") for both (2) and (3) is something like "when given proper coordinates". (Replace that with whatever fits in your context.)

Getting back to the main point, though, for all 3 tests, if the method is returning null then it is not given the opportunity to look for locations and find none (1) and it is not given proper coordinates (2) and (3). So those tests are failing but for the wrong reasons.

So to put into practice: The extra test I introduced above (0) handles the case of the method returning null, so the method must not return null in the remaining tests. You must instrument them appropriately with test doubles (typically mocks and/or stubs) so you can eliminate outside influences and isolate precisely what you want to test.

Body:
I disagree with Infer-On's answer. Indeed, though not always achievable in practice, one should strive for having a single error cause just one test to fail.

The main fallacy of your assumptions is in your list of behaviors. There is one crucial test missing from your list based on the information you provided:

0. Check to see if the method returns null when circumstance x occurs.

This is the one and only test where your method should be allowed to return null. If it returns null in the other 3 tests you have listed, then those tests are not testing what they claim.

First, you need to make sure your behaviors (tests) are correctly stating what they want. Roy Osherove in The Art of Unit Testing goes into this in copious detail but to be very brief, he purports a test name should be of the form <method> <scenario> <behavior>. And, in fact, your first test abides by this, just in a slightly different order, which is perfectly fine (and the way I tend to do it, as it happens). Here I have separated out the components in your test name:

1. <method> <returns an empty collection> <if no locations are found>

But your second and third tests are missing the scenario.

2. <method> <returns the correct number of locations> <when what??>
3. <method> <returns correct location data> <when what??>

Let's say that the scenario (the "when what??") for both (2) and (3) is something like "when given proper coordinates". (Replace that with whatever fits in your context.)

Getting back to the main point, though, for all 3 tests, if the method is returning null then it is not given the opportunity to look for locations and find none (1) and it is not given proper coordinates (2) and (3). So those tests are failing but for the wrong reasons.

So to put into practice: The extra test I introduced above (0) handles the case of the method returning null, so the method must not return null in the remaining tests. You must instrument them appropriately with test doubles (typically mocks and/or stubs) so you can eliminate outside influences and isolate precisely what you want to test.


问:
Technical reasons to prefer coding business logic to support Unicode (when not required)
I have a legacy application in which the UI and business logic are already reasonably well-separated. There is a proposal to separate them even further, turning the core application into a "service" (without UI) and writing a kind of "UI Server" as part of it to which various UIs (potentially in various languages, and for various different devices and operators) can connect to get/set the data to drive the application via those UIs.

On the surface, this seems to make a nice separation between the business logic, which is currently completely ignorant of the possibility of Unicode, and the UI, which is going to need to get very familiar with Unicode to support multiple languages in the UI(s).

Now this application essentially monitors a production process, and has very little (if any) traffic directly from UI to database via the business layer. It strikes me that the "natural language" of this process might as well be Chemistry or Mathematics, and so internally I should stick to the language that best describes it, so long as I can translate from that language into anything any UI requires (which I believe should be possible). This leads me to prefer (the simplicity and familiarity and least work path of) retaining old-fashioned 8-bit chars over moving to Unicode.

Are there any technical reasons to reject keeping the business logic part of an application ignorant of Unicode like this? And even if the "natural language" of the system were "English-without-too-many-strings-or-dates" rather than Chemistry, would that make a difference?

答:
Are there any technical reasons to reject keeping the business logic part of an application ignorant of Unicode like this?

While you're reasonably certain that your system doesn't need Unicode (now), I don't see what you gain by precluding it. Unless you're using an environment with horrible Unicode support, I imagine it'll be more work to go that route.

And even if you really don't ever need it, most other people viewing this answer probably will.

There's likely a performance hit to transition between encodings at the UI/BL boundary.

There may be serialization challenges to transition between encodings depending on your boundary transport.

And even if the "natural language" of the system were "English-without-too-many-strings-or-dates" rather than Chemistry, would that make a difference?

Sure. In something like a physical science where the papers and discussions all take place in English (do they?) you can be reasonably certain that nobody is going to come in and demand localization in the software's lifetime. In "English with few strings" software, success will likely lead to non-English companies wanting to use the application - leading to localization demands.


问:
Is there a way to write this fold neater in Haskell?
I have the following small function that uses foldr to find the largest second number of a 2-tuple:

```<code>listMax :: [(Int,Int)] -> Int
listMax = snd . foldr (\(_,freq1) (_,freq2) -> (0,max freq1 freq2)) (0,0)
</code>```

My question pertains to the body of the lambda:

```<code>(0,max freq1 freq2)
</code>```

I had to make it into a tuple with a dummy head so that it matches it's own input for the fold. To me though, it looks ugly and makes it harder to read. Is this the standard way of dealing with this situation, or is there a idiomatic way around this?

答:
Well I'd probably write it as

```<code>listMax :: [(Int,Int)] -> Int
listMax = foldr max 0 . map snd
</code>```

List fusion should actually make this compile to the same thing in the end :)

Worth noting that this is technically incorrect as it will misbehave with all negative numbers.

```<code>listMax = foldr max minBound . map snd
</code>```

Body:
Well I'd probably write it as

listMax :: [(Int,Int)] -> Int
listMax = foldr max 0 . map snd

List fusion should actually make this compile to the same thing in the end :)

Worth noting that this is technically incorrect as it will misbehave with all negative numbers.

listMax = foldr max minBound . map snd


问:
Handling leaves in tree-based menus
Tl;Dr

Given a language with no polymorphism how to you elegantly modify the behavior of a leaf in a tree data structure.

Context

I'm programming an application in C for a microcontroller and I'm wondering what would be the best way to design flexible GUI-less menus.

Basically inputs may come from 2 different sources: The built-in buttons on the board used by the user and a Uart port used by the production team to calibrate the device before shipping.

I already have a mechanism using a thread to listen to inputs (from both the buttons and the serial port) who post them to a crude parser. The parser then takes action depending on the currently registered callback for the received input. It also knows if the menu must be printed on the LCD screen or through the serial port.

I'm also using a k-ary tree to represent the hierarchy between sub-menus and different options. Since the menus are not defined yet it'll allow me to simply add / remove nodes when my supervisor makes his mind on the supported features.

Now when the currently displayed menu is not a leaf, the behavior is quite simply. Left and Right moves between siblings, Back selects the parent and Enter selects the first child.

If its a leaf, Enter activates / deactivates modifications, Left and Right increment / decrement the value and Back cancels the moficiation.

Other concerns

Am I over-engeenering stuff that could be done with a bunch of
switch-cases?

Are there ressources giving example of clean GUI-less menus when you don't
know where the inputs come from, the actions you will have to take, the menus you must offer and where to display those menus?

Since there is basically 2 options (leaf or not) should I just do
everything with if/elses and move on?

答:
C provides plenty of polymorphism for what you're doing. Cast one pointer-to-function to another, cast pointer-to-struct or overlay them with unions. Some macros can really help the readability -- read some big C projects to get ideas of how. Just be careful, because the compiler won't help much.

Bullets:

No, looks fine to me. Avoid switches.

External resources? Search engines are good at that.

No, avoid conditional logic too.

My view is you're on the right track. A menu structure should be modeled as data, and a node-leaf structure is a good match. Things that can be data should be data, because they're easier to read, test and maintain.

Title: Handling leaves in tree-based menus


问:
How to create an algorithm for determining Boolean Tautologies
So i am right now exploring some topics in a proof course and it occurred to me to try to create a boolean tautology solver. I would like an algorithm that is more efficient than brute force.

Problem Statement:

given a string of '(', ')', '[and]', '[or]', ! and pieces of text that denote variable names (which by definition cannot include parenthetical marks brace marks or ! marks) which must be surrounded by a pair of parenthesis

The words 'TRUE' and 'FALSE' are also reserved

determine if the boolean string is well-formed and if so, is it a tautology

ex: (alpha)[and](beta)

is well formed and not a tautology because if: alpha = false and beta = true is a counter example

ex: (alpha)[or]!(alpha) is well formed and a tautology because ((X)[or]!(X)) is by definition a tautology

ex: ((alpha)[or]((beta)[or]!(beta))) is well formed since (beta)[or]!(beta) is true and ((alpha)[or](TRUE)) is always true

ex: ((alpha[and](beta)) is not well formed

Some ideas I had for this was to begin by forming a parenthetical tree.
Since every statement will be encapsulated by parenthesis before it can be applied to a [or], [and], or [!] operator what I can do is partition the string into its separate highest level blocks enclosed by parenthesis (clause1)(clause2) to generate 2 nodes of a tree pointing to the high level node

Each node contains information about whether it has a ! attached to it's front, and if it has nodes below, what operator is used to unify those two nodes

This tree could be quickly generated to reduce the statement to individual literals and easily verify if the statement is well-formed (are there an equal number of ( as ) and does every [or] and [and] have two statements surrounding and a pair of encapsulating parenthesis around these two statements.

Now my plan was to systematically crawl up to nodes that do have a (!) value and distribute the not via DeMorgan's laws. If I am ever forced to do something along the lines (x and !x) I have immediately found a contradiction and can abort.

I'm still not perfectly clear what must happen at this stage however

答:
The problem to detect a tautology is equivalent to the boolean satisfiability problem which is sadly np-complete for general instances. You can easily convert tautology detection into SAT problem by negating the boolean equation and check its satisfiability , if the negated equation is unsatisfiable then the original equation must be a tautology.

What you can do :-

Use lex & yacc parser tools to generate a grammer to parse a equation.

Evaluate the negation of the equation using de-morgan's law.

Give the negated eqaution to a standard SAT solvers.

Note: If your equation is reducible to 2-SAT then there is linear time algorithm .

OwnerDisplayName: frogeyedpeas

OwnerDisplayName: Vikram Bhat


问:
How restrictive are the GPL's linking restrictions really?
To my basic understanding, software licenses only apply when redistributing software. Even if I am wrong about this in general, the GPL states that you need not agree to the GPL in order to receive or run a GPL-covered program.

Say there is Program X. Program X requires Library L to run. Program X is covered by a GPL-incompatible license (e.g. the Eclipse Public License, or a proprietary license). Library L is covered by the GPLv3.

Program X cannot be distributed alongside Library L - the combination would need to be covered by the GPL, which would violate the EPL.

What prevents users from separately installing Program X and Library L, and then using Program X?

Perhaps more relevantly in the modern world of auto-updaters, what prevents Program X from including a wrapper which downloads Library L from the Internet (say, from Library L's official website) and then executing Program X?

In both of these cases, nothing from Library L is distributed by the authors of Program X, so Library L's license should not apply.

What, if anything, changes if Program X instead requires Library L', a fork of Library L by the authors of Program X, which is only available from the same website as Program X and is only usable with Program X, but is never distributed in the same package as Program X?

What if this is all in a dynamic language, and no part of Library L is required to compile Program X?

What if Program X is distributed in source code form, so that the distribution was not compiled from Library L's headers?

答:
Q1. Nothing. A user can merge X and L as long as they comply with all licence requirements.

Q2. No good. The owners of X are now in control and are performing a merge on-site, which brings them under the L licensing terms. But there is room for a lawyer's picnic.

Q3. Still falls under the merge provisions.

Q4. Dynamic language: no change. Depends where and how the merge happens.

Q5. X in source form: no change.

Ultimately if the distributor of X owns and controls the merge, they are bound by the licence that covers the distribution of merged versions, even if they 'arrange' for that merge to be performed on the client site. Either that or there is a strong argument and a fierce legal battle before anyone is certain.

But if you can distribute X and pass the decision to use and merge X with L entirely on to the recipient you would not be bound by the licence for L. You could write licence terms to that effect and be reasonably sure they could not be challenged, or if they were, that you were indemnified by the recipient. Another lawyer's picnic.


问:
How to identify and run the most relevant automated tests?
Suppose you have a reasonably large codebase (0.5 - 1 msloc) with a large test-suite (6-7hr single-threaded runtime; with a mix of unit-tests and integration-tests built with different tools).  You have a proposed patch (or diff or pull-request) for the codebase, and you want to automatically run the most relevant tests.  Running all tests would be too expensive. Running smoke-tests would be too shallow.  The goal is to find something in-between.  By automating the selection of relevant tests, you can help new developers participate in TDD -- and provide timely pre-merge feedback (as part of code-review).

What techniques or arrangements would you use to identify "relevant"?  (A basic example: if a patch modifies "src/(.*).php", then run "phpunit test/{$1}Test.php".) What, if any, existing tools come to mind?  Or what new tools are needed?  Or is it impossible for tooling to help?

(For context: In my particular use-case, I work with LAMP-based web-apps, so tools or techniques that work with PHP/JS/bash are most helpful. But similar issues probably arise with any large app/deep stack, so examples from other stacks could provide insight.)

答:
TL;DR: Create a Dependency DAG from affected modules

Identifying the tests that are impacted by a particular change is the same as identifying when to recompile/relink a object file.  Create a dependency directed acyclic graph (DAG) starting at the modified module.  You should be able to traverse all imports to identify the what needs to be tested.  You can also follow out from there to the relevant unit tests.  Integration tests will be somewhat harder.  You can either run the integration test if it happens to include the updated module; or you can try doing something more clever like tagging the functions or objects that get called during the tests and use that to determine if it needs to be run or not.


答:
You can actually have both. Unicode supports an encoding where all characters are represented as a (variable length) sequence of 8-bit units: UTF-8.

Assuming that you refer to ASCII with your 'old-fashioned 8-bit chars', then you can almost trivially support UTF-8, because UTF-8 is a proper superset of ASCII: All characters in the original 7-bit ASCII set are present in UTF-8 with the same code value. The characters in the various 'extended ASCII' sets (as well as the rest of the characters in Unicode) are encoded as multi-byte values. This encoding is done in such a way that for each individual byte you can tell if it represents 1) a single-byte character, 2) the start of a multi-byte character, or 3) another byte in a multi-byte character.

The only area that you must be careful in when going from ASCII (or other fixed-length encodings) to UTF-8 (and Unicode in general) is text/string processing. As UTF-8 (and Unicode in general) doesn't use fixed-length encodings, any algorithms that assume a fixed-length encoding can easily give incorrect results.

Title: Technical reasons to prefer coding business logic to support Unicode (when not required)

Body:
I have a legacy application in which the UI and business logic are already reasonably well-separated. There is a proposal to separate them even further, turning the core application into a "service" (without UI) and writing a kind of "UI Server" as part of it to which various UIs (potentially in various languages, and for various different devices and operators) can connect to get/set the data to drive the application via those UIs.

On the surface, this seems to make a nice separation between the business logic, which is currently completely ignorant of the possibility of Unicode, and the UI, which is going to need to get very familiar with Unicode to support multiple languages in the UI(s).

Now this application essentially monitors a production process, and has very little (if any) traffic directly from UI to database via the business layer. It strikes me that the "natural language" of this process might as well be Chemistry or Mathematics, and so internally I should stick to the language that best describes it, so long as I can translate from that language into anything any UI requires (which I believe should be possible). This leads me to prefer (the simplicity and familiarity and least work path of) retaining old-fashioned 8-bit chars over moving to Unicode.

Are there any technical reasons to reject keeping the business logic part of an application ignorant of Unicode like this? And even if the "natural language" of the system were "English-without-too-many-strings-or-dates" rather than Chemistry, would that make a difference?


答:
Telastyn's answer already has some good points, to which I want to add a few:

You're speaking of internationalization, at least for the UI. That means user-names etc.:

Have a user named André Svónögrödäß (yes, him) and store his profile on the server: BOINK! translations and transscriptions everywhere., or tell him that his name is "wrong", while the other 99.9% of software in the world accept his name.

Also: Can you 110% guarantee that no business-data around the globe will ever be dependant on Unicode?

I'd wager the cost of implementing it now with a slight risk of not really needing it vs. the cost of implementing when the users start complaining.


答:
You may want to consider only running tests that have recently failed.  Given that the entire set takes 6-7 hours (i.e. is runnable nightly), you could base your tests set on the past few nights' results.  If you mix in a few randomly selected tests for broader coverage over the course of the day, you should get a good chance of catching errors.

This idea is simple to implement, leverages the notion that most tests rarely if ever fail (considered a bad sign in testing, but usually that's hard to prevent).  You get to keep those low-value tests for your nightly full-coverage test, but run the more valuable tests during the day.

If you want to get really fancy, you could deemphasize tests that are correlated with each other, specifically tests that fail only when some other test fails.

Title: How to identify and run the most relevant automated tests?

Body:
Suppose you have a reasonably large codebase (0.5 - 1 msloc) with a large test-suite (6-7hr single-threaded runtime; with a mix of unit-tests and integration-tests built with different tools).  You have a proposed patch (or diff or pull-request) for the codebase, and you want to automatically run the most relevant tests.  Running all tests would be too expensive. Running smoke-tests would be too shallow.  The goal is to find something in-between.  By automating the selection of relevant tests, you can help new developers participate in TDD -- and provide timely pre-merge feedback (as part of code-review).

What techniques or arrangements would you use to identify "relevant"?  (A basic example: if a patch modifies "src/(.*).php", then run "phpunit test/{$1}Test.php".) What, if any, existing tools come to mind?  Or what new tools are needed?  Or is it impossible for tooling to help?

(For context: In my particular use-case, I work with LAMP-based web-apps, so tools or techniques that work with PHP/JS/bash are most helpful. But similar issues probably arise with any large app/deep stack, so examples from other stacks could provide insight.)


问:
Is recursion an instance of being "too clever" when programming?
I've read several books and learned through experience that optimizing code to the point where it is inscrutable, or coming up with an extremely fast but extremely complex solution to a problem is not desirable when working in teams, or even when you're working by yourself and have to understand your clever solution some time later.

My question is, should recursion be treated in the same manner?  Does the average programmer understand recursion easily and thus one should use it with impunity, or does the average programmer not understand recursion very well and one should stay away from it for the sake of overall team productivity?

I know there are simple answers of, "Any programmer who doesn't understand recursion isn't worth a grain of salt, so don't worry about them" but I was wondering if you all had some real world experience you would like to share that would illuminate the issue more than the opinion I just mentioned.

答:
Some problems, such as walking a tree structure (walking, say, an entire directory structure, as opposed to, say, searching for a specific B-Tree node), are ideally suited to using recursion; the non-recursive equivalents often simply add the complication of managing your own stack.

In these cases, recursion is the best, simplest solution and easiest to understand.


问:
Git submodule vs Git clone
I am working on an open source project on GitHub.

It has a subdirectory /Vendor in which it has a copy of several external libraries. Original maintainer of the project  updated this directory with newer copy of external library once in a while.

One developer send me a pull request with idea to replace this copy by git submodule.

And I am considering whether it's good idea or not.

Git submodule Pros:

Submodules were specifically designed for similar scenarios

It removes possibility of accidental commit to Vendor which will be overwritten while next update

Git submodule Cons:

It looks like git submodules pushes complexity from maintainer to a person who will clone/pull the project (additional steps required after you clone to start working with the project: "git submodule init", "git submodule update"

What's your opinion on this?

One more thing. This problem is reasonably small size library with very limited external dependencies. I think any build tool would be overkill for it for now.

答: One drawback of using submodules is that the tarballs or zip-archives on Github (and many other services) do not include the sources of submodules. That is, the archives are not self-contained. This is of an issue if the repository is small and does not really have a build script, like a static HTML site depending on a JavaScript library.</p>

ContentLicense: CC BY-SA 4.0

Title: Git submodule vs Git clone


答:
What you see is the effect of the optimiser.

The optimisers job is to make the resulting compiled code either smaller, or faster (but rarely both at the same time... but like many things... IT DEPENDS on what the code is).

In PRINCIPLE, any call to a multiplication library, or, frequently, even use of a hardware multiplier will be slower than just doing a bitwise shift.

So... if the naive compiler generated a call to a library for the operation *2, then of course it would run slower than a bitwise shift*.

However optimisers are there to detect patterns and figure out how to make the code smaller/faster/ whatever. And what you have seen is the compiler detecting that *2 is the same as a shift.

Just as a matter of interest I was just today looking at the generated assembler for some operations like *5... not actually looking at that but other things, and along the way I notice that the compiler had turned *5 into:

shift

shift

add original number

So the optimiser of my compiler was smart enough (at least for certain small constants) to generate inline shifts and adds instead of calls to a general purpose multiply library.

The art of compiler optimisers is a whole separate subject, filled with magic, and really properly understood by about 6 people on the whole planet :)

Title: When I test out the difference in time between shifting and multiplying in C, there is no difference. Why?

Body:
I have been taught that shifting in binary is much more efficient than multiplying by 2^k. So I wanted to experiment, and I used the following code to test this out:

```<code>#include <time.h>
#include <stdio.h>

int main() {
    clock_t launch = clock();
    int test = 0x01;
    int runs;

    //simple loop that oscillates between int 1 and int 2
    for (runs = 0; runs < 100000000; runs++) {

    // I first compiled + ran it a few times with this:
    test *= 2;

    // then I recompiled + ran it a few times with:
    test <<= 1;

    // set back to 1 each time
    test >>= 1;
    }

    clock_t done = clock();
    double diff = (done - launch);
    printf("%f\n",diff);
}
</code>```

For both versions, the print out was approximately 440000, give or take 10000. There was no (visually, at least) significant difference between the two versions' outputs. So my question is, is there something wrong with my methodology? Should there even be a visual difference? Does this have something to do with the architecture of my computer, the compiler, or something else?


问:
Is it useful to keep 'definition' entities in a database vs using an enum?
In a project that I have started working on, the database has a lot of FooDefinition tables which act like an enum. It's a C# project using Entity Framework although that is not central to the question.

The entities have an ID, a string Name field and an int Type field that is converted to an enum. For example:

```<code>public class FooDefinition
{
    public int Id { get; set; }
    public string Name { get; set; }
    public FooType FooType { get; set; } // this is an enum that defines the entity
}
</code>```

The FooDefinition table is populated with an entity for each defined enum value, and does not change unless there is a new enum value added.

I am struggling to see the use in this pattern over just using the enum directly as opposed to joining on this Definition table. What are the possible benefits of this approach?

答: I actually just had to make a change that linked two of these tables together, which would have had to have been done in code otherwise (and then required a code release whenever this relationship changed). So I suppose one reason is extensibility in saving data about these enums.</p>


问:
Which management book would you recommend to read for a fresh Team Leader?
Which management book would you recommend to read for a fresh Team Leader?</p>

答:
Peopleware: Productive Projects and Teams comes to mind.

The first chapter of the book claims,

“The major problems of our work are not so much technological as sociological in nature”.

The book approaches sociological or ‘political’ problems such as team ‘jelling’, quiet in the work environment, and the high cost of turnover.


问:
What would you avoid re-inventing at all costs?
We recently had to re-invent a high-availability queueing engine like RabbitMQ (for various reasons).

Naturally this turned out to be more time consuming and expensive than expected.

What type of things would you avoid rebuilding at all costs?  Which types of components should rather be reused?

答:
Just follow the cost benefit analysis. You should avoiding re-inventing all things that Cost_To_Acquire + Maintenance_Cost + Risk is higher then the costs to build the component.

Cost to Acquire can be the cost to purchase a license, pay training or just spend hours studying.
The Risk is far higher for any new product: it is not fully tested, has not known problems, has no community around it, and any plug-ins/tweaks will have to be reinvented.


问:
How comes the C++ standards committee introduces a keyword like nullptr and gets away with it?
That must have broken a lot of peoples code bases right?
Everyone who had a variable named "nullptr" (which I think would have been fairly common) has to find "nullptr" and replace with "something_else" before being able to compile with c++11.

Does the standards committee assume that people will do that much "adjusting"?

答:
The C++ standards committee is full of smart people that are fully aware of the amount of existing code and the consequences of introducing new keywords.

One of the aims of the committee is to keep as much existing code as possible working unchanged and that certainly plays a large role when deciding to add new keywords and how to name those keywords.

To my knowledge, when a new keyword is proposed, they perform an investigation over a number of large codebases to see how many conflicts that new keyword would create and if any of those conflicts would create a silent change in the behavior of the programs.

According to the proposal for adding nullptr, this spelling of the keyword resulted in the least amount of conflict with existing code:

Programmers have often requested that the null pointer constant have a name, and nullptr appears to be the least likely of the alternative text spellings to conflict with identifiers in existing user programs. For example, a Google search for nullptr cpp returns a total of merely 150 hits, only one of which appears to use nullptr in a C++ program.

The alternative name NULL is not available. NULL is already the name of an implementation-defined macro in the C and C++ standards. If we defined NULL to be a keyword, it would still be replaced by macros lurking in older code. Also, there might be code “out there” that (unwisely) depended on NULL being 0. Finally, identifiers in all caps are conventionally assumed to be macros, testable by #ifdef, etc.

The alternative name null is impractical. It is nearly as bad as NULL in that null is also a commonly used in existing programs as an identifier name and (worse)
  as a macro name. For example, a Google search for null cpp returns about 180,000 hits, of which an estimated 3% or over 5,000 use null in C++ code as an identifier or as a macro. Another favorite, nil, is worse still.

Any other name we have thought of is longer or clashes more often.

Given this analysis, I don't expect that that much adjustment needs to be done.

But otherwise, yes you are expected to update your codebase for the backwards-incompatible changes when moving to a new standard.


问:
When I test out the difference in time between shifting and multiplying in C, there is no difference. Why?
I have been taught that shifting in binary is much more efficient than multiplying by 2^k. So I wanted to experiment, and I used the following code to test this out:

```<code>#include <time.h>
#include <stdio.h>

int main() {
    clock_t launch = clock();
    int test = 0x01;
    int runs;

    //simple loop that oscillates between int 1 and int 2
    for (runs = 0; runs < 100000000; runs++) {

    // I first compiled + ran it a few times with this:
    test *= 2;

    // then I recompiled + ran it a few times with:
    test <<= 1;

    // set back to 1 each time
    test >>= 1;
    }

    clock_t done = clock();
    double diff = (done - launch);
    printf("%f\n",diff);
}
</code>```

For both versions, the print out was approximately 440000, give or take 10000. There was no (visually, at least) significant difference between the two versions' outputs. So my question is, is there something wrong with my methodology? Should there even be a visual difference? Does this have something to do with the architecture of my computer, the compiler, or something else?

答:
Whether shifting is faster than multiplication depends on the architecture of your CPU. Back in the days of the Pentium and earlier, shifting was often faster than multiplication, depending on the number of 1 bits in your multiplicand. For example, if your multiplicand was 320, that's 101000000, two bits.

```<code>a *= 320;               // Slower
a = (a<<7) + (a<<9);    // Faster
</code>```

But if you had more than two bits ...

```<code>a *= 324;                        // About same speed
a = (a<<2) + (a<<7) + (a<<9);    // About same speed

a *= 340;                                 // Faster
a = (a<<2) + (a<<4) + (a<<7) + (a<<9);    // Slower
</code>```

On a little microcontroller like a PIC18 with single cycle multiply, but no barrel shifter, multiplication is faster if you're shifting by more than 1 bit.

```<code>a  *= 2;   // Exactly the same speed
a <<= 1;   // Exactly the same speed

a  *= 4;   // Faster
a <<= 2;   // Slower
</code>```

Note that that's the opposite of what was true on older Intel CPUs.

But it's still not that simple. If I remember correctly, due to its Superscalar architecture, a Pentium was able to process either one multiply instruction or two shift instructions simultaneously (as long as they weren't dependent on each other). This means that if you wanted to multiply two variables by a power of 2, then shifting might be better.

```<code>a  *= 4;   //
b  *= 4;   //

a <<= 2;   // Both lines execute in a single cycle
b <<= 2;   //
</code>```

Body:
Whether shifting is faster than multiplication depends on the architecture of your CPU. Back in the days of the Pentium and earlier, shifting was often faster than multiplication, depending on the number of 1 bits in your multiplicand. For example, if your multiplicand was 320, that's 101000000, two bits.

a *= 320;               // Slower
a = (a<<7) + (a<<9);    // Faster

But if you had more than two bits ...

a *= 324;                        // About same speed
a = (a<<2) + (a<<7) + (a<<9);    // About same speed

a *= 340;                                 // Faster
a = (a<<2) + (a<<4) + (a<<7) + (a<<9);    // Slower

On a little microcontroller like a PIC18 with single cycle multiply, but no barrel shifter, multiplication is faster if you're shifting by more than 1 bit.

a  *= 2;   // Exactly the same speed
a <<= 1;   // Exactly the same speed

a  *= 4;   // Faster
a <<= 2;   // Slower

Note that that's the opposite of what was true on older Intel CPUs.

But it's still not that simple. If I remember correctly, due to its Superscalar architecture, a Pentium was able to process either one multiply instruction or two shift instructions simultaneously (as long as they weren't dependent on each other). This means that if you wanted to multiply two variables by a power of 2, then shifting might be better.

a  *= 4;   //
b  *= 4;   //

a <<= 2;   // Both lines execute in a single cycle
b <<= 2;   //


答: Introducing new language features and extensions, most of the time, require new language keywords or syntax changes. In addition, its essential to name these keywords for their intended purposes so as to help programmers memorize the new features. Fortunately, for that purpose, new language version/standards contain a list of code-breaking changes that you must consult before building the code with the new toolset.

Title: How comes the C++ standards committee introduces a keyword like nullptr and gets away with it?

Body:
That must have broken a lot of peoples code bases right?
Everyone who had a variable named "nullptr" (which I think would have been fairly common) has to find "nullptr" and replace with "something_else" before being able to compile with c++11.

Does the standards committee assume that people will do that much "adjusting"?


问:
Is "continue" and "break" in loops antipattern/bad practice in Java?
I see the main purpose of continue in programming, it can get you out from the rest of loop steps like:

```<code>while(condition1){
  ... code ...
  if(!condition2){
    continue;
  }
  ... code ...
  if(condition3){
    break;
  }
  ... code ...
}
</code>```

I understand that condition2 and condition3 might depend on the inner code so it makes handy to make a separate escape route from loop step. But does it mean the code should be refactored instead building escape routes, like rethinking the original condition1?

I would say if I need several continue and break parts, I feel bad about my code, usually I am working without continue and I don't really miss it.

An another use of continue and break which I can accept is optimalization, but I still have the same feeling about it like I told above. For some reasons I have feeling "using GOTO". Am I right, if I am not, why?

答:
Correction: continue gets you out of one iteration of a loop, not out of the entire loop.

Skipping the rest of an iteration of a loop is a lot like returning early from a method call (in fact, a lot of long loop bodies should be method calls). So the same arguments apply as for "return early or use nested if?", which is already a well-known, divisive controversy; I doubt you'll achieve a consensus about this question either.

My own position is: continue is a keyword for a reason; it is in no way automatically bad the way most people think goto is bad.


问:
Purest functional programming language(s)?
I'm interested in better learning functional programming. To do so, it seems obvious that I should force myself to use the purest possible functional programming language. Hence, I'm here asking, more or less, for an ordering of functional programming languages according to their purity.

It seems to me that it would be more practical to learn Lisp or Clojure (or Scheme, or Scala, etc.), but for what I've heard recently, Haskell would be very hard to beat at teaching functional programming principles to someone. I'm not sure about this yet, so I'm asking you: which is the purest functional programming language? An ordering would be great if several are competing for the magnificent title of the purest functional programming language.

答:
Since learning is your goal, and not writing programs per se, you can't get any purer than Lambda Calculus.

Lambda Calculus was around before computers were invented. It took several skilled logicians working on it to figure out how to do subtraction (for a while it was theorized that only addition and multiplication were possible).

Learning how booleans and numbers and if can be invented from seemingly nothing won't put more gas in your tank, but it will make your tank much bigger.


问:
How should I remember what I was doing and why on a project three months back?
I was working on a project three months back, and then suddenly another urgent project appeared and I was asked to shift my attention.

Starting tomorrow, I'll be heading back to the old project. I realize that I do not remember what exactly I was doing. I don't know where to begin.

How can I document a project such that anytime I look back it shouldn't take me more than a few minutes to get going from wherever I left. Are there best practices?

答:
To-do lists are magic.  Generally you need to keep an active to-do list for each project and even while you're busy programming, if you think of something that has to be done and you can't do it immediately, then it goes on the list.  Keep this list in a well-known place, either in a spreadsheet or text file in the project folder electronically, or in your paper logbook.

Also, whenever you leave the project for overnight (or over the weekend), take a post-it note and write the next thing you were going to do on the note, and stick it to the monitor.  That makes it more likely you'll get back into it quickly the next morning.

Edit:

I should mention that to-do lists (specifically prioritized to-do lists segregated by venue and project) are a key part of the Getting Things Done book, which I found highly influential.


答:
In my opinion, there are two parts to "resuming" a code project:

Determining where you left off

Remembering what left you have to do

This is one of those things that, I think, if you are doing version control the right way it'll be your "other brain".

Where did you leave off?  As long as your are committing code frequently, look at your last changeset.  It'll most likely jog something in your mind.  If not, look at the past few, starting with the oldest and replaying commits.

As for what left you have to do, a backlog should serve that purpose (or a to-do list, or whatever you want to name it.  Basically items for the future).

I am not a full-time software developer.  I'm a programmer that hacks on the nights and weekends.  Because of this, when work or other non-programming things take higher priority, sometimes I can go days and weeks without even pulling up my code with a glance.  The above has proven to be quite effective.

Title: How should I remember what I was doing and why on a project three months back?

Body:
I was working on a project three months back, and then suddenly another urgent project appeared and I was asked to shift my attention.

Starting tomorrow, I'll be heading back to the old project. I realize that I do not remember what exactly I was doing. I don't know where to begin.

How can I document a project such that anytime I look back it shouldn't take me more than a few minutes to get going from wherever I left. Are there best practices?


问:
Need an open-source license with a small commercial addition
I'm working on an open-source project and people can use it and modify it, no problems here. The only thing that I don't want to allow is that people exploit it and earn money using my work (because that's what my plans are!)

What kind of license should I use to cover these requirements?

答:
The title of the question says you need a small(??) commercial addition while in the question text you say that you don't want to allow people to earn money using your work. This seems to be contradictory.

Here are some ideas that can help you:

If you are a creator you have the copyright on the code then you can publish your project under multiple (non-exclusive) licenses and still sell it yourself without restrictions

Open source doesn't disallow selling. It only means you have to deliver the source code too. For small commercial activities (like as part of a magazine) this might be sufficient.

As long as your project is also open source, why would anyone buy the product if very probably he can get it for free from you (or someone else)? The market will be very small.

If you want to allow people to use your open software project in their commercial closed source product - use a license that allows this (LGPL, ...)

If you want to restrict commercial usage to small(??) usages, define small and put that in a license (modify LGPL for example).

If you cannot define small but want to have control, just state that upon request you might give away/sell commercial licenses (that do not require to distribute the source anymore).

For all this make sure that either you are the only copyright holder (creator) or that you have the consent of all previous and present creators.

I advice to use one or more popular open source licenses like GPL and offer to issue commercial licenses upon request or to define what small should be.

See also this excellent FAQ from the Free Software Foundation and this comparison of open source licenses.

edit: Adding the information of the comment.

If you don't want others to use your software to make money you would need to restrict your license to non-commercial (something like CC-NC for programming code).

It is questionable if it still is (fully) open source then anymore because it restricts the freedom quite a bit.

So it seems you want a non-commercial license.

A simple "free for private, non-commercial use" might be the right thing for you then.


问:
Explanation on how "Tell, Don't Ask" is considered good OO
This blogpost was posted on Hacker News with several upvotes. Coming from C++, most of these examples seem to go against what I've been taught.

Such as example #2:

Bad:

```<code>def check_for_overheating(system_monitor)
  if system_monitor.temperature > 100
    system_monitor.sound_alarms
  end
end
</code>```

versus good:

```<code>system_monitor.check_for_overheating

class SystemMonitor
  def check_for_overheating
    if temperature > 100
      sound_alarms
    end
  end
end
</code>```

The advice in C++ is that you should prefer free functions instead of member functions as they increase encapsulation. Both of these are identical semantically, so why prefer the choice that has access to more state?

Example 4:

Bad:

```<code>def street_name(user)
  if user.address
    user.address.street_name
  else
    'No street name on file'
  end
end
</code>```

versus good:

```<code>def street_name(user)
  user.address.street_name
end

class User
  def address
    @address || NullAddress.new
  end
end

class NullAddress
  def street_name
    'No street name on file'
  end
end
</code>```

Why is it the responsibility of User to format an unrelated error string? What if I want to do something besides print 'No street name on file' if it has no street? What if the street is named the same thing?

Could someone enlighten me on the "Tell, Don't Ask" advantages and rationale? I am not looking for which is better, but instead trying to understand the author's viewpoint.

答:
Data/Object Anti-Symmetry

As others pointed out, Tell-Dont-Ask is specifically for cases where you change the object state after you asked (see e.g. the Pragprog text posted elsewhere on this page). This is not always the case, e.g. the 'user' object is not changed after it was asked for its user.address. It's therefore debateable if this is an appropriate case to apply Tell-Dont-Ask.

Tell-Dont-Ask is concerned with responsibility, with not pulling logic out of a class that should be justifiably within it. But not all logic that deals with objects is necessarily  logic of those objects. This is hinting at a deeper level, even beyond Tell-Dont-Ask, and I want to add a short remark about that.

As a matter of architectural design, you might want to have objects that are really just containers for properties, maybe even immutable, and then run various functions over collections of such objects, evaluating, filtering or transforming them rather than sending them commands (which is more the domain of Tell-Dont-Ask).

The decision which is more appropriate for your problem depends on whether you expect to have stable data (the declarative objects) but with changing/adding on the function side. Or if you expect to have a stable and limited set of such functions but expect more flux at the objects level, e.g. by adding new types. In the first situation you would prefer free functions, in the second object methods.

Bob Martin, in his book "Clean Code", calls this the "Data/Object Anti-Symmetry" (p.95ff), other communities might refer to it as the "expression problem".


问:
Are "skip deltas" unique to svn?
The good folks who created the SVN version control system use a structure they refer to as "skip deltas" to store the revision history of files internally. A revision is stored as a delta against an earlier revision. However, revision N is not necessarily stored as a delta against revision N-1, like this:

```<code>0 <- 1 <- 2 <- 3 <- 4 <- 5 <- 6 <- 7 <- 8 <- 9
</code>```

Instead, revision N is stored as a delta against N-f(N), where f(N) is the greatest power of two that divides N:

```<code>0 <- 1    2 <- 3    4 <- 5    6 <- 7
0 <------ 2         4 <------ 6
0 <---------------- 4
0 <------------------------------------ 8 <- 9
</code>```

(Superficially it looks like a skip list but really it's not that similar - for instance, skip deltas are not interested in supporting insertion in the middle of the list.) You can read more about it here.

My question is: Do other systems use skip deltas? Were skip deltas known/used/published before SVN, or did the creators of SVN invent it themselves?

答:
Starting from your link Skip-Deltas in Subversion I found this note Notes on keeping version histories of files and there it's written that:

The author does not know of papers or other references describing the
technique [skip-deltas]. .. This document was written by Greg Hudson
ghudson@mit.edu on 2002-06-24.  It was last updated on 2002-10-03.

Skip-deltas seem to have been introduced to SVN in rev. 842883 mostly in file "/subversion/trunk/subversion/libsvn_fs/tree.c" by Greg Hudson on July 31, 2002 with the log message "Implement skip-deltas, in a low-overhead way." and in that revision in the file tree.c a comment was added "We do this using a technique derived from skip lists". Indeed skip lists have similarities to skip-deltas.

I also found two mailing list discussion from July 2002 where Greg Hudson discusses the potential impact and various other people discuss the patch that was committed a few days later.

So my guess is that skip deltas were invented by the SVN team, especially by Greg Hudson from the MIT in 2002, independently from anyone else drawing inspirations from skip lists while wanting to increase the information retrieval performance of their repository "file system".

I also searched for delta compression and didn't find any earlier reference. I think it would make sense, because this skip-delta technique is specialized on fast retrieval and maybe before SVN nobody needed fast retrieval of delta compressed data. Delta compression itself is in the literature since 70s/80s. One of the earliest papers is Experiences with delta compression of data produced by DIII.

Title: Are "skip deltas" unique to svn?


答:
The classic goto has different forms with various restrictions on them.  Be it return, try{} catch{}, throw, break, or continue.  They are all really goto with some additional bits around it.

One could refactor the continue or break into another looping style with return:

```<code>for (int i = 0; i <= max; i++) {
  if(someTest) { continue; }
  if(someOtherTest) { continue; }
  doStuff;
}
</code>```

Can be written as:

```<code>for (int i = 0; i <= max; i++) {
  func();
}
....

void func() {
  if(someTest) { return; }
  if(someOtherTest) { return; }
  doStuff;
}
</code>```

Which is easier to read?  Well, I'd tend to argue that the first is because the second loses the context of the loop... but they're otherwise the same.  Its just that people tend to see less of continue than they do of return in everyday code.

From Java Tutorials : Branching Statements break and continue when used with labels have a bit more power than most people realize.  It also makes the code a bit more explicit as to which loop is being acted upon by the control statement. Consider:

```<code>class ContinueWithLabelDemo {
    public static void main(String[] args) {
        String searchMe = "Look for a substring in me";
        String substring = "sub";
        boolean foundIt = false;

        int max = searchMe.length() -  substring.length();

    test:
        for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            while (n-- != 0) {
                if (searchMe.charAt(j++) != substring.charAt(k++)) {
                    continue test;
                }
            }
            foundIt = true;
            break test;
        }
        System.out.println(foundIt ? "Found it" : "Didn't find it");
    }
}
</code>```

Note that the continue and the break are used with a label that specifies what loop they continue or break to (the label on break isn't necessary because its only one level, but helps in the comprehension of the code).

If you really wanted to, you could refactor this code to:

```<code>public class Demo {
    public static void main(String[] args) {
        String searchMe = "Look for a substring in me";
        String substring = "sub";
        boolean foundIt;

        int max = searchMe.length() - substring.length();

        foundIt = loop2(searchMe, substring, max);
        System.out.println(foundIt ? "Found it" : "Didn't find it");
    }

    private static boolean loop2(String searchMe, String substring, int max) {
        for (int i = 0; i <= max; i++) {
            if (loop(searchMe, substring, i)) {
                return true;
            }
        }
        return false;
    }

    private static boolean loop(String searchMe, String substring, int j) {
        int n = substring.length();
        int k = 0;
        while (n-- != 0) {
            if (searchMe.charAt(j++) != substring.charAt(k++)) {
                return false;
            }
        }
        return true;
    }
}
</code>```

(I think I did that refactoring right though there are certainly bits in there to grumble about) ... but I'm really not sure what that gains you.  And those two methods with multiple returns will draw the wrath of the "multiple returns are an anti-pattern" crowd (which have just as valid points as the continue and break are anti-patterns crowd - and in the above case, likely more justified wrath too).  Yes, this could again be written in a way that makes use of other tests that will make the "arrow is an anti-pattern" people look at you funny.

continue is a guard statement in a loop.  break is a early return.

Because something isn't used much doesn't make it an anti pattern.  It just means that people aren't as familiar with it.

As an aside, goto is seeing a bit of a comeback in C# where it can be used with restrictions (note that C# doesn't have a labeled break like Java does and thus without going through the hoops of extracting methods, this is the way to write the code).

Title: Is "continue" and "break" in loops antipattern/bad practice in Java?

Body:
I see the main purpose of continue in programming, it can get you out from the rest of loop steps like:

```<code>while(condition1){
  ... code ...
  if(!condition2){
    continue;
  }
  ... code ...
  if(condition3){
    break;
  }
  ... code ...
}
</code>```

I understand that condition2 and condition3 might depend on the inner code so it makes handy to make a separate escape route from loop step. But does it mean the code should be refactored instead building escape routes, like rethinking the original condition1?

I would say if I need several continue and break parts, I feel bad about my code, usually I am working without continue and I don't really miss it.

An another use of continue and break which I can accept is optimalization, but I still have the same feeling about it like I told above. For some reasons I have feeling "using GOTO". Am I right, if I am not, why?

Body:
The classic goto has different forms with various restrictions on them.  Be it return, try{} catch{}, throw, break, or continue.  They are all really goto with some additional bits around it.

One could refactor the continue or break into another looping style with return:

for (int i = 0; i <= max; i++) {
  if(someTest) { continue; }
  if(someOtherTest) { continue; }
  doStuff;
}

Can be written as:

for (int i = 0; i <= max; i++) {
  func();
}
....

void func() {
  if(someTest) { return; }
  if(someOtherTest) { return; }
  doStuff;
}

Which is easier to read?  Well, I'd tend to argue that the first is because the second loses the context of the loop... but they're otherwise the same.  Its just that people tend to see less of continue than they do of return in everyday code.

From Java Tutorials : Branching Statements break and continue when used with labels have a bit more power than most people realize.  It also makes the code a bit more explicit as to which loop is being acted upon by the control statement. Consider:

class ContinueWithLabelDemo {
    public static void main(String[] args) {
        String searchMe = "Look for a substring in me";
        String substring = "sub";
        boolean foundIt = false;

        int max = searchMe.length() -  substring.length();

    test:
        for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            while (n-- != 0) {
                if (searchMe.charAt(j++) != substring.charAt(k++)) {
                    continue test;
                }
            }
            foundIt = true;
            break test;
        }
        System.out.println(foundIt ? "Found it" : "Didn't find it");
    }
}

Note that the continue and the break are used with a label that specifies what loop they continue or break to (the label on break isn't necessary because its only one level, but helps in the comprehension of the code).

If you really wanted to, you could refactor this code to:

public class Demo {
    public static void main(String[] args) {
        String searchMe = "Look for a substring in me";
        String substring = "sub";
        boolean foundIt;

        int max = searchMe.length() - substring.length();

        foundIt = loop2(searchMe, substring, max);
        System.out.println(foundIt ? "Found it" : "Didn't find it");
    }

    private static boolean loop2(String searchMe, String substring, int max) {
        for (int i = 0; i <= max; i++) {
            if (loop(searchMe, substring, i)) {
                return true;
            }
        }
        return false;
    }

    private static boolean loop(String searchMe, String substring, int j) {
        int n = substring.length();
        int k = 0;
        while (n-- != 0) {
            if (searchMe.charAt(j++) != substring.charAt(k++)) {
                return false;
            }
        }
        return true;
    }
}

(I think I did that refactoring right though there are certainly bits in there to grumble about) ... but I'm really not sure what that gains you.  And those two methods with multiple returns will draw the wrath of the "multiple returns are an anti-pattern" crowd (which have just as valid points as the continue and break are anti-patterns crowd - and in the above case, likely more justified wrath too).  Yes, this could again be written in a way that makes use of other tests that will make the "arrow is an anti-pattern" people look at you funny.

continue is a guard statement in a loop.  break is a early return.

Because something isn't used much doesn't make it an anti pattern.  It just means that people aren't as familiar with it.

As an aside, goto is seeing a bit of a comeback in C# where it can be used with restrictions (note that C# doesn't have a labeled break like Java does and thus without going through the hoops of extracting methods, this is the way to write the code).


问:
Should I use the repository in the Domain Object or push the Domain Object back to the Service Layer?
I have come from a transaction script world and I am just starting to take a look at DDD. I am unsure of the correct way to integrate a DDD design with database persistence. This is what I have:

A service class called OrganisationService whose interface contains methods for retrieving and saving away instances of Organisation domain objects. Organisation is an aggregate root and has other data related to it: Members and Licenses. EF6 database first DBContext is used within the OrganisationService to retrieve OrganisationDB entities and the related MemberDB and LicenseDB entities. These all get transformed into their domain object class equivalents when retrieved by the OrganisationService and loaded into the Organisation domain object. This object looks like so:

```<code>public class Organisation
{
    public IList<Member> Members { get; set; }
    public IList<License> Licenses { get; set; }
}
</code>```

I am not using the Repository pattern in the OrganisationService...I am using EF itself as the Repository as it seems that EF6 has largely made repository redundant now.

At this point in the design the Organisation domain object is anaemic: it looks like the EF POCO Organisation class. The OrganisationService class looks a lot like a Repository!

Now I need to start adding logic. This logic includes managing an Organisations Licenses and Members. Now in the transaction script days I would add methods into the OrganisationService for handling these operations and call into a Repository to interact with the DB, but with DDD I believe this logic should be encapsulated within the Organisation domain object itself...

This is where I am unsure of what I should be doing: I will need to persist this data back to the database as part of the logic. Does this mean I should use DbContext within the Organisation domain object to do this? Is using the repository/EF within the domain object bad practice? If so, where does this persistence belong?

```<code>public class Organisation
{
    public IList<Member> Members { get; set; }
    public IList<License> Licenses { get; set; }

    public void AddLicensesToOrganisation(IList<License> licensesToAdd)
    {
        // Do validation/other stuff/

        // And now Save to the DB???
        using(var context = new EFContext())
        {
            context.Licenses.Add(...
        }

        // Add to the Licenses collection in Memory
        Licenses.AddRange(licensesToAdd);
    }
}
</code>```

Should I instead just be mutating the Organisation domain object in memory and then pushing it back to the OrganisationService for persistence? Then I have to track what actually changed on the object (which is what EF does to its own POCOs! I am kind of coming to feel that EF isn't just a repository replacement, but also could be the domain layer!)

Any guidance here is appreciated.

答:
ORMs like EF and NHibernate can handle this transparently so you wont have to add the licences to the context explicitly, it will detect them when saving changes. So the method will be down to

```<code>public void AddLicenses(IEnumerable<License> licensesToAdd)
{
    // Do validation/other stuff/
    // Add to the Licenses collection in Memory
    Licenses.AddRange(licensesToAdd);
}
</code>```

and the code around it

```<code>var someOrg = Load(orgId);

someOrg.AddLicenses(someLicences);

SaveChanges();
</code>```

Update:

Of course this works only when u have the unitofwork/dbcontext/ISession open for the whole business operation. see lifetime

Using persisted entities instead of another service object will save you a lot of pain when handling object graphs like in OP code and reduces db calls because you dont have to reload the persisted entities in each service method because you already have them.

Body:
ORMs like EF and NHibernate can handle this transparently so you wont have to add the licences to the context explicitly, it will detect them when saving changes. So the method will be down to

public void AddLicenses(IEnumerable<License> licensesToAdd)
{
    // Do validation/other stuff/
    // Add to the Licenses collection in Memory
    Licenses.AddRange(licensesToAdd);
}

and the code around it

var someOrg = Load(orgId);

someOrg.AddLicenses(someLicences);

SaveChanges();

Update:

Of course this works only when u have the unitofwork/dbcontext/ISession open for the whole business operation. see lifetime

Using persisted entities instead of another service object will save you a lot of pain when handling object graphs like in OP code and reduces db calls because you dont have to reload the persisted entities in each service method because you already have them.


答: The Mythical Man Month by Fred Brooks has a lot of great what-not-to-dos. That and Peopleware are the two that define software project management.

Body: Which management book would you recommend to read for a fresh Team Leader?</p>


答:
The standard solution is dual licence. Release under GPL, retain the original copyright and when you're ready re-release under some different licence. Profit!

However, if you want to stop people from using your code to provide a commercial service, you will almost certainly need a custom licence. Likely terms will include:

free for private and non-commercial use

no rights of redistribution

no rights of sub-licensing

It's not easy to stop people from making money (if they can). You'll need a lawyer, but you'll also have to be willing to sue people.

I think I'd focus first on making something good enough that people want to steal it, and then making it better but only for your customers.

Title: Need an open-source license with a small commercial addition

Body:
I'm working on an open-source project and people can use it and modify it, no problems here. The only thing that I don't want to allow is that people exploit it and earn money using my work (because that's what my plans are!)

What kind of license should I use to cover these requirements?


答:
In addition to the suggestions about project tracking, ToDo lists, Trello, etc something I read once that helps if you're practicing TDD is to always step away from your project with a new failing test to implement whenever you return to the project (tomorrow, next week, or next month)

Sit down, do 'Run Tests', and pick up where you left off.


答:
What to do now?

Now, from tomorrow I'll be heading back to my old project and I realize that I do not remember what exactly was I doing and where to start!

My guess is you have not done any of the next section. So looking up a todo list won't work.

Block a period of time. Put this on your calendar and spend time reviewing the project. This might be reviewing documentation, code, requirements, etc.

Accept it will take a while to get back up to speed. Make sure all those involved realize this. Make sure you realize this.

Start with a small task. Rebuild your confidence some by doing something small. If you have a list of new items, work through smaller ones first. This not only rebuilds your confidence but also helps reacquaint yourself with the project.

How to make this better for yourself in future?

I wish to know how to document the project such that anytime I look back it shouldn't take me more than a few minutes to get going from wherever I left!

First, you need to have a system for keeping track of your todos. Do you have such a system now? How do you manage your current projectwork?

I could get hit by a bus tomorrow and my team would have a good idea of well over 90% of my action items. This is because I have a cohesive system for documenting my:

Immediate todos (<1 week items)

"Nice to have" todos

Milestones and macro todos (where specifics aren't meaningful)

Requirements/meeting notes

Plus, I use a VCS and comment my code where appropriate.

This works for me and my team since I am the primary developer. You can use some sort of issue tracking system for a team. Or a backlog when working with Agile. There are a ton of options. If you are really interested in this, read up on Getting Things Done or other relevant task management methodologies, which exist nearly precisely because of what you describe.

What's the point?

The specifics of the system are less relevant than that it is cohesive system and you use it. And that you use it. And use it. This is important. More important than a nice perfect system you don't use. Don't do "well most of my work is here, but some is in my head" or you'll hate yourself going back on a project.

Also, make sure your comments explain "why" rather than just the "what" for code. It's a lot easier to read "this is to fix a bug with IE8" and recall what the code does than a comment simply explaining the technical details.


答:
I've seen this used in Microsoft Dynamics CRM. It allows users to customize dropdown lists and the like quickly and easily on the fly.

Unless you intend an application to be extensively modifiable by users, I'm not sure if you would want to go down this route, as it could lead to some extra complexity to working with the data from the back end.

Title: Is it useful to keep 'definition' entities in a database vs using an enum?

Body:
In a project that I have started working on, the database has a lot of FooDefinition tables which act like an enum. It's a C# project using Entity Framework although that is not central to the question.

The entities have an ID, a string Name field and an int Type field that is converted to an enum. For example:

```<code>public class FooDefinition
{
    public int Id { get; set; }
    public string Name { get; set; }
    public FooType FooType { get; set; } // this is an enum that defines the entity
}
</code>```

The FooDefinition table is populated with an entity for each defined enum value, and does not change unless there is a new enum value added.

I am struggling to see the use in this pattern over just using the enum directly as opposed to joining on this Definition table. What are the possible benefits of this approach?


问:
In plain English, what is recursion?
The idea of recursion is not very common in real world. So, it seems a bit confusing to the novice programmers. Though, I guess, they become used to the concept gradually. So, what can be a nice explanation for them to grasp the idea easily?</p>

答:
Recursion is a tool a programmer can use to invoke a function call on itself. Fibonacci sequence is the textbook example of how recursion is used.

Most recursive code if not all can be expressed as iterative function, but its usually messy. Good examples of other recursive programs are Data Structures such as trees, binary search tree and even quicksort.

Recursion is used to make code less sloppy, keep in mind it is usually slower and requires more memory.

Title: In plain English, what is recursion?


问:
How to handle business rules with a REST API?
I have a REST API to manage a booking system
I'm searching how to manage this situation :

A customer can book a time slot :
A TimeSlot resource is created and linked to a Person resource. In order to create the link between a time lot and a person, the REST client send a POST request on the TimeSlot resource

But if too many people booked the same slot (let's say the limit is 5 links), it must be impossible to create more associations.

How can I handle this business restriction ? Can I return a 404 status code with a JSON response detailing the error with a status code ?

Is it a RESTFul approach ?

<s>EDIT :

Like suggested below I used status 409 Conflict in addition to a JSON response detailing the error</s>

EDIT 2 :

Like detailed in the @Cormac Mulhall, the 403 Forbidden is the most accurate status code for this case

答:
Attention : See the Answer by Cormac Mullhall

404 means resource not found. Using it here would be not appropriate. Because the resource clearly exists, but cannot be manipulated. According to Quick Tips (http://www.restapitutorial.com/lessons/restquicktips.html) 409 Conflict would be a good way to go. You can of course return 200 with error message in the body. The client is still responsible for reading responses and act on them.


答: 404 indicates a resource is not found. A more appropriate response code would be a 409 with a body containing more details if the nature of the conflict. </p>

Title: How to handle business rules with a REST API?

Body:
I have a REST API to manage a booking system
I'm searching how to manage this situation :

A customer can book a time slot :
A TimeSlot resource is created and linked to a Person resource. In order to create the link between a time lot and a person, the REST client send a POST request on the TimeSlot resource

But if too many people booked the same slot (let's say the limit is 5 links), it must be impossible to create more associations.

How can I handle this business restriction ? Can I return a 404 status code with a JSON response detailing the error with a status code ?

Is it a RESTFul approach ?

<s>EDIT :

Like suggested below I used status 409 Conflict in addition to a JSON response detailing the error</s>

EDIT 2 :

Like detailed in the @Cormac Mulhall, the 403 Forbidden is the most accurate status code for this case


答:
Try timing it with:

```<code>for (runs = 0; runs < 100000000; runs++) {
      ;
}
</code>```

The compiler should be recognizing that the value of test is unchanged after each iteration of the loop, and the final value of test is unused, and eliminating the loop entirely.

Body:
Try timing it with:

for (runs = 0; runs < 100000000; runs++) {
      ;
}

The compiler should be recognizing that the value of test is unchanged after each iteration of the loop, and the final value of test is unused, and eliminating the loop entirely.


问:
Best way to deploy database-dependant application
I have always "custom developed" software for clients. This means:

Develop the software

Install SQL Express on client site

Import DB, create DB user, set DB permissions etc.

Install software on client site (multiple pc's)

Voila!

Now, I am looking at deploying your basic "end user" app, to a mass of unknown audience. I.e. your basic app someone will download.

What are the best common methods for deploying an app with a database? I am looking for the classic (one setup app, deploying both app and db) without the user needing to do some technical configs.

I would appreciate some ideas...

答:
Install SQL Express on client site

Import DB, create DB user, set DB permissions etc.

Install software on client site (multiple pc's)

Do you expect the end-user to be savvy enough to install SQLExpress on their own? If not, you might want to look into including it in your installer (or download it from Microsoft when necessary) and have it installed for them as a part of the process. Things to consider: Can the SQLExpress installer run in headless mode? Can you pre-define any installation-required parameters/settings so that the user doesn't have to worry? Is the SQLExpress installer scriptable? If they already have SQLExpress installed, can you handle it if their installation configuration is different from how you would do it (You might want to give them the option of pointing your installer at an existing instance of SQLExpress and using that if you can)? Does it have to be SQLExpress? What if they have SQL Server (will you really make them install SQLExpress if they already have MS SQL Server)?

The second step shouldn't be hard. You should already have all of the appropriate DDLs and DMLs and once SQLExpress has a minimal working setup, you should be able to execute your DDL and DML statements to get your database up to a good starting point. Again, your installer process will need to be able to do this in the background.

The third point should already be covered by whatever you're currently doing, but it should be the last step in your general installer after these other steps have succeeded.

I've worked on a desktop application before that required the user to install SQLExpress, but the DB set up and post-install config was done via scripts. Future updates to the database (such as schema changes and reference data DML) were handled through a separate "DB Update" application that just ran SQL scripts.

Every scenario is going to be a little different, but I hope this gives you enough info...