答:
I separate Users/Profiles from Authentication on my apps. This might be an approach you can use. Especially if in the future you think you might add twitter or other authentication providers to your system.

Basically I create a table called Credentials that stores the unique UserID in my system and the Unique id the provider gives. Email is not good because the user might change their email with the provider. Facebook provides a unique ID for each user in their token.

When a user authenticates, I look for the matching provider ID in the credentials table. (Don't forget to record which provider because otherwise you might find a match for a twitter login when the user logged in with facebook). Finally, I grab the matching User in my system who has the same UserId as the credential record.

There aren't that many steps in reality I was just spelling it out. In truth I just need one query

```<code>select U.* from Users u
inner join Credentials on
u.userId=Credentials.userId
where Credentials.ProviderId =?
and Credentials.Provider=?
</code>```

System stored username and password of course would look different. But you already know how to handle that.

Regarding requiring a separate login even when the user comes through facebook. Please do not do that...that is the most irritating thing to me as a user when I'm given the option to login through facebook and the system still requires me to create a password. I've left sites in the middle of registering for that very reason.

Title: Using Facebook to authenticate, how to link to user record in my app? Email?

Body:
I'm using Facebook to authenticate users. We also have conventional username/ password login and registration form too. Anyway, when a user chooses to login with Facebook, we use the following procedure:

Redirect to Facebook, user is authenticated, returneded from Facebook to the app - email, name, facebook ID etc is provided from FB .. but ofcourse, no password

We look in our system for any existing user by the email address. If a user is found, then that is the currently logged in user; otherwise, create a new user with the user info returned from FB.

Email kinda makes sense as we don't want duplicate email addresses (also the database currently won't allow it due to unique index) so if a user has signed up already with that email address, it won't attempt to create a new user for them. Instead it will pull the previously registered user.

Is this the sound approach though? Exploring all possibilities, I was wondering what happens in the event that the user tries to register by our conventional registration form, but as they have already created an account with that email from their initial Facebook login, we wouldn't allow the duplicate email. So having made the decision to use their Facebook to login, they are stuck with that method. Is this a common/ok approach?

Also without intention, if they use the conventional registration form first, and setup their account that way, we have their password, so they could login using our form or login with FB and the user account will just be pulled by email. However, if they choose to login with FB first time, and their account is created that way (we won't obtain the pw), they must always use FB only. I've absolutely no idea whether this could be problematic or not, I kinda want to go with the option of - whatever means you chose to login/register first time round - then that's what you stick with :)

I'm a little new to having users sign up with multiple logins so heads a bit full of "what ifs" etc. Would appreciate any advise on this, and common approaches. Thanks

Alternatively, we loose the index on the email field, add a field somewhere to store the facebook ID, and at the application level decide whether to permit duplicate email address and more distinction between users of different login methods (therefor allowing a user to have a conventionally registered user account, and/or a seperate facebook login auth/created user account, both with the same email address - but different methods of login - least if the user deletes their Facebook account, they can create an account with their email through our register form)

Body:
I separate Users/Profiles from Authentication on my apps. This might be an approach you can use. Especially if in the future you think you might add twitter or other authentication providers to your system.

Basically I create a table called Credentials that stores the unique UserID in my system and the Unique id the provider gives. Email is not good because the user might change their email with the provider. Facebook provides a unique ID for each user in their token.

When a user authenticates, I look for the matching provider ID in the credentials table. (Don't forget to record which provider because otherwise you might find a match for a twitter login when the user logged in with facebook). Finally, I grab the matching User in my system who has the same UserId as the credential record.

There aren't that many steps in reality I was just spelling it out. In truth I just need one query

select U.* from Users u
inner join Credentials on
u.userId=Credentials.userId
where Credentials.ProviderId =?
and Credentials.Provider=?

System stored username and password of course would look different. But you already know how to handle that.

Regarding requiring a separate login even when the user comes through facebook. Please do not do that...that is the most irritating thing to me as a user when I'm given the option to login through facebook and the system still requires me to create a password. I've left sites in the middle of registering for that very reason.


问:
Software License question
I am building some software which I am storing on Github (public).

Is it possible to change the license so that I can sell my software at some later point in time, as long as no one has contributed to my project?

I am fine for people to see or use my code, but when it gets to a critical point I want to pull it from Github and just have my own product which I can do as I please.

答:
Yes and no.

If you change the license on Github, then anyone who grabs that copy of your software is bound to the new license. The caveat is that anyone who had previously grabbed a copy of your source code are bound to the old license.

If you have an idea of which license or restrictions you want to place, it would be better to do it now. It's less of a headache going from a restrictive license to a less-restrictive license than the other way around.

ContentLicense: CC BY-SA 3.0

Title: Software License question


问:
Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far

答:
I agree that it depends on the language you're using to some extent; code tends to look neater when your symbol names follow the same formatting regimen as the language's built-ins and stock libraries.

But where there's a choice, I prefer underscores to camel case, for one simple reason: I find that style easier to read. Here's an example: which do you find more readable? This:

```<code>aRatherLongSymbolName
</code>```

or this:

```<code>a_rather_long_symbol_name
</code>```

I find the underscore version much easier to read. My brain can ignore the underscores much more easily than it can detect the lowercase/uppercase boundaries in camel case, especially where the boundaries are between glyphs that look similar to other glyphs of the opposite case, or numerals (I/l, O/0, t/I, etc). For example, this boolean variable stores a value indicating whether or not an Igloo has been built with proper planning permission (undoubtedly a common use case for us all):

```<code>isIllicitIgloo
</code>```

I find this version a lot easier to read:

```<code>is_illicit_igloo
</code>```

Perhaps even worse than a hard-to-read symbol name is an easy-to-misread symbol name. Good symbol names are self-documenting, which to me means that you should be able to read them and understand their meaning at a glance. (I'm sure we all read code print-outs in bed for pleasure, but occasionally we grok in haste, too.) I often find with camel case symbol names that it's easy to mis-read them and get the wrong impression of a symbol's semantics.

ContentLicense: CC BY-SA 2.5

Body:
I agree that it depends on the language you're using to some extent; code tends to look neater when your symbol names follow the same formatting regimen as the language's built-ins and stock libraries.

But where there's a choice, I prefer underscores to camel case, for one simple reason: I find that style easier to read. Here's an example: which do you find more readable? This:

aRatherLongSymbolName

or this:

a_rather_long_symbol_name

I find the underscore version much easier to read. My brain can ignore the underscores much more easily than it can detect the lowercase/uppercase boundaries in camel case, especially where the boundaries are between glyphs that look similar to other glyphs of the opposite case, or numerals (I/l, O/0, t/I, etc). For example, this boolean variable stores a value indicating whether or not an Igloo has been built with proper planning permission (undoubtedly a common use case for us all):

isIllicitIgloo

I find this version a lot easier to read:

is_illicit_igloo

Perhaps even worse than a hard-to-read symbol name is an easy-to-misread symbol name. Good symbol names are self-documenting, which to me means that you should be able to read them and understand their meaning at a glance. (I'm sure we all read code print-outs in bed for pleasure, but occasionally we grok in haste, too.) I often find with camel case symbol names that it's easy to mis-read them and get the wrong impression of a symbol's semantics.


问:
How do you write tests for methods that interact with data in system files?
I'm trying to be proactive about writing an iOS app in a test-driven manner. However, I'm stumped as to how to test a method that is to interact with real system files. For those familiar with iOS, I'm writing to the NSUserDefaults file.

Here's my set-up: I have a singleton called AppState that I am using to record when data downloaded from the Internet was last synced locally. Other classes can update the dateLastSynced property of AppState. I am overriding the setDateLastSynced method to save that update to the system so it's persisted between opening and closing the app:

```<code>- (void)setDateLastSynced:(NSDate *)dateLastSynced
{
    // update instance variable with new value
    _dateLastSynced = dateLastSynced;

    // store change to NSUserDefaults
    [[NSUserDefaults standardUserDefaults] setObject:dateLastSynced forKey:APP_STATE_DATE_LAST_SYNCED_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
</code>```

I'd like to write a test that verifies that setDateLastSynced is working correctly - but I'm not sure how to do that without overwriting data already saved to the system in NSUserDefaults.

答:
You have to mock or emulate, and you have two very good reasons to do so.

You have to mock or emulate whatever parts of the system your code interacts with, precisely because:

You don't want to alter the system, and

You don't want your tests to depend on something as uncontrollable as the system.

 Yes, your emulation will not be perfect; yes, you will in fact be modelling your knowledge and assumptions about how the system works; and that's perfectly fine. You are essentially taking a spec and restating it in code: nothing wrong with that. The spec in this case is written by the creators of the operating system and not by you.

You have to mock or emulate everything that deals with time, even your own stuff.

You have to be able to set the emulated clock time to a certain fake date, pretend that files are created/modified, and then check their creation/modification date and make sure it is the fake date, and all this without of course changing the system clock.

You also have to be able to check that a certain date in the future is correctly set, or that something happens at that moment in time, all during the execution of a single test, without having to wait for real time to advance.


问:
worst case comparisons for special case insertion sort
Consider an Insertion Sort with a Sentinel on n values, where every value occurs exactly
twice in the input (so n must be even).
So the best case input for comparisons is when the elements are already sorted and the exact number of comparisons in the best case is n-1.
I believe the worst case input for comparisons is when the elements are reverse sorted. But what is the exact number of comparisons in this case? and why?</p>

答:
First, let's walk through the best case. You have n elements. The first one you skip because there's nothing before it to compare against, so there are only n-1 elements that might need to be moved. If an element does not need to be moved to the left, then we learn that after only one comparison. So if no elements need to be moved to the left (because the array is already sorted), then only 1 times n-1 comparisons are needed, hence n-1 total.

Now, if the array is reverse sorted, that means every element needs to be moved all the way to the left end of the array. We skip the 1st element as usual, so 0 comparisons there. The 2nd element moves 1 time after 1 comparison, the 3rd element moves 2 times after 2 comparisons, the 4th element moves 3 times after 3 comparisons...and so on. The nth element always requires n-1 comparisons to move all the way to the left. Thus the total number of comparisons for all n elements is 0+1+2+3+...+n-1, which summation formulas tell us is (n-1)((n-1)+1)/2 = (n-1)(n/2) comparisons, or alternatively O(n^2).

You are correct in believing that this scenario is a worst case for insertion sort. The algorithm's outer loop can never have more than n iterations, and the ith inner loop can never have more than i iterations because we decrement j each time, so you end up with 0+1+2+3+...+n-1 as the maximum possible number of iterations of the inner loop for the whole algorithm (and the only comparison we care about is the one performed by an inner loop iteration). We could also try to sketch a proof that this is the only worst case scenario for insertion sort, but I'll leave that as an exercise for now.


问:
Organizing C++ Components
In my current company we've brought the discussion about how to organize most of our different C++ components considering the following requirements:

There might be interdependencies between components

Components with very specific/obscure third party dependencies are not included in this exercise

Not every project needs every component, just a small subset of them

There are basically two schools of thought (at least within the company) as to how to organize all of the components:

The first one believes we should group all of the components together in a massive library (which can be composed of more than one shared object and allows linking to what a project needs, but in terms of installation and compilation it's everything together).

The second one believes we should create a library per component and maintain them totally separately (each of them installed separately and including as many shared objects as they need).

I can see many cons and pros to both approaches and personally I don't believe any of them is right or wrong, but I'd like to get a bit more insight from those who have experienced with both approaches and can support with facts the use of one approach over the other.

Edit: being more specific about the concerns.

How would you manage the version dependencies between a "many small libraries" approach?

How do you avoid having a mess of interdependencies between objects when having a massive library approach?

What kinds of performance issues would each approach cause in both windows and linux systems, when statically or dynamically linking? What kinds of benefits?

Any other comment that could be helpful in deciding what approach to follow?

答: At our company, the dividing line between approach one and approach two comes down to the external dependencies of the component(s). For instance, we have hundreds of "core" components with no dependencies whatsoever, and those are grouped into only a single library. On the other hand, the one component that we use to talk to a specific type of database gets its own library. Similarly, we have a library for our internal service framework, a library for our internal logging framework, and so on, since those libraries depend on the frameworks being installed on the target machines.

Title: Organizing C++ Components


问:
What does "issue or start an instruction" mean?
From Section 2.1.3 RISC vs CISC from Structured Computer Organization by Tanenbaum,

While the initial emphasis was on simple instructions that could be
  executed quickly, it was soon realized that designing instructions that  could be issued (started) quickly was the key to good
  performance. How long an instruction actually took mattered less
  than how many could be started per second.

what does "issue or start an instruction" mean? Does it refer to step 1, 2, 3, 4 and 5 in the fetch-decode-execute cycle?

Does "execute an instruction" mean only step 6 in the fetch-decode-execute cycle ?

Thanks.

Note:

The CPU executes each instruction in a series of small steps. Roughly
  speaking, the steps are as follows:

Fetch the next instruction from memory into the instruction register.

Change the program counter to point to the following instruction.

Determine the type of instruction just fetched.

If the instruction uses a word in memory, determine where it is.

Fetch the word, if needed, into a CPU register.

Execute the instruction.

Go to step 1 to begin executing the following instruction.

This sequence of steps is frequently referred to as the
  fetch-decode-execute cycle.

答:
What does "issue or start an instruction" mean?

In the context of what's written, it should mean the amount of time between when the CPU can start the process of handling one instruction and when it can do the same for the one that follows.  If that explanation sounds vague, the reason is that it's going to vary a lot by architecture.

Say you have some instructions to run on a fictional CPU with numbered registers where fetch and decode (F&D) always takes three units of time and execution takes ten:

```<code>ADD  R1, R2    ; R1 ← R1 + R2
LOAD R3, 0     ; R3 ← 0
LSR  R4, 3     ; R4 ← R4 shifted 3 bits to the right
</code>```

On a simplistic design that doesn't parallelize anything, the total time to run this snippet of code is 39 units: 3+10 (F&D plus execute) for the ADD, 3+10 for the LOAD and 3+10 for the LSR.

At some point, CPU designers noticed their chips had hardware that sat idle while instructions executed and figured out that nothing was stopping from from using it to execute later instructions that weren't dependent on the outcome of those that came before.  In the example above, none of the instructions have anything in common with the others.  All of the registers involved are unique, as are what the instructions do.  (For the sake of simplicity, let's say ADD, LOAD and LSR all use different hardware to execute.)  This means they can all go through the execution phase in parallel without producing the wrong results.

Three instructions executing in perfect, not-of-this-world parallel would take a total of 13 units of time, a 66% time savings over the non-parallelized CPU.  That's quite an improvement until the real world intrudes and you realize that you can't do all of the F&D phase in parallel because you'd have no idea if the LOAD instruction is going to use the same registers as the ADD above it.  To prevent that, F&D must be done serially.  Once you've determined that it doesn't depend on anything prior, you can send it off for execution and go F&D the next one.

The first instruction takes three units for F&D and then is sent somewhere else in the processor to be executed.  Then the second F&D can go ahead for another three time units and then the third for the same.  At that point, we've spent nine units of time on F&D.  Because the third instruction was the last to be decoded, we have to wait another ten units after that for it to execute.  That means the last instruction will finish executing 19 time units after F&D starts on the first one.  That's still a not-too-shabby savings of 51% over doing everything serially.

When you're able to execute a lot of instructions in parallel, how long the instructions take to execute becomes a bit less relevant than how long it takes to start (issue) them.  Start time has become more critical because every unit of time spent evaluating whether or not an instruction can be executed is time the execution hardware won't be busy.  If the designers of our fictitious CPU find a way to cut a time unit out of that phase, the total time for the three instructions in the example drops from 19 to 16, which is nothing to sneeze at.  Chop out one more and you're down to 13.

Does "execute an instruction" mean only step 6 in the fetch-decode-execute cycle ?

For the purposes of this discussion, it would be reasonable to say it means using the hardware in the CPU to carry out the instruction's wishes.

Body:
What does "issue or start an instruction" mean?

In the context of what's written, it should mean the amount of time between when the CPU can start the process of handling one instruction and when it can do the same for the one that follows.  If that explanation sounds vague, the reason is that it's going to vary a lot by architecture.

Say you have some instructions to run on a fictional CPU with numbered registers where fetch and decode (F&D) always takes three units of time and execution takes ten:

ADD  R1, R2    ; R1 ← R1 + R2
LOAD R3, 0     ; R3 ← 0
LSR  R4, 3     ; R4 ← R4 shifted 3 bits to the right

On a simplistic design that doesn't parallelize anything, the total time to run this snippet of code is 39 units: 3+10 (F&D plus execute) for the ADD, 3+10 for the LOAD and 3+10 for the LSR.

At some point, CPU designers noticed their chips had hardware that sat idle while instructions executed and figured out that nothing was stopping from from using it to execute later instructions that weren't dependent on the outcome of those that came before.  In the example above, none of the instructions have anything in common with the others.  All of the registers involved are unique, as are what the instructions do.  (For the sake of simplicity, let's say ADD, LOAD and LSR all use different hardware to execute.)  This means they can all go through the execution phase in parallel without producing the wrong results.

Three instructions executing in perfect, not-of-this-world parallel would take a total of 13 units of time, a 66% time savings over the non-parallelized CPU.  That's quite an improvement until the real world intrudes and you realize that you can't do all of the F&D phase in parallel because you'd have no idea if the LOAD instruction is going to use the same registers as the ADD above it.  To prevent that, F&D must be done serially.  Once you've determined that it doesn't depend on anything prior, you can send it off for execution and go F&D the next one.

The first instruction takes three units for F&D and then is sent somewhere else in the processor to be executed.  Then the second F&D can go ahead for another three time units and then the third for the same.  At that point, we've spent nine units of time on F&D.  Because the third instruction was the last to be decoded, we have to wait another ten units after that for it to execute.  That means the last instruction will finish executing 19 time units after F&D starts on the first one.  That's still a not-too-shabby savings of 51% over doing everything serially.

When you're able to execute a lot of instructions in parallel, how long the instructions take to execute becomes a bit less relevant than how long it takes to start (issue) them.  Start time has become more critical because every unit of time spent evaluating whether or not an instruction can be executed is time the execution hardware won't be busy.  If the designers of our fictitious CPU find a way to cut a time unit out of that phase, the total time for the three instructions in the example drops from 19 to 16, which is nothing to sneeze at.  Chop out one more and you're down to 13.

Does "execute an instruction" mean only step 6 in the fetch-decode-execute cycle ?

For the purposes of this discussion, it would be reasonable to say it means using the hardware in the CPU to carry out the instruction's wishes.


问:
Is it better to call a function multiple times, or to assign a variable multiple times and call the function once?
Is it better to write

```<code>if (condition) {
    do_something(0);
} else if (other_condition) {
    do_something(1);
} else {
    do_something(2);
}
</code>```

or

```<code>int variable;
if (condition) {
    variable = 0;
} else if (other_condition) {
    variable = 1;
} else {
    variable = 2;
}
do_something(variable);
</code>```

?

I prefer the latter, because you only <s>call the function</s> write the function once, but it takes up more lines of code and will grow rapidly for functions with large numbers of arguments.

答:
Use whichever one you think is more readable and maintainable. Depending on the language, variables and function calls involved, either one might be preferable. If I had to evaluate your two examples in isolation, I would have a slight preference for the second version because it makes it a little more obvious that do_something() only gets called once.

But in the context of the rest of your codebase, some "litmus test" questions like these may help with evaluating those criteria:

Is it more intuitive to say "if [condition] is true, [variable] should be 1" or "if [condition] is true, we should do_something(1)"?

Does the value of [variable] have a meaning of its own, or is it only meaningful as an argument to do_something()?

When this block of code has to change in the future, is it more likely that the branches will end up assigning different values to the variable(s), or that the branches will end up calling different functions?

What are the odds we'll ever want to call do_something() more than once in this block of code?

Will it ever make sense to move this branching logic inside of do_something(), rendering this entire question pointless?

How complicated could [condition] and [other_condition] potentially become?


答:
Imagine a concrete example of a code which, given a price of an item, should call a method while specifying if the item is a rebate (price inferior to zero), a paid product (price superior to zero) or a free product (price equal to zero).

Your two pieces of code become:

Solution 1:

if (price < 0)
{
    this.DoSomething(PriceType.Rebate);
}
else if (price > 0)
{
    this.DoSomething(PriceType.Product);
}
else // price == 0
{
    this.DoSomething(PriceType.Free);
}
```

<p><strong>Solution 2:</strong></p>

<pre class="lang-cs prettyprint-override"><code>priceType = PriceType.Free;

if (price < 0)
{
    priceType = PriceType.Rebate;
}
else if (price > 0)
{
    priceType = PriceType.Product;
}

this.DoSomething(priceType);
</code>```

The second solution, as is, has less lines (10 versus 12), despite your assertion that "it takes up more lines of code", but the first one looks more readable. On the other hand, the second solution can be refactored to become much more readable:

Refactoring of solution 2:

private PriceType FindPriceType(price)
{
    if (price < 0)
    {
        return PriceType.Rebate;
    }
    else if (price > 0)
    {
        return PriceType.Product;
    }

    return PriceType.Free;
}

...

this.DoSomething(this.FindPriceType(price));
```

<p>By separating the original method into two methods, the code becomes more readable through the introduction of an explicit name of the method.</p>

<p>There are also two specific cases where the second solution allows even more benefits:</p>

<h2>Specific cases</h2>

<p>The first case is the one where <em>all</em> conditions have the form: <code>if (something == value)</code>. For instance:</p>

<pre class="lang-cs prettyprint-override"><code>if (priceType == 1)
{
    return PriceType.Rebate;
}

if (priceType == 2)
{
    return PriceType.Product;
}

if (priceType == 3)
{
    return PriceType.Free;
}

throw new NotImplementedException();
</code>```

can be transformed into a much shorter:

var map = {
    1: PriceType.Rebate,
    2: PriceType.Product,
    3: PriceType.Free
}[priceType];
```

<p>A second specific case is where you have not three branches, but only one <code>if/else</code>. Example:</p>

<p><strong>Solution 1:</strong></p>

<pre class="lang-cs prettyprint-override"><code>if (price < 0)
{
    this.DoSomething(PriceType.Rebate);
}
else
{
    this.DoSomething(PriceType.Product);
}
</code>```

Solution 2:

priceType = PriceType.Product;

if (price < 0)
{
    return PriceType.Rebate;
}

this.DoSomething(priceType);
```

<p>Here, the second solution can (in many languages) be transformed into a one-liner:</p>

<pre class="lang-cs prettyprint-override"><code>this.DoSomething(price < 0 ? PriceType.Rebate : PriceType.Product);
</code>```

Title: Is it better to call a function multiple times, or to assign a variable multiple times and call the function once?

Body:
Is it better to write

```<code>if (condition) {
    do_something(0);
} else if (other_condition) {
    do_something(1);
} else {
    do_something(2);
}
</code>```

or

```<code>int variable;
if (condition) {
    variable = 0;
} else if (other_condition) {
    variable = 1;
} else {
    variable = 2;
}
do_something(variable);
</code>```

?

I prefer the latter, because you only <s>call the function</s> write the function once, but it takes up more lines of code and will grow rapidly for functions with large numbers of arguments.

Body:
Imagine a concrete example of a code which, given a price of an item, should call a method while specifying if the item is a rebate (price inferior to zero), a paid product (price superior to zero) or a free product (price equal to zero).

Your two pieces of code become:

Solution 1:

if (price < 0)
{
    this.DoSomething(PriceType.Rebate);
}
else if (price > 0)
{
    this.DoSomething(PriceType.Product);
}
else // price == 0
{
    this.DoSomething(PriceType.Free);
}

Solution 2:

priceType = PriceType.Free;

if (price < 0)
{
    priceType = PriceType.Rebate;
}
else if (price > 0)
{
    priceType = PriceType.Product;
}

this.DoSomething(priceType);

The second solution, as is, has less lines (10 versus 12), despite your assertion that "it takes up more lines of code", but the first one looks more readable. On the other hand, the second solution can be refactored to become much more readable:

Refactoring of solution 2:

private PriceType FindPriceType(price)
{
    if (price < 0)
    {
        return PriceType.Rebate;
    }
    else if (price > 0)
    {
        return PriceType.Product;
    }

    return PriceType.Free;
}

...

this.DoSomething(this.FindPriceType(price));

By separating the original method into two methods, the code becomes more readable through the introduction of an explicit name of the method.

There are also two specific cases where the second solution allows even more benefits:

Specific cases

The first case is the one where all conditions have the form: if (something == value). For instance:

if (priceType == 1)
{
    return PriceType.Rebate;
}

if (priceType == 2)
{
    return PriceType.Product;
}

if (priceType == 3)
{
    return PriceType.Free;
}

throw new NotImplementedException();

can be transformed into a much shorter:

var map = {
    1: PriceType.Rebate,
    2: PriceType.Product,
    3: PriceType.Free
}[priceType];

A second specific case is where you have not three branches, but only one if/else. Example:

Solution 1:

if (price < 0)
{
    this.DoSomething(PriceType.Rebate);
}
else
{
    this.DoSomething(PriceType.Product);
}

Solution 2:

priceType = PriceType.Product;

if (price < 0)
{
    return PriceType.Rebate;
}

this.DoSomething(priceType);

Here, the second solution can (in many languages) be transformed into a one-liner:

this.DoSomething(price < 0 ? PriceType.Rebate : PriceType.Product);


答:
You should keep an eye on two aspects here:

The first one is how components you cannot change are already arranged. Third party components or some legacy components you don't want to change anymore

Components you or your company wrote, which can be merged or split

One of my Best Practices when deciding how to divide any code in packages is to let the progress itself decide how it would be better for me. That means for example you start a game which will need boost, opengl, openal and opencl. Maybe you're thinking of a cool engine component loading resources and so on.

You will surely not start with opencl and GPGPU algorithms or audio, so don't even include opencl/openal in your project at first. You will go that way using boost and opengl to start your project. Then you will might notice that you're using many filesystem operations at different locations in your code and writing too many strings which are appended for filepaths to load. That would be a nice start of your engine, but still don't even try to create bunch of files and folders for components you're not going to implement immediately.

As a conclusion ask every new piece of code if it has a right to exist. Then you'll see that the question of how to organize your components is no question which should be answered at the beginning of any project, but anytime a further component is used in the project.

Title: Organizing C++ Components

Body:
In my current company we've brought the discussion about how to organize most of our different C++ components considering the following requirements:

There might be interdependencies between components

Components with very specific/obscure third party dependencies are not included in this exercise

Not every project needs every component, just a small subset of them

There are basically two schools of thought (at least within the company) as to how to organize all of the components:

The first one believes we should group all of the components together in a massive library (which can be composed of more than one shared object and allows linking to what a project needs, but in terms of installation and compilation it's everything together).

The second one believes we should create a library per component and maintain them totally separately (each of them installed separately and including as many shared objects as they need).

I can see many cons and pros to both approaches and personally I don't believe any of them is right or wrong, but I'd like to get a bit more insight from those who have experienced with both approaches and can support with facts the use of one approach over the other.

Edit: being more specific about the concerns.

How would you manage the version dependencies between a "many small libraries" approach?

How do you avoid having a mess of interdependencies between objects when having a massive library approach?

What kinds of performance issues would each approach cause in both windows and linux systems, when statically or dynamically linking? What kinds of benefits?

Any other comment that could be helpful in deciding what approach to follow?


问:
How do latency and bandwidth form tradeoff?
From Instruction pipelining section in Tanenbaum's Structured Computer Organization:

Pipelining allows a trade-off between latency (how long it takes
  to execute an instruction), and processor bandwidth (how many MIPS
  the CPU has).

With a cycle time of T nsec, and n stages in the pipeline, the
  latency is nT nsec because each instruction passes through n stages, each of which takes T nsec.

Since one instruction completes every clock cycle and there are 10^9/T
  clock cycles/second, the number of instructions executed per second is
  10^9/T. To get the number of MIPS, we have to divide the
  instruction execution rate by 1 million to get (10^9/T)/10^6 = 1000/T
  MIPS.

I think the smaller latency the better, and the bigger bandwidth the better.
Since the two are related as reciprocals, they always move simultaneously in either both good or both bad directions. Then how do the two form tradeoff? Thanks.

答:
They aren't reciprocals. Those equations don't give a complete relationship between latency, MIPS and pipeline stages; in that excerpt they're only being used to define what he means by "latency" and "MIPS" so that his claim about the tradeoff is more precise.

The tradeoff Tanenbaum's referring to is that when you split the CPU's pipeline into more stages, you can execute more instructions in parallel (more bandwidth), but each instruction takes longer to finish because of the added complexity (more latency).


问:
How should I unit test mathematical formulae?
I have a number of functions that are pretty close to the mathematical definition of a function. For example, a simplified version of one of these functions may look like:

```<code>int function foo(int a, int b) {
    return a * b;
}
</code>```

I'd like to unit test them, but I'm not sure what the best way to approach those tests, as these functions have very large ranges for parameter values. Every approach I've come up with feels lacking:

If I test with a discrete pre-defined subset of possible values, I fear the set I choose may not be representative of the whole, leading to a potentially endless cycle of adding new values to the subset every time an unexpected value is found. This seems like defeating the point of having a unit test in the first place.

If I test with a discrete subset of possible values that's randomly determined, I inherit all of the problems of picking the subset manually as well as the real chance that tests will fail randomly every run.

If I test with every possible value (e.g. 0 to 264), the tests will take forever.

My final thought on how to approach the problem was to avoid testing the implementation of the function entirely, either by:

Only testing that the function accepts two integers and returns an integer, or

Not testing the function at all

But if I'm not testing the functions at all—either in practice or in principle—I'm not sure how I can guarantee the correctness of the functions in the case of an eventual refactor.

What is the best way to test functions that have completely deterministic output, but can operate on a large range of possible inputs?

答:
Create one or two typical test cases, and then focus your remaining testing on boundary conditions.

For example, how does your function behave with zeroes?  with ones?  with int.MaxValue?  What are the largest positive or negative numbers that can be used in the function before it overflows or underflows? What happens when an overflow or underflow occurs?

And so forth.


问:
Cheap implementations in fundamental TDD
This is a question concerning the fundamental approach of TDD, so the example below is as simple as possible which might make it seem a little useless; but of course the question applies to more complicated situations as well.

Some colleagues and I are currently discussing and trying out some basic TDD ways of coding.  We came across the questions how to deal with cheap solutions for existing but not encompassing TCs.  In TDD one writes a TC which fails, then implements whatever it takes (and not more!) to let the TC pass.  So the task at hand would be to make the TC green with as little effort as possible.  If this means to implement a solution which uses inside knowledge of the TC, so be it.  The reasoning was that later TCs would check for more general correctness anyway, so that first solution would need to be improved then (and only then).

Example:

We want to write a comparison function for a data structure with three fields.  Our comparison shall return whether the given values are equal in all three fields (or differ in at least one).  Our first written TC only checks if a difference in the two first values is detected properly:  It passes (a,b,c) and (a,b,c) and checks for a correct detection of equality, then it passes (a,b,c) and (x,b,c) and checks for a correct detection of inequality.

Now the cheap approach would be to also implement only a comparison of the first field because this should be enough to pass this TC.  Keep in mind that this can be done because we know that later tests will also check for the equality of the two other fields.

But of course it does not seem very useful to only implement such a (more or less) nonsense solution; every programmer doing this would do it in the knowledge of writing a bug.  It obviously seems more natural to write a decent comparison right away in the first iteration.

On the other hand, writing a correct solution without having a TC which checks it might lead to the situation that such a TC which tests the behaviour more thoroughly will never get written.  So there is behaviour which was written without having a TC for it (i. e. which is not developed test-driven).

Maybe a proper approach is to not write such rudimentary TCs (like the one only checking the first field) in the first place, but that would mean to demand perfect TCs in first iteration (and of course in complexer situations one will probably not always write perfect TCs).

So how should one deal with rudimentary TCs?  Implement a cheap solution or not?

答:
I would like to say that the refactoring phase in the TDD cycle is the second most important step, and the one that make the switch from simpler and cheap to intended code. The most simple example I can think of is a constructor.

My first test can be that my new class receives a certain parameter and check the value of a parameter. That's pretty easy to implement right? I can make it pass very cheaply. But once that it passes the implementation is left to a refactor.

I can implement a getter/setter into that parameter.

Or maybe that my class makes a get request to a external API (mocked) and stores the result into the parameter.

Or that parameter is the result of mat operation.

But all those cases are tested with the premise that you input a value and it expects another, the back workings are irrelevant, you want the same result. That's to me the great advantage of cheap solutions.


答:
The short answer is they aren't related as reciprocals.

Assume you have a very boring CPU with one instruction that takes 1 ns to complete.  Therefore your latency is 1 ns, and your bandwidth is 1 instruction per ns.

Say you add a pipeline stage to split that instruction into fetch and execute phases.  Each of those stages might be able to complete in 0.5 ns, so now you can increase your clock speed, but you can't double it, because you've added the overhead of the pipeline logic.  Also, stages all have to use the same clock, even if one is faster than another.  So maybe you can do a 0.6 ns clock.  Your latency is now increased to 1.2 ns, but your bandwidth has also increased to 1.7 instructions per ns.

The relationship isn't linear, especially when you are already close to the limits of your semiconductor technology, but latency and bandwidth both increase when pipeline stages are added, up to a certain point.

Title: How do latency and bandwidth form tradeoff?

Body:
From Instruction pipelining section in Tanenbaum's Structured Computer Organization:

Pipelining allows a trade-off between latency (how long it takes
  to execute an instruction), and processor bandwidth (how many MIPS
  the CPU has).

With a cycle time of T nsec, and n stages in the pipeline, the
  latency is nT nsec because each instruction passes through n stages, each of which takes T nsec.

Since one instruction completes every clock cycle and there are 10^9/T
  clock cycles/second, the number of instructions executed per second is
  10^9/T. To get the number of MIPS, we have to divide the
  instruction execution rate by 1 million to get (10^9/T)/10^6 = 1000/T
  MIPS.

I think the smaller latency the better, and the bigger bandwidth the better.
Since the two are related as reciprocals, they always move simultaneously in either both good or both bad directions. Then how do the two form tradeoff? Thanks.


问:
Bridging the gap between abstract machines and computer achitectures?
I always feel disconnected between abstract machines (such as Turing machines) and computer architectures (including virtual machines' architectures, Von Neumann's achitecture).
So I would like to know how they are related? How do one influence the other?
References are also appreciated. Thanks.</p>

答: I see the theoretical machines as bridging the gap between real world computation and mathematics. A Turing machine is powerful enough to simulate any real-world architecture or programming language, simple enough to be simulated easily, and, most importantly, simple enough to be the subject of reasonably straightforward mathematical reasoning and proofs.</p>


问:
PHP: A config file in .ini or .php format?
I'm working on a huge CMS system, and I asked myself what configuration format I should use.

There are two common formats for configuration files. The first one is an INI file, containg all the configuration properties. Then you can simply parse this INI file using build in PHP functions. A second option is to use a PHP file containing a regular PHP array with these configuration properties.

Now, it's easier to edit an INI file, but a PHP file give's you more options, for example it allows you to add a function which retrieves one of the configuration options while reading the configuration file.

Note: The PHP configuration file would only contain an array of configuration, no initialization functions or anything. (This is possible of course, but it's not implemented by default)

Now, what is recommend for me to use as configuration file? What is the most common format for a configuration file? Should I go for simplicity with the INI files, or with a more dynamic one using PHP.

One thing to note, this is not for personal usage. I'm planning to release the CMS system soon, and a lot of websites are scheduled already to change to my CMS system.

答:
Try to answer this question individually for each configuration file. A dependency injection container tree is actually also a kind of configuration, but who could change the file? It might only be another developer.

Writing a CMS means there are configuration files like database connection setups and so on, which might be edited by any luser, but they are more computer literate people. Do you think they can handle any "Unexpected T_STRING" messages? Maybe, maybe not. I recommend YAML as configuration format for non-developers in that case. Easy to read and when I create PHP projects with symfony, I can use the configuration component (http://symfony.com/doc/current/components/config/index.html), which produces error messages which everyone understands. You define your parse and validate tree in PHP and if the yaml file cannot be parsed you have your message.

If your configuration is for real luser it might be better to use INI.


问:
Measure and locate areas of similar value in an image
I saw this picture online and wanted to see if I could create an algorithm to give ordinary images an effect like this:
http://justinlivi.net/wp-content/uploads/2011/01/Living_In_Digital.jpg

My idea was to take the input image and first find the largest area of pixels that are within a predefined threshold of similarity (basically are of similar value). Then I take those pixels and form a square containing all of them. After doing that until most of the image is covered in squares, (no overlapping squares) I plan to color the squares based on their values (so that lighter values might be colored white, midtones green, and dark shades purple.

My problem is that I can't find an algorithm to group pixels with similar values. It'd be nice if someone could point me in the right direction or if someone has some comments on my algorithm idea that's fine too.

As a side note, I'm going to make this completely in javascript so whatever method you suggest should preferably be fast and shouldn't require server side code (for example no storing of data for genetic algorithm training)
Thanks in advance!

答: One of the simplest ways to compare color values is to divide a pixel into its color components, then treat those color components as elements defining a point in space, then compare the distance between the various points in space. You can use RGB, HSV, etc as your color components.</p>


答:
It's very important to have reproducible failing or succeeding tests, so forget about any random input approach. Let's say you test the sin(x) function and you know its result is always in the range of [-1,1] and you say you test 100 random numbers then your assertion is mathematically right but what if there is any dirty fast sin(x) implementation which may produce a 1.00000000000001 and your test fails nearly every 1000th run.

Try to find good input parameters:

values producing nice round results

inflection points

relative and absolute borders

Sometimes parametrized functions keep those properties when changing only a specific parameter (for example the zero crossings and a scaling parameter), so also test some odd values.

And reduce boilerplate code with unit test data-providers if available.

Title: How should I unit test mathematical formulae?

Body:
I have a number of functions that are pretty close to the mathematical definition of a function. For example, a simplified version of one of these functions may look like:

```<code>int function foo(int a, int b) {
    return a * b;
}
</code>```

I'd like to unit test them, but I'm not sure what the best way to approach those tests, as these functions have very large ranges for parameter values. Every approach I've come up with feels lacking:

If I test with a discrete pre-defined subset of possible values, I fear the set I choose may not be representative of the whole, leading to a potentially endless cycle of adding new values to the subset every time an unexpected value is found. This seems like defeating the point of having a unit test in the first place.

If I test with a discrete subset of possible values that's randomly determined, I inherit all of the problems of picking the subset manually as well as the real chance that tests will fail randomly every run.

If I test with every possible value (e.g. 0 to 264), the tests will take forever.

My final thought on how to approach the problem was to avoid testing the implementation of the function entirely, either by:

Only testing that the function accepts two integers and returns an integer, or

Not testing the function at all

But if I'm not testing the functions at all—either in practice or in principle—I'm not sure how I can guarantee the correctness of the functions in the case of an eventual refactor.

What is the best way to test functions that have completely deterministic output, but can operate on a large range of possible inputs?


问:
What to do with user stories that depend on horizontal integrations?
How do you handle a user story when it depends on horizontal integrations in an application?

An example would be a user story such as, "I would like to have audio help on the start screen." Let's say that audio help depends on us creating an audio player in our application which would handle audio across multiple screens and may even be a component of another user story such as "I would like to have audio help on the settings screen". I guess what I'm getting at is how to handle architecture in user stories?

What I have considered so far:

have common repeated task in each story

break out architectural and
horizontal pieces into their own stories

just plain don't write

stories for these issues and instead track them independently

答:
A user story is actually some text of your customer. You should split that story into valuable backlogs. If it's hard for you to write them, because they take too much time to be reasonable valued you have to consider a story split. That means you talk to your stakeholder and recompose the user story in more smaller user stories.

The thing is, that scrum is how you use it in your company. The workflow is nearly the same, but there will be many companies which say that a 2 week user story divided into ten 1-day backlogs is okay and other companies say one user story max. 2 days and one backlog not more than 1 day is okay.

In your case, if your user story depends on a component which does not exist yet, you also have to define that component first, don't you? So you have your other user story.


问:
How to handle initial state in an event-driven architecture?
In an event-driven architecture each component only acts when an event is sent through the system.

Imagine a hypothetical car with a brake pedal and a brake light.

The brake light turns on when it receives a brake_on event, and off when it receives a brake_off event.

The brake pedal sends a brake_on event when it is pressed down, and a brake_off event when it is released.

This is all well and good, until you have the situation where the car is turned on with the brake pedal already pressed down. Since the brake light never received a brake_on event, it will stay off - clearly an undesirable situation. Turning the brake light on by default only reverses the situation.

What could be done to resolve this 'initial state problem'?

EDIT: Thank you for all the responses. My question was not about an actual car. In cars they solved this problem by continuously sending the state - therefore there is no startup issue in that domain. In my software domain, that solution would use many unnecessary CPU cycles.

EDIT 2: In addition to @gbjbaanb's answer, I'm going for a system in which:

the hypothetical brake pedal, after initialization, sends an event with its state, and

the hypothetical brake light, after initialization, sends an event requesting a state event from the brake pedal.

With this solution, there are no dependencies between components, no race conditions, no message queues to go stale, and no 'master' components.

答:
What you need is a broadcast event and message inboxes. A broadcast is a message that is published to an unspecified number of listeners. A component can subscribe for broadcast events so it only receive events that it is interested in. This provides decoupling, as the sender doesn't need to know who the receivers are. The subscription table needs to be statically configured during component installation (instead of when the is initialized). The inbox is a part of the message router that acts as a buffer to hold messages when the destination component is offline.

Using invoices brings one problem, which is inbox size. You don't want the system to have to retain a growing number of messages for components that will never be online anymore. This is important especially with embedded system with strict memory constraints. To overcome inbox size limit, all broadcasted messages need to follow a few rule. The rules are:

every broadcast events requires a name

at any given time, the sender of a broadcast event can only have one active broadcast with a specified name

the effect caused by the event must be idempotent

The broadcast name needs to be declared during component installation time. If a component sends a second broadcast with the same name before the receiver processes the previous one, the new broadcast overwrites the previous one. Now you can have a static inbox size limit, which can be guaranteed to never exceed a certain size and can be precalculated based on the subscription tables.

Finally, you also need a broadcast archive. The broadcast archive is a table that holds the last event from each broadcast name. New components that are just installed will have its inbox prepopulated with messages from the broadcast archive. Like the message inbox, the broadcast archive can also have static size.

Additionally, to deal with situation where the message router itself is offline, you also need message outboxes. The message outbox is part of the component that holds outgoing message temporarily.


问:
Using XML as data storage
I was thinking about the XML format and the following quote:

“XML is not a database. It was never meant to be a database. It is never going to be a database. Relational databases are proven technology with more than 20 years of implementation experience. They are solid, stable, useful products. They are not going away. XML is a very useful technology for moving data between different databases or between databases and other programs. However, it is not itself a database. Don't use it like one.“ -Effective XML: 50 Specific Ways to Improve Your XML by Elliotte Rusty Harold (page 230, Part 4, Item 41, 2nd paragraph)

This seems to really stress that XML should not be used for data storage and should only be used for program to program interoperability.

Personally, I disagree and .NET's app.config file that's used to store a program's settings is an example of data storage in an XML file. However for databases rather than configurations etc XML should not be used.

To develop my point, I will use two examples:

A) Data about customers with fields that are all on one level i.e. there are a number of fields all relating to one customer with no children

B) Data about configuration of an application where nested fields and properties make a lot of sense

So my question is, Is this still a valid statement and is it now acceptable to store data using XML?

EDIT: I've sent an email to the author of that quote to ask for his input/extra context.

答:
I agree that it's not a relational database.  I think the author is simply saying in the quote not to use it as one.

Having said that though you may or may not need one.  If you don't really need to do much querying on the data, and only intend to store it and then fetch it later based on some limited query criteria then you need XML DOCUMENT storage and retrieval - not a relational database.

There are plenty of applications which simply need to store a document with data in it for retrieval in whole later.  If this is the case then it's useless to create a SQL based schema, parse the XML, and then serialize it to the database only to do just the reverse later.  There is a lot of code overhead potentially involved in doing that.  There is less though if you do it right.

You can use ORM tools like Hibernate and tools like Apache Axis in order to autogenerate practically all the code you'd need to build a service which just handles simple CRU operations.  You'd have to wrap that in authentication of course, and possibly might want to segregate the data based on the user, level of access, etc.  You may even want to limit which operations a given user is allowed to do via SOAP service for example.

In this sense you're doing more like content management than anything else.

Title: Using XML as data storage


答: What you have sounds like what is known as an Epic.  This is basically a user story that is too large to be implemented, tested and accepted in a single sprint.  This should typically be the starting point to go back to the customer and try to derive more details and specifics around what they want.  You should be doing this as a regular part of your backlog grooming, identify stories that are too large or too broad and figure out how they can be split into smaller chunks.</p>

Title: What to do with user stories that depend on horizontal integrations?

Body:
How do you handle a user story when it depends on horizontal integrations in an application?

An example would be a user story such as, "I would like to have audio help on the start screen." Let's say that audio help depends on us creating an audio player in our application which would handle audio across multiple screens and may even be a component of another user story such as "I would like to have audio help on the settings screen". I guess what I'm getting at is how to handle architecture in user stories?

What I have considered so far:

have common repeated task in each story

break out architectural and
horizontal pieces into their own stories

just plain don't write

stories for these issues and instead track them independently


问:
What is the difference between ref and out in runtime?
C# provides the ref and the out keyword to make arguments to be passed by reference. The semantic of the two is very similar. The only difference is in the initialization of the flaged variable:

ref requires the variable to be initialized before passing it to the function, out does not.

out requires the variable to be initialized inside the function, ref does not.

The use cases of these two keywords are also almost the same, and their too frequent usage is I beleive considered a code smell (although there are valid use cases like the TryParse and TryGetValue patterns).

Because of this could someone explain, why there are two very similar tools in C# for so narrow use cases?

Also, on MSDN, it is stated that they have different run-time behavior:

Although the ref and out keywords cause different run-time behavior, they are not considered part of the method signature at compile time.

How is their run-time behavior different?

Conclusion

Both answers looks correct, thank you both. I accepted jmoreno's because it is more explicit.

答:
Runtime? Absolutely none.  You can't overload a method with the same parameters differing only by ref or out keyword.

Try to compile this and you'll get a compile error "Method with same signature is already declared":

```<code>    private class MyClass
    {
        private void DoSomething(out int param)
        {
        }
        private void DoSomething(ref int param)
        {
        }
    }
</code>```

To answer this question:
 "...why there are two very similar tools in C# for so narrow use cases?"

From a code readability and API standpoint there is a huge difference.  As a consumer of the API I know that when "out" is used the API does not depend on the out parameter.  As the API developer I prefer the "out" and use "ref" only when absolutely (RARELY!) necessary.  See this reference for a great discussion:

https://stackoverflow.com/questions/1516876/when-to-use-ref-vs-out

Supporting info:  I compiled the following method and disassembled it.  I used the ref and out keywords (out in this example), but the assembly code did not change except for an address reference as I would expect:

```<code>    private class MyClass
    {
        internal void DoSomething(out int param)
        {
            param = 0;
        }
    }
</code>```

00000000  push        ebp

00000001  mov         ebp,esp

00000003  push        edi

00000004  push        esi

00000005  push        ebx

00000006  sub         esp,34h

00000009  xor         eax,eax

0000000b  mov         dword ptr [ebp-10h],eax

0000000e  mov         dword ptr [ebp-1Ch],eax

00000011  mov         dword ptr [ebp-3Ch],ecx

00000014  mov         dword ptr [ebp-40h],edx

00000017  cmp         dword ptr ds:[008B1710h],0

0000001e  je          00000025

00000020  call        6E6B601E

00000025  nop

                param = 0;

00000026  mov         eax,dword ptr [ebp-40h]

00000029  xor         edx,edx

0000002b  mov         dword ptr [eax],edx

            }

0000002d  nop

0000002e  lea         esp,[ebp-0Ch]

00000031  pop         ebx

00000032  pop         esi

00000033  pop         edi

00000034  pop         ebp

00000035  ret

Am I reading the assembly correctly?

Body:
Runtime? Absolutely none.  You can't overload a method with the same parameters differing only by ref or out keyword.

Try to compile this and you'll get a compile error "Method with same signature is already declared":

    private class MyClass
    {
        private void DoSomething(out int param)
        {
        }
        private void DoSomething(ref int param)
        {
        }
    }

To answer this question:
 "...why there are two very similar tools in C# for so narrow use cases?"

From a code readability and API standpoint there is a huge difference.  As a consumer of the API I know that when "out" is used the API does not depend on the out parameter.  As the API developer I prefer the "out" and use "ref" only when absolutely (RARELY!) necessary.  See this reference for a great discussion:

https://stackoverflow.com/questions/1516876/when-to-use-ref-vs-out

Supporting info:  I compiled the following method and disassembled it.  I used the ref and out keywords (out in this example), but the assembly code did not change except for an address reference as I would expect:

    private class MyClass
    {
        internal void DoSomething(out int param)
        {
            param = 0;
        }
    }

00000000  push        ebp

00000001  mov         ebp,esp

00000003  push        edi

00000004  push        esi

00000005  push        ebx

00000006  sub         esp,34h

00000009  xor         eax,eax

0000000b  mov         dword ptr [ebp-10h],eax

0000000e  mov         dword ptr [ebp-1Ch],eax

00000011  mov         dword ptr [ebp-3Ch],ecx

00000014  mov         dword ptr [ebp-40h],edx

00000017  cmp         dword ptr ds:[008B1710h],0

0000001e  je          00000025

00000020  call        6E6B601E

00000025  nop

                param = 0;

00000026  mov         eax,dword ptr [ebp-40h]

00000029  xor         edx,edx

0000002b  mov         dword ptr [eax],edx

            }

0000002d  nop

0000002e  lea         esp,[ebp-0Ch]

00000031  pop         ebx

00000032  pop         esi

00000033  pop         edi

00000034  pop         ebp

00000035  ret

Am I reading the assembly correctly?


问:
SOA: Make each level of a service stack a package (NuGet etc.)?
Say I have a service that has the following hierarchy:

Controller

Business Logic

Data Adapter

All of these make up a service that presents an HTTP API that can be used by other services. Together these layers form a functional piece of an application.

Does it make sense to package each of these layers together as 1 versioned unit? Or to package each individualy with its own version and then consume eachother as a package dependency using NuGet for example. Controller consumes the business logic package which in turn consumes the data adapter package.

Would there be any benefit over the other?

Essentially what I'm asking is should packages be left for shared code across many services/applications or should the guts of a service also use packages to manage its internal dependencies in its own stack?

答:
If you will have other "UIs" (the web service can be thought of as the ui part of your application) then it may make sense to package the BL and DAL as one package and have your service (and other UIs) consume it.  Otherwise its easier to treat everything as a single unit.

You might also consider if you will deploy new versions of the service while leaving the one ones running as separate applications as well. In that case you have multiple UIs (each version installation) but you may have to deploy them with later versions of the BL and DAL (if there are db changes for example).


问:
UI automation patterns and best practice for desktop applications
Background

I'm currently automating some tests for a plugin for MS Office. We are creating Coded UI tests in VS 2010. I suppose I could use the "Coded UI test builder" tool, but it does not really suit my particular case.

Because of this I created my own UI Map class and extension methods for each UI Control/Map where I add different action functionality. For example press buttons or assert some UI values.

The scenarios of the test cases are in the test classes.

I am new in this area and also I'm new in working as a automation tester.

The question

Would people be kind enough to share their experience and advice for some good practices for test automation on desktop applications from a programming/design point of view?

答:
The best practice for UI Automation Testing is to do as little as possible. UIs change frequently, which means you're constantly having to update your automation. It's generally preferable to structure the product code in a way which allows automated testing without UI Automation.

That said, you can't always get rid of UI Automation. You mention office so I'm assuming you're coding for Windows and using .Net. I do quite a bit in my current job. Here are some of the things I've learned.

1) Look at the UIAutomation libraries which were introduced in .Net 3.0. They provide an extensive and fairly simple to use library for automation. (http://msdn.microsoft.com/en-us/library/ms753107.aspx)

2) Download UISpy (http://msdn.microsoft.com/en-us/library/ms727247.aspx)

3) Make your product's UIs Automatable.

3a) If it's WPF put AutomationIDs on everything.

3b) Try to create distinctive control and window class names (UI Class names, not source code class name). If you don't know what I mean, load up UI Spy and start looking at windows. Notice how many windows across different apps have a class name of #32770. This is the class name for a Windows Dialog Box. Any window which extends the dialog and doesn't set it's own name, defaults to this. This causes all sorts of grief from an UI Automation standpoint.

4) Avoid Thread.Sleep() statements. Try to use Waiters (see UIAutomation docs) instead.

5) NEVER mix the test code with the UI Automation code. Create separate libraries to perform the UI Automation. Call these libraries from your tests. When the UI changes, this will make it much easier to update the automation.

6) Always register a listener for a UI Event before performing the action which would cause the event to fire. In practice, this means you'll be working with threads.

6a) Example: don't start waiting for a Window Opened event after you have clicked a button to open the window. The window may open before the waiter is registered and never get the event.

7) Never assume the window that just opened is the one you want. All sorts of window may open unexpectedly in Windows.

I could go on more, but this is getting a bit long.


问:
When do I have to provide source code for firmware that uses GPLv2 libraries?
Suppose that I am writing the firmware F for the device D, and that I am using the library L which is licenses under GPLv2. The library L is a "source code library" that means that it is not compiled, but is composed of source code files that need to be compiled and linked with the main application.

The device D is a custom device for the customer C, so it is not meant to be sold to everybody, but only to customer C.

What am I obliged to do in this case?

Do I have to provide customer C with all of the source code of firmware F?

How am I supposed to provide this source code?

答:
Try reading the license.  It's surprisingly readable for a legal document.

Also see http://gnu.org/licenses/gpl-faq.html

Basically,

you must provide a copy of the GPL

you must provide source code, or a written offer for source code.  But the written offer has other obligations, so it's probably easiest to just provide the source with the product.

The source code for a work means the preferred form of the work for making modifications to it. It must be provided on a "medium customarily used for software interchange." You must include the code, headers, and build scripts.

OwnerDisplayName: Robbo

OwnerDisplayName: markrages


问:
Staying productive by keeping focus on a feature while developing
As a hobbyist developer I'm quite keen on the git-flow way of working.

But I keep having a problem that I can only blame myself for: while developing a new feature, I keep getting sidetracked by small things that I can "quickly" do. Such things range from small refactoring, writing a particular piece of code in a more pythonic way, adding comments, decoupling, writing an extra test, etc.

Of course, next to the fact that these small things are unrelated to the feature I'm developing, they also tend to grow in size. What appears to be a small thing to do turns out to be something that you spend 2 hours on.

Are there any best practices to keep myself from doing this? I have tried forcing myself to switch to the development branch and do the fixes in a seperate hotfix branch, but I always fool myself into thinking that "for this little change, it's unnecessary to bother with a new branch". Is this just a question of discipline?

(Bonus question: I'm a sole developer, but how on earth would a team of developers handle someone like me? In other words: I'd be changing code all over the place, all the time, which would mean my co-developers would have to keep checking out code and keep trying to get their heads around the new changes).

答:
Stay focused.

I have had a similar problem for years, but I seem to have finally broken through. For me, one of the projects I was having this issue with, was a code base that had very poor design, or often a lack of design. Also, I am constantly reading blogs and books about good practices. But I also constantly question everything I read, question my own conclusions and beliefs, and experiment with new ideas in order to improve and learn. So I had a hard time even sticking to my own design decisions or project coding standards. Here are some things I picked up that help me to stay on track, while also being able to experiment, improve, and refactor the code. Many of these sound similar or related. They are. They work together in a synergistic way. To keep the wording simple, I will speak in terms of absolute truths, even though these are actually just things that seem to help me and may also help or inspire you in some way.

Keep your work interesting. When you find your current task interesting, this helps you to Stay focused. The desire to work on something other than what you know you should be working on is because the thing you are supposed to do seems very boring or will require a lot of tedious work. When that happens, it has nothing to do with the type of feature you working on. It has everything to do with how you go about working on it. If you are bored, you need to work at it from a higher level of abstraction that allows you to solve the solution in a smarter, more elegant, less tedious way. Lift the level of abstraction just high enough that it involves a tiny bit of experimentation, a tiny bit of play, and a tiny bit of learning. Here are some ideas: Write a script to make that database change everywhere it needs to be made instead of making a bunch of manual changes. Write some classes that create an abstraction that you will subsequently use to write the feature you need with a smaller amount of more expressive code. Use, create, or extend a framework that will eventually do a lot of the work for you. Write a reusable script, command, or dev tool extension that does some tiny piece of work for you, or shows you useful information. This will also have the effect of constantly, slowly adding to a body of useful abstractions and tools that you can reuse. In this way, you will constantly increase your productivity the longer you remain on a given project. There are also other ways to keep your work interesting, as you will see.

Keep your work boring. If you try to raise the level of abstraction too much at once, your mind will get way away from the feature you are actually working on. Figuratively speaking, you are building too high up in the sky and it will take a very long time before you are able to connect your structures to the buildings on the ground. This will help you to balance your need to Keep your work interesting and help you to Stay focused.

Frequent releases. If you make a practice of frequently releasing, this will help you to reign in your desire to venture off on massive refactorings or experiments, since you know you will need to do a release soon. This will help you to Keep your work boring and Stay focused so that you can do frequent releases. Doing frequent releases will also help to Keep your work interesting as releases are exciting and interesting. You will soon find that you are addicted to releasing. It's like a drug! You will always be itching to get another release out there.

Keep your code releasable. Even if you don't release at every opportunity, always get back to a releasable state as quickly as possible. Make very small changes to the code. This will give you great opportunities to change directions. Making changing directions easy will help you get back on track if you get off track. This will help you to Keep your work boring, do Frequent releases, and Stay focused in order to keep your code releasable. Releasable code is the opposite of imaginary code in that it could be released whenever you want and at which point it can start affecting the real world. Non-imaginary code that can affect the real world is more interesting than imaginary code that is just a dream. Therefore, this also helps to Keep your work interesting and helps you to Stay focused.

Write high quality code. Make sure code you add is up to your standards. This will prevent you from being tempted to refactor unrelated code, as it will all be pretty well organized most of the time. This will help you to Keep your work boring and Stay focused. Knowing the code you write is high quality will help you to feel better about it. You will not feel like you are actually just wasting your time by digging yourself into a hole that you will just need to dig yourself out of later. That will help to keep your work feeling meaningful. It will Keep your work interesting.

Keep a list changes you intend to work on. This includes changes to existing features, new features, bug fixes, code quality improvements, development tools, etc. This will help motivate you to Keep your work boring and Stay focused as you know you have a whole list of things that need to be done. Code quality improvements only need to be added to the list for already existing code. New code you add should be up to your standards. One caveat to this is that for code you yourself wrote, that at the time was up to your standards, you may see a way to refactor it to improve it. One problem is you could probably go on doing this forever. If this cannot fit quickly into the context of another item, it should be added to the lists and broken up if necessary. Lately I have been having success using Asana for my lists.

Prioritize your list. Constantly reorder the list so that the highest priority items are on the top. Add notes that help you conceptualize what the priority of something should be and how to compare it to priority of other items in the list. Having a prioritized list will give you permission to work on refactorings to existing code or experiments when those things are truly of the highest priority. Having a prioritized list will help you to put things into context and bring your emotions in harmony with your thinking as to your actual priorities. When your emotions and thinking are in harmony, this helps you to Stay focused.

Break up ideas. Each item in the list should usually represent the smallest change possible that you could release and would provide some kind of improvement. This requires you to take ideas for a feature and really dissect them and realize that they are actually multiple features in disguise as a single feature. This helps you to do Frequent releases. and Stay focused. As a bonus this enables you to change directions at almost any time, by reprioritizing the list based on feedback from releases or business changes. When there is not a constant flow of completed items and releases, this means you are not breaking up your ideas enough. When you do have a constant flow of completed items and releases, this helps everyone to see that you have been busy and they can see fruits from your labor. You will become that valuable, productive programmer that everyone wants on their team!

Utilize transparency. Keep the list available for everyone involved in the project to see, even if you are the only person actually changing the code. Make sure you have the ability to mark items in the list as complete, and that people can see completed items. This transparency will help motivate you to keep your priorities straight. If the majority of items completed are refactorings, other people following the project will start to get upset at you. Just knowing that they see what you have been working on is usually enough to keep you on track.

Refactor in very small steps. Even though I already mentioned that keeping your code releasable involves making the smallest changes possible and then getting back to releasable code, I thought this was worthy of extra consideration in the context of refactoring. Learning to refactor this way is an art. Refactoring is making changes that are internal to the design of the code that do not affect the behavior of the program. You can to learn to think in terms of preparatory refactorings, and small little in between refactorings that you are only making because of having the goal of making some larger refactoring. A little change is easier to reason upon. This helps you to write it without bugs. If you write it with bugs, this helps you to reason about the bugs, to investigate them, and to fix them. You can make lots of these small changes very quickly. Going slow will help you to go fast, and will help you to safely make larger refactorings. If you eat up more time than expected making small refactorings in pursuit of a larger one, this approach allows you to reprioritize frequently if necessary. You can finish the rest of the larger refactoring later.

Get ideas out of your head. While you are working on an item from the list, you may think of something you may want to work on at some point that is not already in the list. Instead of trying to remember it, immediately add it to the list. If you try to push it out of your head without adding it to the list, part of your mind will actively work at evaluating how much importance the idea has so that it can remember it later if necessary. So instead of concentrating on the item you are trying to work on, you are divided because part of you is saying "This is not important, just push it aside and stay focused on what is important", while another part of your mind is stressed out saying "No, that is not necessarily true. This may be very important. I am very concerned that you might forget about this important idea". Adding it to the list will put your mind at ease, allowing you to truly focus on the item you are working on. Even if you are not sure if it is actually a good idea, or you want to discuss it with someone first, just explain that in the notes.

Make lists of lists. Eventually the list will become very long, and people looking at it feel overwhelmed and confused. You will start to have a difficult time figuring out how to prioritize things. That is when you need multiple lists. Each list should have a theme that helps you understand the priority that list has in relation to the other lists. One list might be a list of bugs, another a list of changes or features specifically needed by clients. Another a list of ideas for improvements to the software that are not specifically required by any clients. Another may be a list of code quality issues that you want to be addressed at some point. That will make it much easier for you to figure out what is the most important thing for you to work on next.

Break up lists into subcategories and tags. The bug list could have each item in one of the following categories: critical, important, minor, and very minor. Tag items lists as being for a particular client or part of a particular feature set or sub-project.

Collaborate with everyone. Make sure that everyone who can see the lists, can add items, notes, categorize, and tag items. Make sure discussion can happen and be seen right along with the items. As I said before, lately I have been having success using Asana for this. Asana can even be configured to send out automatic notifications, keeping everyone engaged. This will eliminate unnecessary email and communication as people can just add something to a list instead of communicating to you about it. If they want to see if an item is complete, they can just look at the lists. This organized, less cluttered, less redundant way of communicating will help you to Stay focused on the item you are working on instead of reading emails, having chats and phone conversations, and then trying to organize all this information in a way that is then only visible to you, or even worse is entirely in your head.


问:
Difference between overhead of B frame and P frame
I understand that B frames either find the motion vector of the best matching block from either the past or the future reference frame. And P frames finds the motion vector of the best matching block from the previous reference frame. So how can B frames result in less overhead and better compression compared to P frames?  </p>

答:
Presumably you're talking about MPEG compression, or some variant such as MPEG 4 part 10 (aka H.264).

In this case, prediction in a B-frame doesn't just choose the better of a preceding or following frame. Rather, it does a linear interpolation between blocks from the two frames, then encodes the difference from that.

You frequently see relatively linear transformations between frames, and when this happens, the linear interpolation used with B frames can give a significantly better prediction of the current block than either the preceding or subsequent frame could have individually.


答:
The GPL requires that any time you distribute the software, you must either include the source code or make it available for download with clear instructions on how to do so (e.g. provide a URL to your public repository or download page).

You are only obligated to provide the source code to whomever you are distributing binaries. For the vast majority of GPL projects, the software is available to the public so the source must be as well. In your case, the binaries are only available to specific customers, so only those customers must receive source code (or have it available).

As far as "when," you must make the source code available no later than the instant the binaries are available.

Title: When do I have to provide source code for firmware that uses GPLv2 libraries?

Body:
Suppose that I am writing the firmware F for the device D, and that I am using the library L which is licenses under GPLv2. The library L is a "source code library" that means that it is not compiled, but is composed of source code files that need to be compiled and linked with the main application.

The device D is a custom device for the customer C, so it is not meant to be sold to everybody, but only to customer C.

What am I obliged to do in this case?

Do I have to provide customer C with all of the source code of firmware F?

How am I supposed to provide this source code?


答:
If you think about it, architectures are abstract machines.  They describe how a lump of carefully made silicon "should" behave.  The difference between the architectures and Turing machines is more a matter of scale than a fundamental shift in approach.

The advantage of Turing machines is that there is a set of useful proofs that are very easy to do using a Turing machine.  It is simple to prove that any machine powerful enough to simulate a Turing machine can solve any problem a Turing machine can (duh).  However, it gets more interesting when you define a Computable function.  It turns out that there are many compatible definitions of a computable function.  If you can define all of your behavior as computable functions, you can be simulated in a Turing machine.

So let's say you have an architecture which directly supports LISP style programs, and another like the x86 which is more procedural.  Your friend claims "LISP is more expressive, so you can write programs on this machine you could never write on your x86."  This is brutal to counter (especially since you probably don't know enough LISP).  However, you can abuse several abstract machines like the Turing machine:

Your LISP machine may be fancy, but everything it can do is reducible to lambda calculus. Your friend nods eagerly.  Lambda calculus is a bit of a cult thing for functional programmers.

My x86 may be fancy, but everything it can do is reducible to a register machine. Once again, no question from your friend.  Registers are SO pase in modern computer theory!

Any register machine can be modeled as a Turing machine simulating that register machine. Now your friend wonders why you're harkening back to the punch-tape era.

And your lambda calculus machine can be reduced to a Turing machine as well. *Your friend objects, but you point them at the Church-Turing thesis, and they hang their head in shame.

Thus my x86 box can do anything your fancy LISP based machine can do!

There are, of course, plenty of other examples.  Conway's Game of Life was proven to be Turing complete, meaning it could theoretically do anything your computer can do.  The easiest way to do this was to build a Turing machine in Life.  I bring this up because this would be a case of what you called an abstract machine being treated as a literal architecture!  You can imagine how hard the claim of computability in Life would be without the aid of abstract models (I sure as heck am not modeling a x64, complete with cache peeking, just to prove Life is computable!)

In the end, the big difference between architectures and abstract machines is that architectures are usually concerned with performance.  Architectures want to know how fast you can do something.  Abstract machines tend to be content with just knowing if you can.  Consider the Universal Constructor developed for von Neuman state machines.  It was enough to prove that the UC could work, nevermind that the authors never had enough computing power to actually see it through.

The price architectures pay for demonstrating how fast they can work is that it is often terribly difficult to prove that they can compute everything.  For that, the architectures turn right back around and start using abstract machines.

Title: Bridging the gap between abstract machines and computer achitectures?

Body:
I always feel disconnected between abstract machines (such as Turing machines) and computer architectures (including virtual machines' architectures, Von Neumann's achitecture).
So I would like to know how they are related? How do one influence the other?
References are also appreciated. Thanks.</p>


问:
Making sure loaden (non default) config is valid
I'm writing a device Software in which the device must handle much data. Therefore it has a database, either on NV-Ram (Non-volatile memory) or a SD-Card.

Due there's a DB which I can use, I also use it to store configurations which should survive restarts or power loss.

Everything is working fine so far, but how can I prevent corrupted configs?
Using SQLite3, I can be relatively sure, that changes either aren't saved, or are correct.
But what happens if wrong data is stored? This is a viable scenario.

Which techniques are good to check a set of data for coherency?

So far:
By (re-)start of the device, I check if DB holds a config and if not, I'm writing the hard-codet default config to the DB.
There are multiple problems with that, it does only check if there IS an existing config table in the DB, but not if the table is validt.

One Idea I had so far, is to iterate through default-config and check every entry in config if it has the specific entrie, if yes check for datatype, if not throw error. Still, this would not prevent invalid data.

Example:

Entry "reader-port" (hardware-port on which an specific device is connected)

Expected datatype -> String (example: "\ttys\com2" )
Given    data     -> String ("paoghsfodgvfnamox33" )

As you can guess, this is wrong.

Note: This question is not language specific. But beside of this, I'm working with Lua.

答:
In general, one can write a checksum with the data that can be recomputed at read time and compared with the written value. If they do not match, you know there has been data corruption (or your checksum is out of date).

You could go a step further and provide enough redundant information to repair the corruption (error correcting codes), but this might be overkill in your case.

Since you are using a database (SQLite), it generally provides its own checksums and data integrity validation internally. However, I think it is unlikely you would read a string from it and see garbled data, as in your example. Typically if a database file gets corrupted the structural information in the file that the database itself relies on will also be corrupted, so the database will (at best) throw an error or (at worst) crash.


问:
How can I ask my boss (in a polite way) to comment his code?
I am being taught by my boss (I just finished school and he wanted someone with a little programming experience, so he chose me to train me on what that company specializes in) and started working with ASP.NET MVC applications, some HTML and CSS. I'm fine with the web design stuff he gives me (it is pretty simple to understand without clarification).

But for instance, he gives me a task to do with ASP.NET MVC, he explains it really well. But he doesn't explain anything in the code he has just given me. (We use source control in Visual Studio 2013), so it's literally hundreds of lines of code, without any background on what it is supposed to do. The kind of code that I'm seeing is code I've never seen before, so it is really difficult to try and figure out.

I would try and ask him more questions, but he is always working (it's his own business), and I feel as though he might get annoyed with all these questions I have on my hands.

So just something that will help my out until I get a grip on things, how can I ask my boss to put comments into his code that he gives me, but politely?

答:
I was having the same problem. Im student of phyzist and have good programing experience. I was programing in many languages but nothing for premium aplication.

I have applied for a job for web developer and they instantly put me on back end of web programming. When boss showed me the base api for node REST application i was thinking that I would throw out. I have never seen functions with callback and so strange syntax. And I ask my boss do I have a problem If i don't understant anything in the code. He sad no, he sad that i have 1 month to figur it out and in the mean time I will make a CMS for testing me with another frontender.

Well and I went 1 line of code at the time and google every thing that I havent know. So 1 week was passed and i was familiar with the code enough that i could make some colaboration with front ender. My code at the beginig was crap but se me 3 month after that! I'm coding better and faster than our software architect !

I sugest that you never stop learninig! My moto -> Keep learning and keep calm :) Dont depend on boss be independat and ask him directly but only the hardest problems. Because you will be happy after you figure it out by your own resarch. And remember when you stop learning its something wrong, learn ewery day how to be a good programmer.

If you will learn from boss you will never go better than him set your own standard, learn blind typing, VIM or VIM plugin for your IDE, Linux wmii, so you would some day go beyond of boss, and be better than him!