答:
VB.NET has an operator that does double duty as both the ternary and null coalescence operators. This operator is If. It also has a function, IIF, which takes three parameters.

These are two entirely different things. The IIF function is just that, a function, you could write your own that does the exact same thing. It should be avoided, it became obsolete the moment the operator was introduced.

Now, the IF operator is quite handy, and allows doing things that would have been extremely difficult to even approximate, and impossible to exactly duplicate, before lambdas were introduced (you still can't exactly duplicate it, but you could get a similar effect). There is no reason to avoid it, it behaves as expected, so even if you don't know about it, it doesn't surprise -- so it is not a danger for junior programmers.

Both functions of the If operator are basically short circuiting calculations, and that's a good thing.

If the standard you are working on is for using VB.NET, then it should be recommended. If it's for a new language, I recommend both operators as being useful additions to readable and understandable programs (you might want to make them a bit more distinct).

PS: You say that IIF behaves as expected, I would deny that and change your example a bit:

```<code> Dim input as String = "Junior"
 Dim parsed as Integer
 parsed = IIF(IsNumeric(parsed), CInt(input), -1)
</code>```

Throw that at someone not familiar with the language and they naturally expect parsed to be -1. Which is not what happens, instead you get an invalid cast exception. http://ideone.com/JfbFwi

I have fixed bugs exactly like the above.

Body:
VB.NET has an operator that does double duty as both the ternary and null coalescence operators. This operator is If. It also has a function, IIF, which takes three parameters.

These are two entirely different things. The IIF function is just that, a function, you could write your own that does the exact same thing. It should be avoided, it became obsolete the moment the operator was introduced.

Now, the IF operator is quite handy, and allows doing things that would have been extremely difficult to even approximate, and impossible to exactly duplicate, before lambdas were introduced (you still can't exactly duplicate it, but you could get a similar effect). There is no reason to avoid it, it behaves as expected, so even if you don't know about it, it doesn't surprise -- so it is not a danger for junior programmers.

Both functions of the If operator are basically short circuiting calculations, and that's a good thing.

If the standard you are working on is for using VB.NET, then it should be recommended. If it's for a new language, I recommend both operators as being useful additions to readable and understandable programs (you might want to make them a bit more distinct).

PS: You say that IIF behaves as expected, I would deny that and change your example a bit:

 Dim input as String = "Junior"
 Dim parsed as Integer
 parsed = IIF(IsNumeric(parsed), CInt(input), -1)

Throw that at someone not familiar with the language and they naturally expect parsed to be -1. Which is not what happens, instead you get an invalid cast exception. http://ideone.com/JfbFwi

I have fixed bugs exactly like the above.


问:
Should model / table names be as generic as possible?
When naming a model, should the name be as generic as possible-- even if that won't be the name displayed to users?

For example let's imagine a Django model for liking another user's posts.

Does it make sense to name the model 'Like' even if I plan on displaying it as Kudos, Endorsements, Ups, etc?

Does it make sense to make the name as generic as possible, even if the name won't be the one displayed to the user?

答:
Table and field names should be descriptive of the domain entity that they capture.  If the domain entity is a customer, you should call the table "Customers."  Like classes in an object-oriented program, tables follow the Single Responsibility Principle: each table should store instances of one thing (with all of its attributes), and one thing only.

To see why this is so, imagine the complete opposite.  Imagine a system so generic that it's all stored in just three tables:

```<code>TableID     Primary Key
Name        Text

FieldID     Primary Key
TableID     Foreign Key
Name        Text
Type        Enum  (Text, Number, etc.)

ValueID     Primary Key
FieldID     Foreign Key
Value       Text
</code>```

Notice that there's no identifying information at all in the tables themselves.  You have to run a query to find the table you want.  Then, you have to run another query to get the field that you want, and a third to get the field value.

If this looks familiar, it should: the first two tables are basically the "system" tables in an ordinary DBMS, which we have now re-invented.  In fact, we have reinvented the entire DBMS.  If you doubt this could ever happen, read here:

https://www.simple-talk.com/content/article.aspx?article=292

ContentLicense: CC BY-SA 3.0

Body:
Table and field names should be descriptive of the domain entity that they capture.  If the domain entity is a customer, you should call the table "Customers."  Like classes in an object-oriented program, tables follow the Single Responsibility Principle: each table should store instances of one thing (with all of its attributes), and one thing only.

To see why this is so, imagine the complete opposite.  Imagine a system so generic that it's all stored in just three tables:

TableID     Primary Key
Name        Text

FieldID     Primary Key
TableID     Foreign Key
Name        Text
Type        Enum  (Text, Number, etc.)

ValueID     Primary Key
FieldID     Foreign Key
Value       Text

Notice that there's no identifying information at all in the tables themselves.  You have to run a query to find the table you want.  Then, you have to run another query to get the field that you want, and a third to get the field value.

If this looks familiar, it should: the first two tables are basically the "system" tables in an ordinary DBMS, which we have now re-invented.  In fact, we have reinvented the entire DBMS.  If you doubt this could ever happen, read here:

https://www.simple-talk.com/content/article.aspx?article=292


问:
What does the static keyword do here?
Can anyone explain this piece of code?

CODE1

```<code>int &fun()
{
    static int x = 10;
    int &b =x;
    return b;
}
int main()
{
    fun() = 3;
    cout << fun();
    return 0;
}
</code>```

Output: 3

CODE 2

```<code>int &fun()
{
    int x = 10;
    int &b =x;
    return x;
}
int main()
{
    fun() = 3;
    cout << fun();
    return 0;
}
</code>```

Output: 10

答:
It means that x is shared in between function calls. It's the function equivalent of static members of classes.

Static members are shared in between instances while static function variables are shared in between invocations. This means that when you modify x after the first function call in your example it stays modified for all future invocations.

Title: What does the static keyword do here?


答:
```<code>int &fun()
{
    static int x = 10; // x is statically allocated at compile time
    int &b =x;         // b is a reference to x
    return b;          // each call to fun() returns a reference to the same int
}
int main()
{
    fun() = 3;         // sets 'x' to 3
    cout << fun();     // it's still 3
    return 0;
}
/////////////////////////////////
int &fun()
{
    int x = 10; // x allocated on the stack whenever f runs
    int &b =x;  // does nothing, b is initialized but never used
    return x;   // undefined behavior.  After fun returns, x does not exist
}
int main()
{
    fun() = 3;  // more undefined behavior
    cout << fun(); // could print any number, or crash
    return 0;
}
</code>```

Title: What does the static keyword do here?

Body:
Can anyone explain this piece of code?

CODE1

```<code>int &fun()
{
    static int x = 10;
    int &b =x;
    return b;
}
int main()
{
    fun() = 3;
    cout << fun();
    return 0;
}
</code>```

Output: 3

CODE 2

```<code>int &fun()
{
    int x = 10;
    int &b =x;
    return x;
}
int main()
{
    fun() = 3;
    cout << fun();
    return 0;
}
</code>```

Output: 10


问:
What's the best way to scale and split an agile team building a web app?
I've recently joined a company where I'm working as the scrum master on an agile development project building a web app.

The team is just about to be the maximum size for an agile team (expecting 9 next week).  We have talked about potentially splitting the team into two teams, not so much to shorten standups (which aren't excessive at the moment) but to stop people from being completely bored in sprint planning sessions (which again aren't excessively long).

There are two very distinct layers to the project - high technical backend dev (like seriously complex), and UI design/build/integration.  It seems that when the backend guys are talking technical the UI guys zone out, and vice versa.  It seems like the logical way to split the team if only to be more time efficient, but I have one massive reservation in that all I might really be doing is reducing collaboration and knowledge sharing.  The two teams just won't really have a good idea about what the rest of the team are building.

Does anyone have any experience in dealing with something like this?

答:
How far is the front-end from the backend? Predictably, splitting is a good advice only if the distance is too far.

If the backend talks about database schema, this is not too far. Both front-end and backend needs to listen to discussions about database schema.

If the backend talks about sharding, memory caches, disk latency, etc., then this is a bit too far (where the backend focuses on mechanical sympathy and optimization, while the front-end focus on humanly aesthetics).

Is there a stable and unambiguous programming interface between the front-end and the backend?

By stable and unambiguous, it means the users of that programming interface (the front-end developers) will not be bogged down with changes, and will not need to read walls of text in order to learn how to use it correctly.

The backend team need to provide a good API, and a mock implementation early on, and only after that start the real development.

This is not to say the API should be set in stone. This is just a mitigation of the consequence for splitting a team into two.

Why do so many agile articles recommend having vertical slices? Here is some background information:

Most agile articles actually recommend avoiding backend work, from a cost perspective.

Also don't forget that a fraction of agile articles had the implicit bias toward startup companies.

And don't forget the harsh reality of marketing - most customers only pay for the front-ends.

Backend work tend to be costly and had slow payoff. Unless a company is already established for the long run and is generating a decent profit, it is better off to "outsource" backend by sticking to off-the-shelf technology and open-source libraries.

Most agile articles also recommend implementing the front-end so that it can survive a backend switch. This advice goes hand-in-hand with the previous one: if the off-the-shelf technology does not meet all requirements, try another one.

Practices that can mitigate the bad consequences from splitting a team

Stable back-ends

Stable API

Low defect rate back-end

Reason: to avoid frustration

How: unit testing

Doesn't mean: performance or optimization; it just need to be functionally correct.

Continuous integration

Transparency in communication, progress, and decision making

Encourage informal discussions across the two teams

Encourage team members (those who don't zone out) to attend the meetings of the other team.

Set up occasional joint meetings, and joint retrospects

Other team-building activities


答:
The static keyword makes the storage class of the int x static -- which means that it is essentially a global variable that has its access scoped by the function. In particular, the lifetime of x extends past the execution of the function, and the initializer is only executed once.

When fun() returns the reference to x in Code 1, the reference points to the static storage for x. As a result, the assignment to fun() in main sets the static variable x to 3, which is then returned when fun() is called again on the next line. Since the initializer for x is only executed once, the second call to fun() does not reset the value to 10.

The example in Code 2 is not valid. Returning a reference to a local variable is not valid because the storage for the local variable does not exist after the function returns. While it may appear to work in this case, the result of this code is undefined. Since local variables are generally stored on the stack, for this specific sequence of code, the value in the location that was used for x has not been trashed and the value is set by the initializer in fun(). But this is completely implementation dependent and the compiler specification makes no guarantees about this behavior.

In fact, if the code was a bit more complex that value could have been trashed and you might get some random value printed. Or the code could even crash. In any case don't return references or pointers to local variables as that is not valid code.

Title: What does the static keyword do here?


问:
How to evaluate moving to Team Foundation Server
My development team presently uses the following software in our workflow:

JIRA

Bamboo (Atlassian continuous integration)

Greenhopper (Atlassian agile project management)

Confluence

Git, hosted on BitBucket

Visual Studio 2012

As you can see we are quite heavily invested in the Atlassian ecosystem. We are considering a move to TFS so we can get the niceties of advanced Visual Studio integrations such as code reviews and more importantly the Microsoft Test Manager.

My previous experience with TFS was with 2005 or 2008 (I can't remember) and I have bad memories of it, although not quite as bad as my time with ClearCase.

What criteria should we be looking at in order to properly evaluate our move to TFS?

答:
I have a very positive experience of using TFS 2012. It is quite easy to set your TFS server up and running, CI build automation is very simple and straightforward (and the Gated check-in build is just awesome. We failed to achieve same functionality with Team City). Team interaction is very transparent and straightforward too. You can easily associate your check ins to TFS workitems, manage a backlog, track defects, do codereviews and so on. There is even a messenger build in =)

However keep in mind that if you accustomed to your JIRA's workflow, setting up TFS workflow could be a tough task. I'd suggest adopting one of the predefined TFS workflow. Also you will have to keep Confluence as you knowledge base or switch to SharePoint as there is no wiki build into TFS.

TFS is much more cheaper if you have a MSDN subscription (I believe most developer companies working with MS technology stack have it) in that case you have TFS for free.

I think there is no reason to keep using side parties tools if you all your developers are working with Visual Studio. TFS provides integrated, robust yet easy to use ALM system.
I will gladly answer your questions if you have any.


问:
Do I need IDs in my database if the records could be identified by the date?
I am writing my first application for Android and will use the SQLite database so will be trying to limit the size as much as possible, but I think the question applies in general to database design.

I am planning to store records that will have text and the date of creation. The app is a stand-alone app, i.e. it will not link to the internet and only one user will be updating it, so there is no chance that there will be more than one entry with a given date.

Does my table still need an ID column? If so, what are the advantages of using the ID as a record identifier as opposed to the Date?

答:
Keep in mind that you might also want to change meaning of "date" column from created_at to updated_at or any other change along those lines, which I find to be very common case.

Adding id column in some cases will give you more flexibility when your design changes.


问:
Why does Facebook use hash in the URL...sometimes?
I've noticed that Facebook SOMETIMES uses a hash in the url.  For example, when I'm on my home page, and then I click my profile page, the URL quickly changes to:

```<code>facebook.com/#_________
</code>```

followed by some other stuff.

before quickly loading to:

```<code>facebook.com/profileName
</code>```

It doesn't always do this.  What's going on here?

答:
The "#" allows you to target something in a web-page. as in

```<code>...
<div id="foo"></div>
...
</code>```

to target foo div in a page you can just do #foo

That being said there is no need to reload the page if you just change the # in the url, and facebook uses this as a hack. What they do is they just change the hash 'which makes the url bookmarkable' at the same time they can load up assets using XHR and the page doesn't reloads itself providing a seamless experience to the user on the other hand it doesn't make as many HTTP requests to the server for CSS / HTML / JS files (despite of being cached the validation is required) and hence reducing the amount of content they have to render and number of HTTP requests to their server, they also can increase the performance and reduce latency of the website doing so.

There is though a better way to do this which is documented in the HTML 5 History API( Which you should read perhaps ) Which allows you to change the URL in the address bar by pushing history states.

Body:
The "#" allows you to target something in a web-page. as in

...
<div id="foo"></div>
...

to target foo div in a page you can just do #foo

That being said there is no need to reload the page if you just change the # in the url, and facebook uses this as a hack. What they do is they just change the hash 'which makes the url bookmarkable' at the same time they can load up assets using XHR and the page doesn't reloads itself providing a seamless experience to the user on the other hand it doesn't make as many HTTP requests to the server for CSS / HTML / JS files (despite of being cached the validation is required) and hence reducing the amount of content they have to render and number of HTTP requests to their server, they also can increase the performance and reduce latency of the website doing so.

There is though a better way to do this which is documented in the HTML 5 History API( Which you should read perhaps ) Which allows you to change the URL in the address bar by pushing history states.


问:
BSD-2 Licence Code modifying
I'm using a BSD-2 Licence code in my project and with author permission, I modify the code. Now, I am using this code in my project. I know, I should mention Author's name and copyright information. Should, I mention What I modify in this code??</p>

答:
The 2-clause BSD license requires that you advertise the names of the original authors (my emphasis):

Copyright (c) [YEAR], [OWNER].

All rights reserved.

(...)

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

The same goes for the binary form:

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

A binary release, obviously, doesn't require that you identify clearly what parts of the source code the original copyright applies to.

A source code release however would have you include the copyright in each original file, and put your own in each of your files. In case a file has been patched, and thus contains code from both the original author and yourself, you would have to stack the copyrights at the top of the file. At least, this is what seems to be the general practice to me.

OwnerDisplayName: Yasir Adnan

Title: BSD-2 Licence Code modifying


问:
Inner workings of the IF() function - why aren't expressions evaluated?

Short version

How does the IF() function cause the passed expressions to NOT be evaluated prior to being passed in as parameters?

Detailed version

I am part of a standards committee, and a discussion was initiated which, in general, is trying to ban the use of the IIF() function. The general consensus is that if you want to do a short line-length assignment IF() is okay. And if you for some reason want to evaluate two expressions, don't try to accomplish that all on one line, explicitly and purposefully evaluate the expressions on seperate lines, then do an IF() call with the results in the If True and If Else parameters.

I'm asserting that before a Function(param1, expression) is stepped into, any expressions are evaluated. Then, their evaluated value is passed as a parameter.

That being asserted, this makes sense:

```<code>Sub Main()
    Dim intTest As Integer = 0
    Dim blnResult As Boolean = IIf(2 = 2, Integer.TryParse("3", intTest), Integer.TryParse("4", intTest))
    'intTest = 4
End Sub
</code>```

As expected, blnResult is True.

Because the conditional of the IIF() function is True, the value of the expression in the "If True" parameter is the resulting assignment.

But BOTH the If True AND If Else expressions were evaluated (in written order) prior to even stepping into the IIF() function, so intTest became 4.

As far as I'm concerned, that is programatically expected, but not the results desired.

On the reverse side of the coin, we have this:

```<code>Sub Main()
    Dim intTest As Integer = 0
    Dim blnResult As Boolean = If(2 = 2, Integer.TryParse("3", intTest), Integer.TryParse("4", intTest))
    'intTest = 3
End Sub
</code>```

As the inverse of the previous issue, we now have:

As expected, blnResult is True.

Because the conditional of the IF() function is True, the value of the expression in the "If True" parameter is the resulting assignment.

But ONLY the If True (in this case) is evaluated, so intTest became 3.

As far as I'm concerned, that is the results desired, but not programatically expected.

I'd like to see a custom function that does the same thing as IF().

答:
Your confusion stems from a misapprehension:

Inner Workings of the IF() Function

How does the IF() Function

the conditional of the IF() Function

I'd like to see a custom function that does the same thing as IF()

But IF() is not a function.

The language specification for VB.NET (freely available for download) has this to say about If. I quote the 11.0 version; emphases as mine, and note that the apparent error in the example is a direct quote!:

11.22 Conditional Expressions

A conditional If expression tests an expression and returns a
  value. Unlike the IIF runtime function, however, a conditional
  expression only evaluates its operands if necessary. Thus, for
  example, the expression If(c Is Nothing, c.Name, "Unknown") will not
  throw an exception if the value of c is Nothing.

Note the difference: If is an expression, whereas IIf is a function. Like any other function, IIf obeys the usual parameter evaluation rules. But If, being an expression, doesn't have to.

You wouldn't expect

```<code>If <condition> Then
    ' Do this
Else
    ' Do that
End If
</code>```

to do both this and that; similarly, you shouldn't expect If to evaluate both parts.

You're not going to be able to readily make a function that does this, any more than you'd be able to (say) make a function that does what Using does - it's part of the language.

Body:
Your confusion stems from a misapprehension:

Inner Workings of the IF() Function

How does the IF() Function

the conditional of the IF() Function

I'd like to see a custom function that does the same thing as IF()

But IF() is not a function.

The language specification for VB.NET (freely available for download) has this to say about If. I quote the 11.0 version; emphases as mine, and note that the apparent error in the example is a direct quote!:

11.22 Conditional Expressions

A conditional If expression tests an expression and returns a
  value. Unlike the IIF runtime function, however, a conditional
  expression only evaluates its operands if necessary. Thus, for
  example, the expression If(c Is Nothing, c.Name, "Unknown") will not
  throw an exception if the value of c is Nothing.

Note the difference: If is an expression, whereas IIf is a function. Like any other function, IIf obeys the usual parameter evaluation rules. But If, being an expression, doesn't have to.

You wouldn't expect

If <condition> Then
    ' Do this
Else
    ' Do that
End If

to do both this and that; similarly, you shouldn't expect If to evaluate both parts.

You're not going to be able to readily make a function that does this, any more than you'd be able to (say) make a function that does what Using does - it's part of the language.


问:
Revoking Open Source license, for specific individuals
I develop an open source Android application, which is licensed under GPL and freely available on Github.

It is currently under heavy development, therefore it isn't published in the Play Store yet.

What can I do, if someone decides to publish it in the Play Store,

without modifying the code (just build it from my repo and upload it, same package name).

with modifying the source code and publishing it on Github under same license.

and modify the code but don't publish the code under the same license.

答:
The first two actions are completely fine. That’s all allowed by the GPL. If you want to restrict it, your only option might be to trademark the name; still, anyone is free to publish the app under a different name.

Regarding the third point, do you mean that the modified app isn’t published at all, but only used privately? That would be fine as well. Or do you mean that the modified app is distributed without any source code, or with source code under a different license? That would be a violation of the GPL, and you could take legal actions to try and stop it.

Generally, you can’t restrict the GPL to only some people. Everyone is free to use, modify or distribute a GPLed program, as long as they abide by the terms of the license.


答:
Quite simply do not use the GPL if it doesn't suit your needs. What you want to create is not free software (not entirely anyway). You can derive a new licence from some type of open source license and add restriction on what can be done with the software.

If you want to prohibit that somebody else generates money with it (through the Play Store or not) you could use something like CC BY-NC.

If you want to prohibit that somebody else publishes it somewhere for free, I think you shouldn't and should rather be grateful that you have somebody else taking charge of the distribution of a non-commercial product.

Title: Revoking Open Source license, for specific individuals

Body:
I develop an open source Android application, which is licensed under GPL and freely available on Github.

It is currently under heavy development, therefore it isn't published in the Play Store yet.

What can I do, if someone decides to publish it in the Play Store,

without modifying the code (just build it from my repo and upload it, same package name).

with modifying the source code and publishing it on Github under same license.

and modify the code but don't publish the code under the same license.


问:
When should I write integration tests?
According to rules of TDD unit tests are written before production code, but what about Integration tests that exercises interaction between concrete (non mocks) wired objects?

Should they be written before unit tests or after production code just to test the "wiring" ?

Note that I'm not talking about Acceptance or functional tests but Lower level integration tests.

答:
Unit Tests are used to test the smallest possible testable bit of software in an application and to test it's functionality. Each unit is tested separately before amalgamating them into parts or larger components of the application.

That's where Integration Tests come in:

They test these newly created parts that consist of the previously tested units during fitting these parts together. Best case would be to write the tests at this point while writing the application itself.

Title: When should I write integration tests?


答:
I've moved from a company with a largely Atlassian stack (and Mercurial) to a company with a heavy TFS stack. I find two irritations.

The first is Source Control.

When you've got used to DVCS, switching back to a CVCS is painful. TFS is particularly painful because, for all that integration to work, it insists on being connected to the server at all times.

However, thankfully, Microsoft have recently allowed for integration of Git version control into the rest of the TFS stack. So you don't need to give up Git, and I advise you not to, given that everyone already knows it.

I'm not yet sure how well the code-review tool works against Git though, given that it seems to rely a lot on shelvesets (a little like stashes, but not so powerful). But then relying on shelvesets for code-review is painful in itself because it discourages regular commits.

The other irritation is the reason most people won't consider moving away from TFS: The Visual Studio Integration.

I have yet to figure out the cognitive reasoning behind this but, in my experience (and taking into account that this is generalising), people who are used to TFS love the integration. They don't like to move outside their IDE for anything.

I, on the other hand, have not warmed to it after a year. I find it cluttered and hard to navigate, compared to having my build server in one browser tab, my tickets in another browser tab and so on. (Edit: As Andrei notes, there is a web interface, but it is also inexplicably clunky, when you're used to more recent versions of Jira and Jenkins. But still, it does at least work in browsers other than IE now. So that's something.)

I never look at builds unless I'm trying to do one, and then I find it hard to find out if someone else is already doing one. I don't see other people's changes unless I'm asked to review.

But, your milage may vary. As I say, some people seem to find it indispensable. I just can't help noticing that it's generally people who have never done it another way.

Also, don't fail to notice that this is 2 negatives, one of which may be personal, in a pretty large infrastructure. Most of my experience is good and TFS isn't as bad as some people will have you believe. And most things you find you're missing can probably be switched on (it's very configurable); given that you're moving a whole team, rather than one person, you might find less resistance.

Title: How to evaluate moving to Team Foundation Server

Body:
My development team presently uses the following software in our workflow:

JIRA

Bamboo (Atlassian continuous integration)

Greenhopper (Atlassian agile project management)

Confluence

Git, hosted on BitBucket

Visual Studio 2012

As you can see we are quite heavily invested in the Atlassian ecosystem. We are considering a move to TFS so we can get the niceties of advanced Visual Studio integrations such as code reviews and more importantly the Microsoft Test Manager.

My previous experience with TFS was with 2005 or 2008 (I can't remember) and I have bad memories of it, although not quite as bad as my time with ClearCase.

What criteria should we be looking at in order to properly evaluate our move to TFS?

ContentLicense: CC BY-SA 4.0


问:
Can you help me understand this design pattern made by Java expert?
I inherited the project from a very experienced Java developer. The project is Android app and the guy who coded is is very experienced in coding regular Java apps. He introduced some file structures that I haven't come across before (I haven't coded Java apps outside Android area). I can follow the code with no problem and I actually have finished a few add-ons so far, but now I would like to know more of why he used such approach since it may help me myself write a better code. On the other hand, if his approach is not suitable for Android apps, I would like to know that as well so I don't use such structures.

I will divide all questions into points.

When dealing with a database, he made 3 layers: entities, data_access and controllers. This is a kind of MVC structure. Is it advised to use it in Android apps?

In controller part, he made the following file structure:

```<code>controller/
      async/
            AsyncAddObject.java
            AsyncExecutorAdd.java
            AsyncExecutorGetAll.java
          Entity1Controller.java
          Entity2Controller.java
          Entity3Controller.java
          IController.java
</code>```

All async files are the generics.

Is this structure familiar to you? I remember executors used in Java, but have never used such approach in Android development. If this is a proper way, what is Executor used for?

What about IController.java - something usual in regular Java coding?

+++++++++

Then when we want to add some entry into database, he uses the following code

```<code>Entity1 ent = new Entity1();
ent.setSomething(someParameter);

AsyncAddObject<Entity1> obj = new AsyncAddObject<Entity1>();
obj.setController(mEntity1Controller);
obj.setObj(ent);
new AsyncExecutorAdd<Entity1>().execute(obj);
</code>```

Does this look confusing to you? I usually call some database method and pass object to it. For example, I would do it like this

```<code>Entity1 ent = new Entity1();
ent.setSomething(someParameter);

MyDatabaseClass.addEntity1(ent); //just an example, adding to database will be done on non-Main thread.
</code>```

This is it. I apologize for a long post.

答:
On Android events are triggered on the main UI thread, but you can not do any work on the main UI thread.

What the developer might be doing is sending the task of addObject to another thread so that the main UI thread can continue.

Looks like he has created a few classes to make these kinds of tasks easy to do. This is good practice, but I am making an assumption. Without seeing the code of these files we won't know for sure.

In your example;

```<code>MyDatabaseClass.addEntity1(ent);
</code>```

If that is writing to a SQLite database on the Android device, then there is the risk that the database is stored on an SD card. SD cards are a bottleneck for performance on mobile devices, and this will block the main UI thread. You should not be doing any time consuming tasks on that thread.

I'm not even sure if Android will let you do it. There are some cases where the SDK will throw an exception if you attempt to do certain operations in the main thread.

Body:
On Android events are triggered on the main UI thread, but you can not do any work on the main UI thread.

What the developer might be doing is sending the task of addObject to another thread so that the main UI thread can continue.

Looks like he has created a few classes to make these kinds of tasks easy to do. This is good practice, but I am making an assumption. Without seeing the code of these files we won't know for sure.

In your example;

MyDatabaseClass.addEntity1(ent);

If that is writing to a SQLite database on the Android device, then there is the risk that the database is stored on an SD card. SD cards are a bottleneck for performance on mobile devices, and this will block the main UI thread. You should not be doing any time consuming tasks on that thread.

I'm not even sure if Android will let you do it. There are some cases where the SDK will throw an exception if you attempt to do certain operations in the main thread.


答:
The Rspec Book, among other BDD resources, suggests a cycle like this:

In essence, the process is:

```<code>While behaviour required
    Write an integration test for a specific behaviour
    While integration test failing
        Write a unit test to fulfil partial behavior
        While unit test failing
            Write code to make unit test pass
        Commit
        While refactoring can be done
            Refactor
            While unit test failing
                Write code to make unit test pass
            Commit
    Push
</code>```

Disclaimer: There's no doubt in my mind that this leads to the best code and product, but it can be time-consuming. There are all sorts of difficulties around data and determinism, when it comes to saying that integration tests should always pass. It's not appropriate in all circumstances; sometimes you just have to get stuff out of the door.

That said, having an ideal process in mind is great. It gives you a point from which to compromise.

Title: When should I write integration tests?

Body:
According to rules of TDD unit tests are written before production code, but what about Integration tests that exercises interaction between concrete (non mocks) wired objects?

Should they be written before unit tests or after production code just to test the "wiring" ?

Note that I'm not talking about Acceptance or functional tests but Lower level integration tests.

Body:
The Rspec Book, among other BDD resources, suggests a cycle like this:

In essence, the process is:

While behaviour required
    Write an integration test for a specific behaviour
    While integration test failing
        Write a unit test to fulfil partial behavior
        While unit test failing
            Write code to make unit test pass
        Commit
        While refactoring can be done
            Refactor
            While unit test failing
                Write code to make unit test pass
            Commit
    Push

Disclaimer: There's no doubt in my mind that this leads to the best code and product, but it can be time-consuming. There are all sorts of difficulties around data and determinism, when it comes to saying that integration tests should always pass. It's not appropriate in all circumstances; sometimes you just have to get stuff out of the door.

That said, having an ideal process in mind is great. It gives you a point from which to compromise.


问:
Align draggable elements in line and generate without overflow or new line
I have this script I'm working on.
What it should do is generate a new div every time I press a button and I've already done that, but those are not draggable. I think that happens because of the onLoad function but alternative do I have?
The second problem is that when I click one of the blue boxes, all of them must arrange in a line like you see them when you load my jsFiddle link, and if the line is full and you click the "New Square" button, instead of overflowing or add a new line, it would close the last box instead and add a new box before all of the other boxes.

I'm sorry to bother you with those questions, but I am a PHP and MySQL programmer, I just started using jQuery.

jsFiddle

HTML:

```<code><div id="container">
    <div class="round"></div>
    <div class="round"></div>
    <div class="round"></div>
    <div class="round"></div>
</div>
<br><br><br>
<input type="button" class="button" value="New Square">
</code>```

jQuery:

```<code>$('.round').draggable();

$('.button').click(
    function (){
$("#container").append("<div class='round'></div>");
    });

$('.round').click (

    );
</code>```

I had more code in jQuery, but I removed all of the useless options because I want you to easily understand what I want to do.

答:
you have to assign the draggable class to the newly created object:

```<code>$('.button').click(
   function (){
    $("#container").append("<div class='round'></div>");
    $(".round").draggable();
});
</code>```

That should do  it actually. Or Perhaps:

```<code>$("#container").append("<div class='round draggable'></div>");
</code>```

Body:
you have to assign the draggable class to the newly created object:

$('.button').click(
   function (){
    $("#container").append("<div class='round'></div>");
    $(".round").draggable();
});

That should do  it actually. Or Perhaps:

$("#container").append("<div class='round draggable'></div>");


问:
Is SQLite a sensible option for data logging?
I am trying to setup a small data-logging application under linux. The data arrives via serial port, and from there it should be pumped to logging and to graphical display.

The logging functionality is there for initialization purposes of the graphing functionality, after a reboot.

The data arrives every second and is composed of 1 number of 5 decimal digit precision, and should be logged for 2 years. My current free space is about 15GB.

The languages of the project so far are bash and python.

My objectives are to make simple but robust (maybe some live backups to a flash drive?) logging system, that is also fast and easy to read from python and write from bash.

Is SQLite suitable for this (I have never used it)? Is a text file in my home directory suitable for this?

答:
No. SQLite is a great tool, but it is not designed to insert very many records at high speed.

The best solution here is something that can be appended to quickly, and that's a file. Such a file can be located anywhere you like, on Linux they are usually put in /var/log (as some admins prefer to put /var on a separate partition so if a rogue app write a lot of data, it won't crash the OS when it fills the disk up).

Once the data is written, you can write a tool that reads the log files, imports them into a SQLite DB and uses that for reporting.

Alternatively, use an existing tool such as Nagios. Write a plugin for it (if you can't configure it to recognise your data directly in the log file) and use that for monitoring and reporting.


答:
Aside from acceptance tests, I tend to only write integration tests at the boundaries of an application, to verify that it integrates well with third-party systems or components.

The idea is to create adapter objects that translate from how the third party speaks to what your application needs, and test these translators against the real external system. Whether you do that test-first or test-last is I think less important than with your regular unit tests because

The design insight provided by TDD doesn't matter as much here since design is pretty much known in advance and there's typically nothing terribly complex involved, you just map things from one system to another.

Depending on the module/system you want to tackle, it can require a lot of exploration, configuration tinkering, sample data preparation, which takes time and doesn't fit really well in a short TDD feedback loop.

However, if you really feel more comfortable building your adapter incrementally in little secure steps, I'd definitely recommend going test-first, it can't hurt.

You can find examples of this approach here :
http://davesquared.net/2011/04/dont-mock-types-you-dont-own.html (6th paragraph)
http://blog.8thlight.com/eric-smith/2011/10/27/thats-not-yours.html

Title: When should I write integration tests?


答:
As @gbjbaanb pointed, SQLite "is not designed to insert very many records at high speed."

I'd say 1 number / 1 second is not high speed if you keep the connection to the database open. And that should work reasonably fine, but logs are usually made on files, that solution is more conventional and maybe elegant due to that.

I'd use text files and I would create a new one every month. You can compress and/or delete old files after some time that may suit for you if the HDD space is a problem.

If "The logging functionality is there for initialization purposes of the graphing functionality, after a reboot." and you only need a time window with the last n elements then you can add a finally block to your code and use pickle to dump some data structures and load them after the reboot. But make sure before that the reboot is actually allowing you to do what you need.

That is probably the solution that requires less resources and fits more tightly to your requirements.

Title: Is SQLite a sensible option for data logging?

Body:
I am trying to setup a small data-logging application under linux. The data arrives via serial port, and from there it should be pumped to logging and to graphical display.

The logging functionality is there for initialization purposes of the graphing functionality, after a reboot.

The data arrives every second and is composed of 1 number of 5 decimal digit precision, and should be logged for 2 years. My current free space is about 15GB.

The languages of the project so far are bash and python.

My objectives are to make simple but robust (maybe some live backups to a flash drive?) logging system, that is also fast and easy to read from python and write from bash.

Is SQLite suitable for this (I have never used it)? Is a text file in my home directory suitable for this?


答:
So I was going to accept the first answer but it has been deleted.

To sum it up

In a given iteration :

Write unit-test

Write production code

Write Integration tests to test interactions

Keep in mind integration testing while 1 and 2 to guarantee testability at the integration level.

Integration tests are not necessarily written end to end at step 3 they may be partially written between step 1 and 2.

Title: When should I write integration tests?


答:
Yes. SQLite is just a binary file. You just need to have an empty skeleton for your database once, then you are able to just append data to that binary file to fill up the "database".

In a former company we have implemented this for the Symbian OS (Using the c++ language), doing some kind of logging too. Unfortunately this was a while ago and I can not remember the details.


答:
I would say that given the requirements for robustness and longevity that a plain old text file is a better choice. As others have noted, your data rate is not high; also, your post-processing is all offline from the logging system so you need not write your data in the most efficient manner because you can read it back at leisure.

A filesystem is a database (although a degenerate one), and appends to text files are very light on system resources. It would be hard to beat

```<code>echo data >> mylogfile
</code>```

for minimal system call activity. Also text files are much more robust in the face of internal corruption than a sqlite db and especially a pickle file.

I'm guessing that your application is a remote, unattended sensor, somewhere not easy to get an operator to. In that case, the lowest tech solution should be preferred.

Body:
I would say that given the requirements for robustness and longevity that a plain old text file is a better choice. As others have noted, your data rate is not high; also, your post-processing is all offline from the logging system so you need not write your data in the most efficient manner because you can read it back at leisure.

A filesystem is a database (although a degenerate one), and appends to text files are very light on system resources. It would be hard to beat

echo data >> mylogfile

for minimal system call activity. Also text files are much more robust in the face of internal corruption than a sqlite db and especially a pickle file.

I'm guessing that your application is a remote, unattended sensor, somewhere not easy to get an operator to. In that case, the lowest tech solution should be preferred.


问:
How would my custom language be categorized?
I'm developing my own scripting language to solve some unique challenges for a project.

The language takes source code and converts the contents into tokens, and then a command factory is used to convert those tokens into something that can be executed.

An example of a script might look like this.

```<code>accept: always;
reject: title has "something" or body has "something else";
reject: title length < 10;
</code>```

Each line in the script ends with a ; terminator, and each line starts with a named rule that ends with :. Each rule uses a command followed by arguments. The commands can be joined together using logical operators. The number of arguments a command can have is fixed. So when I find a command I can expect X number of additional tokens for the syntax to be correct. The goal is human readable code because non-programmers will be using it.

An alternative way of writing the same above code using a C style structure would be.

```<code>accept(true);
reject(has(title,"something") || has(body,"something else"));
reject(length(title) < 10);
</code>```

What is the term used for a parser that handles a language where () for structuring arguments is omitted, and there are no clear boundaries defined for arguments.

I would like to read up on how these kinds of parsers are implemented. To ensure I'm not overly reinventing the wheel or running into common problems.

答:
Obligatory LISP:

```<code>(accept t)
(reject-if (or (has title "something) (has body "something else")))
(reject-if (< (length title) 10)
</code>```

Obligatory FORTH:

```<code>1 accept
"something" title has "something else" body has or reject-if
title length 10 < reject-if
</code>```

The key is that you don't have to write and debug a custom parser for either of these approaches.

Body:
Obligatory LISP:

(accept t)
(reject-if (or (has title "something) (has body "something else")))
(reject-if (< (length title) 10)

Obligatory FORTH:

1 accept
"something" title has "something else" body has or reject-if
title length 10 < reject-if

The key is that you don't have to write and debug a custom parser for either of these approaches.


答:
Martin Fowler's little survey says a lot about the state of TFS in previous years. 'dangerous' is quite right. (I think this refers to the way that it doesn't recognise changes made outside of VS, so you can create a WCF project, then use the external svcutil tool to create your client, then check all your changes in.. but TFS will happily ignore your client changes because they weren't made inside VS).

You have to count the cost : the required version of VS to get the goodies - code reviews, for example, require Premium edition which is significantly more expensive if you get VS via MSDN. Also, accessing the system for non-VS users is fine, but if they want the full access instead fo the cut-down web view, then you'll have to shell out for CALs for them. The overall cost of TFS can be quite a lot. Even the recent Forrester report (commissioned by Microsoft, so you have to read between the lines a little) says that TFS requires significant administration support - 2 consultants and 6 admins (who spent 25% of their time) were required to support TFS for their case study of 122 users (works out to 4.5 admins over those 122 users... this is a lot compared to just me setting up and maintaining a full SVN solution whilst also doing my day job). TFS can take a lot of effort to keep working as people expect.

In my experience with TFS2012 (forget previous versions as they're crap), is that is is a very complicated system administer, especially if you step outside the pre-defined setup. For example, if you use MSBuild to build everything, you're fine. But if you have, say, a load of old .vdproj propjects that are no longer supported by MSBuild, you have to edit the huge xaml build script to make it build these projects. After several days working on this, the best I could do was to rebuild the solution by passing it to devenv, and even then, getting the build results out and into the build summary was impossible. Similar results were had by other teams who used NUnit for their tests - if you use the built-in MSTest, then it works. Otherwise, you're pretty much stuffed.

As a user, I find that the integration is more of a nuisance. I prefer TortoiseSVN and I do nearly all of my SCM work via that (as it is an awesome tool). With TFS, you end up with a new screen inside VS for every operation. So you have a new tab in your environment for the team explorer, and another for the builds, and another for each build summary you want to see (and if you want to see the details of a build, an error for example, you have to click through too many links). I found the number of documents I had open when using TFS were more than the source files!

The same applies to checkins, committing changes required clicking through several tabs on the Pending Changes pane in VS to assign a work item and comment to your checkins. Its a small thing, but I found it annoying as I was used to more streamlined tools.

Extending the build system was another area that I found lacking. Adding new features into the build is difficult because of the xaml configuration, and getting the results of those features into your build screens is either very very hard, or impossible. So if you like adding stuff like code complexity or static analysis, or even automated testing via, say selenium, or deployments... forget it. Unless, you are using the Microsoft tools for these aspects (eg fxcop).

Updating the workflow was another niggle - though the powertoys helped tremendously, it was still awkward to get the workflow right,and you still can't configure the scrum board with the information you really want to see - again, you get the defaults or nothing.

Merging was also painful, I think there's a very good reason MS has adopted git for TFS (note this only works with brand new TFS projects, you cannot convert from TFS to git backends).

So all in all, its not too bad as it does work, but I have found a lot of other tools are much better. The disadvantage of those tools is that they don't come fully integrated, but IMHO this is a strength as you can pick and choose the best bits you want. With TFS you get pretty much what someone else wants you to have.  If you decide the bug system in TFS is poor (and I think you will), you'll have a hard time changing to a different one.

TFS should be considered along with other big, fat full-lifecycle tools. Most developers hate such things as they dislike the restrictions these tools end up imposing on them.

I would try it though, download the 30-day trials and install it. When evaluating remember to change a little bit here and there, don't just use it for a source code checkin, checkin with a workitem required and get reports based on that workitem. Try assigning a checkin to multiple workitems, and try combining workitems together as related. Try to incorporate something different into the build system, see how to get a daily progress report out of the reporting services, link a document to a workflow requirement and trace it through bug triage to coding to build to rework and then release. Branch and merge a lot. If you can't easily do all these things, then you might as well stick to git. There's not much point to using TFS if you don't take advantage of most of its ALM features.


问:
Status update & news feed database design / architecture
Imagine a application similar to Facebook, where you have status updates and a news feed.  The names and profile pictures can be changed.  There are also several different types of updates requiring a different layout template for each type.

I hate my implementation and would like some feedback on how to improve it.  When I store the status update in the database, I basically store the HTML template in the database with some of the update specific information in it as well.  Since the profile pic and poster name can change, I'm keeping placeholders in the HTML stored in the database like '{USER_PROFILE_PIC}' and replacing that with the most current value when the record is pulled & displayed.  I hate doing it this way because if we want to do a design change down the road, we are stuck with this HTML in the database.

I'm doing this all in SQL Server.  I'm open to other databases if needed, I just am looking for a good way to pull dynamic status updates from a database and display them with up to the moment info.

TIA

答:
Ok, if you're using mvc then you're definitely doing this a bit wrong...
Consider mvc, its the model => view => controller framework.
The whole point of the framework is to ensure a nice and clean separation of concerns.

When you start storing templates in your db, your muddling those concerns.
What I would do is convert each of my templates into a partial view.
The whole reason partial views exist is to serve as little code templates.

I would store the data only in the database.

So your app basically has this:

the db containing only the data required for a status update.
a controller that loads this data, and then passes it to the relevant view
a view that displays the data in its own required format.


问:
why is remainder of division, multiplied by divisor ? using operator %
I have started to learn Javascript. From book http://eloquentjavascript.net:

There is one more arithmetic operator which is probably less familiar to you. The % symbol is used to represent the remainder operation. X % Y is the remainder of dividing X by Y. For example 314 % 100 is 14, 10 % 3 is 1, and 144 % 12 is 0. Remainder has the same precedence as multiplication and division.

I don't understand, why it multiply the remainder fraction by divisor (after division). It is more complicated or less accurate.

10 / 3 = 3.3333  (a recurring decimal number). 10 % 3 = 1 (0.333 * 3 = 0.999 (not 1 )

What is purpose of this strange remainders ?

Thanks

答:
There are several answers possible to this question from different points of view.

Lets start with the practical approach. There are simply things that can only be divided in units of one. At the same time there may for a given problem be the constraint that all parts have to be equal. If you want to divide ten cents between three people and each of them to get an equal share then you are left with one cent. If you have a screen with 128 pixels width and a table with ten columns each one can have 12 pixels and you are left with 8 pixels. Divide those by two and you know where to place the table to center it.

From a mathematical view: Here it can simply be a matter of definition which number system you have to use (natural numbers, integers, rationals etc.). If your calculation is limited to natural numbers or integers then there are no decimal places. There is a clear definition for this in mathematics: Remainder (I am no mathematician so I hope this explanation isn't too much simplified)

For computers and programming languages there is often a strong difference between integers and floating point numbers because their binary representation is different. Today it doesn't make such a big difference any more but integer operations were faster than a floating point operation. And the number of bits that can be used to hold a number is limited, therefore recurring decimals are not possible (there are exceptions in some languages or libraries) which would lead to results of such a calculations not being exact. As you can see from Benjamin's link, in mathematics 0.999... would equal 1, for a computer this would not be the case.

Many programming languages have different data types for integers and floats. Javascript does not make this differentiation. But for many reasons (as in my examples above) it still has the modulo operator since there are practical applications as much as it simply completes the set of mathematical operators for a well defined operation.


答:
It's one of those operators that you think you'll never use and then you find irreplaceable.

One example is looping through an indexed item:

```<code>i++;
if (i % 5 === 0) {
   i = 0;
}
</code>```

Obviously, that can be simplified but that's the idea spelled out.

The result is:
1, 2, 3, 4, 0, 1, 2, 3, 4, etc...

[Edit]

Also, to answer the question I think that you might be asking...

It may help to think in fractions:

10 / 3 = 3 ⅓

  ⅓ * 3 = 1

See also : Euclidean Division

Title: why is remainder of division, multiplied by divisor ? using operator %

Body:
I have started to learn Javascript. From book http://eloquentjavascript.net:

There is one more arithmetic operator which is probably less familiar to you. The % symbol is used to represent the remainder operation. X % Y is the remainder of dividing X by Y. For example 314 % 100 is 14, 10 % 3 is 1, and 144 % 12 is 0. Remainder has the same precedence as multiplication and division.

I don't understand, why it multiply the remainder fraction by divisor (after division). It is more complicated or less accurate.

10 / 3 = 3.3333  (a recurring decimal number). 10 % 3 = 1 (0.333 * 3 = 0.999 (not 1 )

What is purpose of this strange remainders ?

Thanks

Body:
It's one of those operators that you think you'll never use and then you find irreplaceable.

One example is looping through an indexed item:

i++;
if (i % 5 === 0) {
   i = 0;
}

Obviously, that can be simplified but that's the idea spelled out.

The result is:
1, 2, 3, 4, 0, 1, 2, 3, 4, etc...

[Edit]

Also, to answer the question I think that you might be asking...

It may help to think in fractions:

10 / 3 = 3 ⅓

  ⅓ * 3 = 1

See also : Euclidean Division


答:
It's the modulo operator. It's not unique to JavaScript. It's a Discrete Math concept. And it's very useful in a lot of ways. Of particular interest in computer science, it's an important operation in cryptography.

But, and maybe this is more what you're looking for, it doesn't correlate perfectly with the "normal" math operations because it's a discrete math function. (Which generally means you're dealing with integers.)


问:
Techniques to Enable Dynamic Query / Calculation at Runtime
I'm working on a C# project which provides users an on-demand method of importing data from various formats and then performs mail-merge-like actions to complete a template. The process works for basic data types. However, I need to add the ability to perform calculations on the existing data (which is not present in the source) so the results can be placed on the output.

Example 1:

Date range -- if there is data in both the start date and end date fields then the output should contain the two dates separated by " - ". If only one is present then just that date is output.

Example 2:

Conditionals -- if data in field X meets criteria Y then output Z.

Example 3:

Format text before conversion to number and format output as currency.

Source Field: "000059975"

Desired Output:  "$599.75"

Note that the text version of the number was of fixed length and included both whole and partial units of currency (dollars and cents in this case).

I understand how to perform these actions in code; however, all configuration of the data sources and the "calculated" fields must be done at runtime via strings. All data, once imported, is placed in a DataTable, so any solution will have access to the capabilities thereof in C# 4.

Some ideas I've considered so far:

lambda functions with a regex replace

direct C# expressions

scripting language (e.g., SQL / JavaScript / Python) processing

A DSL (though I have no experience with designing/implementing such)

I've not successfully identified a way to implement any of the above possibilities. Note also that while this is an internal business application which will largely be used by a small group of IT staff, I'd prefer to stick with a solution which limits the possibility of arbitrary code execution.

What techniques exist to address this need?

答:
It appears that there are a few possible solutions:

Reflection -- Reflection.Emit

CodeDOM -- System.CodeDom

Expression -- System.Linq.Expressions.Expression

CSharpCodeProvider -- Microsoft.CSharp.CSharpCodeProvider

Edit

CSharpCodeProvider ended up being the most straightforward solution. I used the technique detailed at Treating C# Like A Scripting Language and it worked perfectly.


答:
I tend to view integration tests as very similar to unit tests.  In that I am treating a subset of the code as a black box.  So integration tests are just a bigger box.

I prefer to write them before the production code.  This has the advantage of helping me remember which pieces I haven't wired up yet or that I changed a detail in the objects interaction slightly.

Title: When should I write integration tests?


问:
Are Frequent Complicated Merge Conflicts A Sign of Problems?
On our team, we use Git as our source control. We have several areas of code that are almost independent but have some overlap. Lately we have been discussing workflows and approaches to using source control. One complaint that comes up when I promote using a feature branch workflow is that people often run into complicated merge conflicts that they incorrectly resolve. By complicated, I mean "not obvious as to how to resolve". In light of this, other workflows are being more actively used, such a "pull rebase"-based workflow.

As an advocate of the feature branch approach, I'm not really getting the complaint. Yes, you have to keep your local feature branches up-to-date from master or wherever, but that's about the only real problem I see. I'm thinking that if your merges are always complicated and may have secondary effects, then that's more of a teamwork problem than a Git problem.

Am I correct in thinking this? Are complicated merge conflicts a sign of anything good or bad?

答:
I am used to the "fetch-rebase-push" workflow. Which is actually the first, most primitive, workflow, that is described in your tutorialHere are the advantages:

True continuous integration

Early conflict management - right after one has written and tested the code

Rapid response - "-Hey, Bob, the cubic interpolation you wrote is giving funny output, could you look at it while I am at lunch?"

No merge commits - clean timeline as if one developer wrote everithyng

Now, concerning complicated merge conflicts. I do not understand how one could experience both frequent and complicated merges. Complication arises from not rebasing/cherry-picking for a long time, working on that lone feature for a month.

I personally would prefer to deal with frequent, easy merge (actually rebase) conflicts, rather than rare, all-encompassing merge horror.


问:
Is state pattern a good solution for implementing UI changes for Landscape and Portrait modes?
For our iOS app, a lot of complicated UI logic depends on the interface orientation of the ViewController. This conditional logic is present in a lot of places.

Can it be segregated into different states in form of objects?

答:
Yes, you can utilize the State Pattern to separate out each UI widget's layout logic into distinct classes depending on orientation.  But realize that this potentially triples the class count for your UI widgets, and forces many to be re-created each time orientation changes.

If you go forth with said pattern, make sure that you have each Widget defined properly, and then have distinct landscapeWidget and portaitWidget objects that inherit from the widget.  (Rather than placing non-layout code in both, which would be copy and paste programming.)

Of course, realize that you will eventually need to adjust the UI again, when Apple releases an iOS DVR or an iOS watch.  You may be better off defining a layoutManager that organizes your UI, and having all of the layout logic in there, rather than having the individual UI elements have distinct classes.  Tell the individual widget elements how much X and Y they have, and don't make them worry about the entire screen.


答:
Merges and rebases should cause the exact same conflicts, for those inherent conflicts that a human must resolve (i.e. two developers changing the same line of code).  For other conflicts, merges actually tend to be cleaner, because you're not changing the SHA-1 of commits all over the place.  I'm not sure how you're managing to get into a state where merges cause more conflicts than rebases, but it's certainly a sign that some people's workflow is messed up, and they probably need more training on how git works.  Are they removing other people's merge commits when they do their local rebases, or something like that?

The benefit and drawback of the pull-rebase method is it's very similar to centralized workflows that a lot of people are used to.  You don't have to understand branching in order to use it.

At any rate, it's perfectly feasible to do a feature branch workflow only locally, if you can't get other people to sign on to it.

Title: Are Frequent Complicated Merge Conflicts A Sign of Problems?

Body:
On our team, we use Git as our source control. We have several areas of code that are almost independent but have some overlap. Lately we have been discussing workflows and approaches to using source control. One complaint that comes up when I promote using a feature branch workflow is that people often run into complicated merge conflicts that they incorrectly resolve. By complicated, I mean "not obvious as to how to resolve". In light of this, other workflows are being more actively used, such a "pull rebase"-based workflow.

As an advocate of the feature branch approach, I'm not really getting the complaint. Yes, you have to keep your local feature branches up-to-date from master or wherever, but that's about the only real problem I see. I'm thinking that if your merges are always complicated and may have secondary effects, then that's more of a teamwork problem than a Git problem.

Am I correct in thinking this? Are complicated merge conflicts a sign of anything good or bad?


问:
Is it possible to reach absolute zero bug state for large scale software?
I am talking about 20-30+ millions lines of code, software at the scale and complexity of Autodesk Maya for example.

If you freeze the development as long as it needs to be, can you actually fix all the bugs until there is simply not a single bug, if such a thing could be verified by computers? What are the arguments for and against the existence of a bug-free system?

Because there is some notion that every fix you make creates more bugs, but I don't think that's true.

By bugs I meant from the simplest typos in the UI, to more serious preventative bugs that has no workaround. For example a particular scripting function calculates normals incorrectly. Also even when there are workarounds, the problem still has to be fixed. So you could say you can do this particular thing manually instead of using the provided function but that function still has to be fixed.

答:
A fair proportion of the "bugs" that I have encountered might more properly be described as mismatches between system design and customer expectation.

Now, whether we call these bugs or not is academic, but the fact remains that a good deal of maintenance work arises as a direct result of imperfect communication and shifting customer expectations.

Even if a system is technically, provably "correct" in the sense of meeting a spec, (however improbable that might be for real-world commercial software), then you will still have the problem of matching the software's function to your customer's ever-shifting and poorly defined expectations.

In short:

No.


答:
It's not impossible that the problem is your code. If your codebase has a lot of inter-relationships between modules, then every change is going to have tendrils everywhere, and every a dev interacts with anyone else's code, it's going to be a nightmare.

I'd tend to think you'd notice this in other ways first, but it's possible that you're so used to it that you can't see it anymore.


答:
UIViewController is capable of handling this directly.

Let's assume most of your views' frames are being set at the same time (in your ViewController), Move all the frame setting code into one method.

```<code>-(void)setAllFrames;
</code>```

This method will set each subview's frame according to the current interface orientation, so it will contain the logic to determine what each frame should be based on orientation.  So when the view first loads you call [self setAllFrames]; and all the frames will be adjusted properly according to the interface orientation.

Now when the interface orientation changes, just call that method.

Title: Is state pattern a good solution for implementing UI changes for Landscape and Portrait modes?

Body:
For our iOS app, a lot of complicated UI logic depends on the interface orientation of the ViewController. This conditional logic is present in a lot of places.

Can it be segregated into different states in form of objects?

Body:
UIViewController is capable of handling this directly.

Let's assume most of your views' frames are being set at the same time (in your ViewController), Move all the frame setting code into one method.

-(void)setAllFrames;

This method will set each subview's frame according to the current interface orientation, so it will contain the logic to determine what each frame should be based on orientation.  So when the view first loads you call [self setAllFrames]; and all the frames will be adjusted properly according to the interface orientation.

Now when the interface orientation changes, just call that method.


答:
The project I am working on has this type of problem from time to time and it seems to result from a couple of factors:

We are using Visual Studio and files like the Visual Studio .sln are just XML documents ( which don't respond well to textual merges ) full of Guids ( which Git can't understand any better than the rest of us ) and can easily be badly merged and cause files to be lost.

Some people are working on similar areas of the code, so that the changes getting pushed can be right next to each other in classes. Although unavoidable in this situation, this type of configuration is going to be very hard work for any source control system. Even if you have great communication in your team, sometimes people won't realise they are bumping into one another's code and conflicts arise.

I'm interested by the potential for Semantic Merge to help with some of those problems, but obviously that is only any use if you're working in a language it can parse and I haven't yet run into any significant challenges when I'm using it, so I can't vouch for its effectiveness.


问:
Benchmark of asynchronous code
Asynchronous programming seems to be getting quite popular these days. One of the most quoted advantages is performance gain from removing operations that block threads. But I also saw people saying that the advantage is not that great. And that properly configured thread pool can have same effect as fully asynchronous code.

My question is, are there any real benchmarks that compare blocking vs. asynchronous code? It can be any language, but I think C# and Java would be most representative. Not sure how good would this benchmark be with Node.js or similar.

Edit : My attempt at general question combined with unclear terminology seems to have failed. By "asynchronous code"  I mean what some answers described as event or callback programming. In the final result, operations that would block thread are instead delegated to some callback system so threads can be utilized better.

And if I wanted to ask specific question : Are there any benchmarks that compare throughput/latency gain of async/await server code in .NET? Or any other similar comparison?

答:
To benchmark asynchronous code, you measure its performance in the usual way, and compare it to its non-synchronous equivalent.

```<code>Time for Synchronous call to return to caller: 900 ms
Time for asynchronous call to return to caller: 50 ms
Time saved: 850 ms.
</code>```

Of course, you don't get that time savings for free; the resulting thread that is spun off from the asynchronous call must still spend 850 ms in the background completing its work, and if you spin up enough threads you will eventually run out of cores (on processor-bound tasks), so your mileage may vary.

To find out how much improvement you will get overall, you can run a load test.

Title: Benchmark of asynchronous code

Body:
To benchmark asynchronous code, you measure its performance in the usual way, and compare it to its non-synchronous equivalent.

Time for Synchronous call to return to caller: 900 ms
Time for asynchronous call to return to caller: 50 ms
Time saved: 850 ms.

Of course, you don't get that time savings for free; the resulting thread that is spun off from the asynchronous call must still spend 850 ms in the background completing its work, and if you spin up enough threads you will eventually run out of cores (on processor-bound tasks), so your mileage may vary.

To find out how much improvement you will get overall, you can run a load test.


答:
When people refer to the performance advantages of asynchronous code vs. blocking code, they are talking about within the context of a single thread.  If you stop for 2 seconds and do nothing while a web page is being downloaded, that's obviously slower than continuing on doing other things while you wait.

Yes, thread pools can accomplish the same effect.  The difference is that asynchronous code is generally easier to write correctly compared to multithreaded code, and asynchronous code doesn't usually need a thread backing it, so it's lighter on resources.

For example, waiting on 100 network calls only requires 100 socket handles, instead of 100 socket handles and 100 threads.  This means benchmarks like latency for one web page download will be about the same, but asynchronous code will usually have advantages in things like number of simultaneous sockets.  Which kind of benchmark you use depends on your use case.

Title: Benchmark of asynchronous code

Body:
Asynchronous programming seems to be getting quite popular these days. One of the most quoted advantages is performance gain from removing operations that block threads. But I also saw people saying that the advantage is not that great. And that properly configured thread pool can have same effect as fully asynchronous code.

My question is, are there any real benchmarks that compare blocking vs. asynchronous code? It can be any language, but I think C# and Java would be most representative. Not sure how good would this benchmark be with Node.js or similar.

Edit : My attempt at general question combined with unclear terminology seems to have failed. By "asynchronous code"  I mean what some answers described as event or callback programming. In the final result, operations that would block thread are instead delegated to some callback system so threads can be utilized better.

And if I wanted to ask specific question : Are there any benchmarks that compare throughput/latency gain of async/await server code in .NET? Or any other similar comparison?


答:
Actually both approaches have their set of disadvantages. It's rather complicated subject going way beyond just threads vs events.

I recommend that you read excellent "Concurrent Programming for Scalable Web Architectures", either whole thing (which I recommend) or at least sections 4.2 Server Architectures and 4.3 Case of Threads vs. Events.

Title: Benchmark of asynchronous code


问:
Weird UIView transforms in Retina iPhone
I'm having a problem I don't understand. I'm developing an OpenGL app for iOS. Because at some points I want to force the orientation of the view programatically, and Apple for whatever reason doesn't make it easy (or even possible), I'm doing it by hand.

I return always NO in shouldAutoRotateToInterfaceOrientation, and when I want to change the orientation (to portrait, for example), I do something like this in the UIView:

```<code>[self setTransform:CGAffineTransformMake(1, 0, 0, 1, 0, 0)];
[self setBounds:CGRectMake(0, 0, 768, 1024)];
</code>```

This works fine.

In order to support Retina devices, I started checking [UIScreen mainScreen].scale, and setting self.contentScaleFactor accordingly. I also modified the code above to account for the new dimensions, like this:

```<code>[self setTransform:CGAffineTransformMake(1, 0, 0, 1, 0, 0)];
[self setBounds:CGRectMake(0, 0, 2*768, 2*1024)];
</code>```

Same rotation, different size. The weird result with this is that I get a "screen" with the right size, but offsetted half a screen to the bottom and the left. To correct for this, I need to do the following:

```<code>[self setTransform:CGAffineTransformMake(1, 0, 0, 1, 0, 0)];
[self setBounds:CGRectMake(-768, -1024, 2*768 - 768, 2*1024 - 1024)];
</code>```

This works, but it's ugly, I also need to make similar corrections when I get touch coordinates, and worst of all, I don't understand what's going on or why the above "correction" works.

Can anyone shed some light on this issue?

答:
Don't hard-code screen size values!

If you get screen size values from [[UIScreen mainScreen] bounds]:

Take the status bar height into account.

If portrait: set width to screen height and height to screen width

-- Look at my code to see what I'm talking about: UIScreen+Flexible category.

If you get screen size values from the parent View:

Make sure you aren't setting any frames before the parent view's frame is set.

Also, Use setFrame. I can't think of a case where you should be setting bounds?*

*I may be wrong about bound-setting.


答: Unless developers are modifying historical commits (instead of pure merges), the conflicts in a feature workflow type git model are a sign of a tightly coupled codebase (/brandnew codebase) or overlapping feature assignment.</p>


答:
Regardless of how you define asynchronous programming, there's no global answer. Some programming problems are more efficiently solved with threads (or "asynchronous programming"), others will just be taking an unnecessary performance hit by spinning up a new thread (or sending a job off to a thread). When you have a particular problem with two solutions, you'll just need to benchmark the performance -- from start to finish -- of each prospective solution.

A few indicators that a job may benefit from a threaded/asynchronous solution:

There are multiple, potentially long-running calculations that can be performed independently of each other

There are "distant" data-fetches/puts (via HTTP, for instance) alongside other code that doesn't depend on the data

There are many medium-to-long data-fetches, interactions, or calculations that can be run independently of each other

Or more basically, if you reach a point in code wherein you need to doSomething() and you know that

doSomething() will take a "long" time, and ...

You can continue doing other urgent, important, and/or time-consuming things while you wait for doSomething(), then ...

... it's probably advantageous to run doSomething() asynchronously. (But, you still have to benchmark, even if "informally", to know for sure!) Whether you're explicitly aware that doSomething() has it's own thread or simply that you called doSomethingAsync() instead is up to you and/or your framework ...

Title: Benchmark of asynchronous code


答:
All async programming(in node and other single threaded async implementations) does is hide latencies by being able to continue working while you wait for external resources, and being able to request multiple external resources at the same time so that their latencies overlap.  There should be no difference between async and threads if the use of threads is limited to resource waiting and you don't overly tax the system with threads.

There are some async implementations that run the async tasks on a thread pool, for those implementations I wouldn't expect there to be any difference besides the difference in library overhead and library smartness in thread management.

http://www.ducons.com/blog/tests-and-thoughts-on-asynchronous-io-vs-multithreading

Title: Benchmark of asynchronous code


问:
Matrix Pattern Recognition Algorithm for a 2D space
I have a picture that I elaborate with my program to obtain a list of coordinates.

There is a matrix represented in the image.
In an ideal test I would get only the sixteen central points of each square of the matrix.
But in actual tests I have some noise points.

I want to use an algorithm to extrapolate from the list of the coordinates the group formed by 16 coordinates that best represent a matrix.

Example of found points:

Example of desired result:

How to do this?

Note: The matrix in the image can be rotated a little too, so a rotation-independent algorithm would be great.

答:
Now I'm using an algorithm that worked very well for me.

This is the pseudo code:

```<code>for each pair of points (p1, p2):
    let d be the distance vector (x and y) between them
    if d.x > (image.width-p1.x)/3 or d.y > (image.height-p1.y)/3:
        continue
    let d_t be d turned 90 degrees (d.y, -d.x)
    for i from 0 to 3:
        for j from 0 to 3:
            if there is no point at p1 + i*d + j*d_t:
                continue outer loop
    if you get here, you have a 4*4 grid
</code>```

Body:
Now I'm using an algorithm that worked very well for me.

This is the pseudo code:

for each pair of points (p1, p2):
    let d be the distance vector (x and y) between them
    if d.x > (image.width-p1.x)/3 or d.y > (image.height-p1.y)/3:
        continue
    let d_t be d turned 90 degrees (d.y, -d.x)
    for i from 0 to 3:
        for j from 0 to 3:
            if there is no point at p1 + i*d + j*d_t:
                continue outer loop
    if you get here, you have a 4*4 grid


答:
About the verifying by computer part.

There are two ways to verify a program using a computer.  One is testing, the other is using proof system.

As soon as exhaustive testing isn't possible, testing becomes unable to show that a program doesn't have bugs, just that it has some. (And you have the issue to show that your tests themselves aren't testing for the presence of bugs).

To use a proof system, you start from formal requirements (and they may themselves have bug, hopefully the language used for the requirements will be more suitable to convince yourself that there is no bug there than with a programming language) and construct/prove with the help of proof systems that the program is bug free (and there is the question of bugs in the proof systems, but they proved themselves correct).  The current state of the art is a compiler for a C subset (and the subset isn't academic, "CompCert supports all of the MISRA-C 2004 subset of C, plus many features excluded by MISRA").

Title: Is it possible to reach absolute zero bug state for large scale software?

Body:
I am talking about 20-30+ millions lines of code, software at the scale and complexity of Autodesk Maya for example.

If you freeze the development as long as it needs to be, can you actually fix all the bugs until there is simply not a single bug, if such a thing could be verified by computers? What are the arguments for and against the existence of a bug-free system?

Because there is some notion that every fix you make creates more bugs, but I don't think that's true.

By bugs I meant from the simplest typos in the UI, to more serious preventative bugs that has no workaround. For example a particular scripting function calculates normals incorrectly. Also even when there are workarounds, the problem still has to be fixed. So you could say you can do this particular thing manually instead of using the provided function but that function still has to be fixed.


问:
What mistakes do your users make, and how can you update your application to handle them?
In fact this question is about cautions to be taken to enhance quality user experience and reduce avoidable support calls.</p>

答:
Almost every program that I write is invoked strictly from the command line. I've also written some fancier things that started out as CLI interfaces and rapidly grew into something more shell like than anything.

So, I can speak only for what I know. Here's some common issues with command line programs:

Way too many options

Unless you are writing a compiler or a line editor, try to keep options limited to one screen full on an 80x25 frame buffer when --help or /? is passed. It is perfectly fine to have more options than that, but break them into sub categories. For instance

foo --help

foo --help option_name

No long options

It is much easier to remember foo --attach_to [argument] --volatile --verbose than it is to remember foo -a [arg] -v +V. This isn't always possible, but in most cases, it is.

No input validation

Almost every platform has multiple libraries that are tried, tested and true when it comes to parsing and validating arguments. Almost every platform has a tried, tested and true lexer that validates input from a CLI. Use one, the other or both. If your program segfaults or divides by zero due to something a user provided, that's just embarrassing.

You might not need something as complex as a lexer, perhaps you can just tokenize the string if you are expecting stuff in a certain order with certain things in certain places.

I actually got a bug report once where an integer was expected and someone typed f*** my life in quotes. I didn't write that program, I had the misfortune of inheriting it.

No 'verbocity' knob

Allow experienced users to easily discover how to get way more noise out of your program than most people would tolerate, but default to printing serious and critical stuff only. I can't tell you how many times I had to fire up strace just to realize that something segfaulted because it operated on a NULL file stream.

You can also wrap assertions so that turning them off via NDEBUG or other means still results in something printed or logged for the user to find.

Speaking of log files, try to make sure anything you place in them makes (at least a little) sense to someone other than you. If the start of every entry is a UNIX epoch date, you're going to compound frustration in someone who really wants to help you reproduce the bug.

No 'bug buddy' in debug mode

A lot of programs offer some sort of 'debug' switch that offers extra chatter regarding what is going on with the program, but very few offer the following:

A way to automatically send a report via HTTP/HTTPS and get some kind of service reference number

A way to dump useful information to a file that could be sent as an attachment to a support request

Or, perhaps you like hearing people read the following over the phone:

It says unexpected condition at zero
  eff oh four zero oh .... OK lemme read that back to you ...

Overly complex configuration files

Don't justify the need to parse a config as an excuse to get a buzz on lots of syntactic sugar. Try to use a format that people actually know, even if it means extra work when parsing. I try to use the INI style format whenever possible. You'd be amazed what you can pull off with a simple key->value dictionary.

No configuration files

Don't make people write shell scripts or batch files just to use your program, unless it was intended to be a tool for either task. Give me a means to point at a file containing my usual options and provide just a few additional arguments.

No 'wet floor' signs

If some feature could get the user into trouble (perhaps it is there for advanced users), clearly mark it as such. Additionally, if someone fat fingers input or forgets something, have you program print a very friendly link to on-line documentation. You might be dealing with someone who is using your program via KVM and can't cut and paste.

When possible, (this coincides with input validation) use the Google apporach:

Did you mean foo --bar FILENME, you
  typed only foo --bar

Offer a way out of destructive instructions

The goal is to tell the user why it didn't work and have them try a few more times, while ensuring that you do nothing potentially destructive unless it appears that the user really wants you to do that. Allow a switch that turns off 'nagging' , for instance -Y or /Y but otherwise allow a way out for someone who simply has 'fat fingers'.

I'm probably forgetting a few pointers. I deal with this frequently as it is very, very difficult to make the 'low level' interface for something intuitive enough for most people to avoid making mistakes.

ContentLicense: CC BY-SA 2.5


问:
What must I take into consideration when designing a UI around a 0..1:1 relationship?
I'm designing the database schema for a new product feature. In my current design I have some related optional data. Rather than have nullable fields I have a separate table with a 0..1:1 relationship to the main table. I chose this design because the queries are simpler* if null data doesn't have to be taken into consideration.

The team lead pointed out to me that it will complicate data binding in the UI and suggested that I just use nullable fields. I am wondering what complications the optional table approach will introduce?

The obvious thing that comes to mind is the data aware controls can't bind to a closed data set so I'll need to either create a record on the fly when the user attempts to fill in the optional data or create the record at the same time as the main record, negating the purpose of have a separate table. Is there anything else I should be aware of?

Clarification

*Simpler, by which I refer to the dizzying amount of rules and ambiguities concerning null's behavior under different query scenarios in the SQL standard and the fact that no two vendors agree on which of these rules to implement.

答:
Assuming you're doing this in C#, which you don't specify, you could set up the main data object like this:

```<code>public class MainObj
{
    public int ID { get; private set; }
    public string Name { get; set; }

    private SubdataObj _data;
    public int? OptionalID
    {
      get
      {
         if (_data == null) return null;
         else return _data.OptionalID;
      }
      set
      {
         if (_data == null) _data = new SubdataObj();
         _data.OptionalID = value;
      }
    }
    class SubdataObj
    {
        public int OptionalID { get; set; }
    }
  }
</code>```

Just populate _data on object load if you can, or leave it null otherwise.  Note that OptionalID is a regular int, but we make it nullable when we expose it.  Doing it this way means you don't have to do anything special for the UI, although it does mean more work when modifying the SubdataObj's backing table.

Body:
Assuming you're doing this in C#, which you don't specify, you could set up the main data object like this:

public class MainObj
{
    public int ID { get; private set; }
    public string Name { get; set; }

    private SubdataObj _data;
    public int? OptionalID
    {
      get
      {
         if (_data == null) return null;
         else return _data.OptionalID;
      }
      set
      {
         if (_data == null) _data = new SubdataObj();
         _data.OptionalID = value;
      }
    }
    class SubdataObj
    {
        public int OptionalID { get; set; }
    }
  }

Just populate _data on object load if you can, or leave it null otherwise.  Note that OptionalID is a regular int, but we make it nullable when we expose it.  Doing it this way means you don't have to do anything special for the UI, although it does mean more work when modifying the SubdataObj's backing table.


问:
Choosing the simplest platform version of a source when porting to another platform
The question will sound weird as I'm not very experienced in C, C++ and ASM.

Let's say I have a hard time finding a C# managed, safe-code-only solution to solve a problem. Then I find that in 1998, some codes for (e.g.) a codec have been written in C for PPC, x86, arm, etc. This code can have 20000+ lines, and I need to port it.

Then I try one platform, and notice a lot of API call, CUDA stuff, inline assembler in most of the code. Etc.

Is there a preference, concerning portability, between PPC, PS2, x86, arm, sparc, etc, when porting to another platform that helps reducing the number of platform-specific code occurrence? I know that all these builds exist especially because there are specific features on each processors, but I wonder if some processors have less antennas, third eye, and four legs, and are less simpler (or "limited") than others.

I spent the last week porting codes, and had the intuition that focusing on certain aspects helps finding more cross-platform code. I may be wrong, and I - know - that it highly depends on skill. But that doesn't change anything to the fact that, e.g., a 20000 lines Java code may be easier to port to .Net for Windows Phone than a x86 asm code.

More specifically, my question is about a good approach when porting Orange to Peach, and avoiding going through several platform specific implementations.

答:
If I understand correctly, what you seem to be describing is that you have a highly-optimized C implementation of some codec that you need to bring to a platform-agnostic managed environment like .NET.

There are some problems with this.

A codec that has been optimized for several CPU architectures includes a lot of platform-specific code, because that's the only realistic way to achieve a level of performance that allows relatively real-time operation. This is why C and assembler were chosen over a managed language. (Setting aside the fact that it apparently predates most modern managed platforms - modern codecs like x264 and Vorbis are still written in C for this reason.) When performing complex transformations on large sets of data in a real-time setting, careful optimizations are made to account not merely for the CPU's features, but for the CPU's behaviors. The codec makes certain assumptions about the CPU's caches and timings to make the most of every single operation.

These kinds of optimizations are not possible in a managed environment. It is neither worth your time nor effort to port these kinds of things to a managed language.

Rather than porting this complex (and likely fragile!) code, you should instead use your chosen platform's ability to interact with unmanaged code. In .NET, you would probably want to use P/invoke to access the codec, and simply ship a pre-built copy of the codec for every platform you will deploy on.