问:
Should I take care of race conditions which almost certainly has no chance of occuring?
Let's consider something like a GUI application where main thread is updating the UI almost instantaneously, and some other thread is polling data over the network or something that is guaranteed to take 5-10 seconds to finish the job.

I've received many different answers for this, but some people say that if it is a race condition of a statistical impossibility, don't worry about it at all but others have said that if there's even a 10-53% (I kid you not on the numbers, this is what I've heard) of some voodoo magic happening due to race condition, always obtain/release locks on the thread that needs it.

What are your thoughts? Is it a good programming practice to handle race condition in such statistically-impossible situations? or would it be totally unnecessary or even counterproductive to add more lines of code to hinder readability?

答:
If it is truly a 1 in 10^55 event, there would be no need to code for it.  That would imply that if you did the operation 1 million times a second, you'd get one bug every 3 * 10^41 years which is, roughly, 10^31 times the age of the universe.  If your application has an error only once in every trillion trillion billion ages of the universe, that's probably reliable enough.

However, I would wager very heavily that the error is nowhere near that unlikely.  If you can conceive of the error, it is almost certain that it will occur at least occasionally thus making it worth coding correctly to begin with.  Plus, if you code the threads correctly at the outset so that they obtain and release locks appropriately, the code is much more maintainable in the future.  You don't have to worry when you're making a change that you have to re-analyze all the potential race conditions, re-compute their probabilities, and assure yourself that they won't recur.


答:
From the cost-benefit standpoint, you should write additional code only when it gets you enough benefit.

For example, if the worst thing that would happen if a wrong thread "wins the race" is that the information would not display, and the user would need to click "refresh", don't bother guarding against the race condition: having to write a lot of code is not worth fixing something that insignificant.

On the other hand, if the race condition could result in incorrect money transfers between banking accounts, then you must guard against race condition no matter how much code you need to write to solve this problem.

ContentLicense: CC BY-SA 3.0

Title: Should I take care of race conditions which almost certainly has no chance of occuring?

Body:
Let's consider something like a GUI application where main thread is updating the UI almost instantaneously, and some other thread is polling data over the network or something that is guaranteed to take 5-10 seconds to finish the job.

I've received many different answers for this, but some people say that if it is a race condition of a statistical impossibility, don't worry about it at all but others have said that if there's even a 10-53% (I kid you not on the numbers, this is what I've heard) of some voodoo magic happening due to race condition, always obtain/release locks on the thread that needs it.

What are your thoughts? Is it a good programming practice to handle race condition in such statistically-impossible situations? or would it be totally unnecessary or even counterproductive to add more lines of code to hinder readability?


答: Obtain and release the locks.  Probabilities change, algorithms change.  It's a bad habit to get into, and when something goes wrong you don't have to stop and wonder whether you got the odds wrong...</p>


答:
This would depend on the context.  If its a casual iPhone game, probably not.  The flight control system for the next manned space vehicle, probably.  It all depends on what the consequences are if the 'bad' result happens measured against the estimated cost of fixing it.

There is rarely a 'one size fits all' answer for these types of questions because they are not programming questions, but instead economics questions.


问:
Does "don't reinvent the wheel" ignore the limits of human memory?
One thing working in Haskell and F# has taught me is that someone in a university smarter than me has probably already found an abstraction for what I'm doing.  Likewise in C# and object-oriented programming, there's probably a library for "it", whatever it is that I'm doing.

There's such an emphasis on reusing abstractions in programming that I often feel a dilemma between: 1) just coding something short and dirty myself or 2) spending the same time to find someone else's more robust library/solution and just using that.

Like recently one of the coders here wrote up a (de)serializer for CSV files, and I couldn't help but think that something like that is probably very easy to find online, if it doesn't already come with the .NET standard APIs.

I don't blame him though, several times working in .NET I've patched together a solution based on what I know, only to realize that there was some method call or object or something  ,often in the same library, that did what I wanted and I just didn't know about it.

Is this just a sign of inexperience, or is there always an element of trade-off between writing new and reusing old?  What I hate the most is when I run across a solution that I already knew about and forgot.  I feel like one person just isn't capable of digesting the sheer quantities of code that comes prepackaged with most languages these days.

答:
Sometimes this is a sign of inexperience, whether with the particular language or with programming in general.  Sometimes, though, if the fit isn't obvious it's just better to roll your own code that does exactly what you want and nothing more.  Generic libraries, while often useful, can be built for requirements that you simply don't have, and in some cases this level of genericity can make them more trouble than they're worth.

Example:
For my small one-man projects, I never use a "real" logging library.  I use print statements plus a little ad-hoc configuration.  I don't want to be bothered with setting up and configuring a logging library that has way more features than I'll ever use, when print statements works fine for my purposes.  I also don't want yet another dependency that might not be compatible with the version of the compiler/interpreter I want to use, would have to be distributed, etc.

ContentLicense: CC BY-SA 2.5


答:
Finding a race condition is the hard part.  You probably spent almost as much time writing this question as it would have taken you to fix it.  It's not like it makes it that much less readable.  Programmers expect to see synchronization code in such situations, and actually might waste more time wondering why it's not there and if adding it would fix their unrelated bug.

As far as probabilities are concerned, you would be surprised.  I had a race condition bug report last year that I couldn't reproduce with thousands of automated tries, but one system of one customer saw it all the time.  The business value of spending 5 minutes to fix it now, versus possibly troubleshooting an "impossible" bug at a customer's installation, makes the choice a no-brainer.


答:
Simple vs correct.

In many cases, simplicity trumps correctness. It's a cost issue.

Also, race conditions are nasty things that tend not to obey simple statistics. Everything goes fine until some other seemingly unrelated synchronization causes your race condition to suddenly happen half the time. Unless you turn the logs on or debug the code of course.

A pragmatic alternative to preventing a race condition (which can be tricky) can be to detect and log it (bonus for failing hard and early). If it never happens, you lost little. If it does actually happen, you got a solid justification to spend the extra time fixing it.


问:
Why is using System.out.println() so bad?
Of course, it is very good use to use a logging framework for the error messages or warnings. But sometimes I use System.out.println() if I want to try something new in a short time.

Is it really so bad using System.out.println() for some quick test?

答:
There is nothing wrong with using it, it helps you figure out 'what the hell is going on'.

But if your peers/other devs/tools are ridiculing you, you could always use Logger, or start Junit testing!

ContentLicense: CC BY-SA 4.0


问:
Could implicit static methods cause problems?
This is a purely hypothetical question.

Say I create a class method that contains no references to instance variables or other resources.  For example (C#):

```<code>protected string FormatColumn(string value, int width)
{
    return value.Trim().PadLeft(width);
}
</code>```

As far as I can see, there is absolutely no reason why this method could not be declared static:

It only uses method-scope variables.

It doesn't override a base class method.

It's not virtual or abstract.

My questions are:

Is there any benefit to calling a static method over an instance method?

If so, why doesn't the compiler implicitly convert this to a static method?

I'm certain I've missed some key point here.  Any ideas?

答:
Since your method is not final (sealed)nor private, it means that it could be overridden by a child class, which is at least one reason why the compiler can't transform that method into a static method.

Now, if you make it either private or final (sealed), then there's no reason not to make it static, but then the performance improvement would be minimal, since it's only passing one less parameter (no need for virtual call if method is private and/or final)
Also, as Bernard said, that would also remove the null check on the instance, which could still occur even with a private or a protected method.

For example with this code :

```<code>public static staticMethod() {
    MyClass class= ...
    class.FormatColumn("a", 1) // this should throw an exception if column is null, but not when FormatColumn becomes static
}
</code>```

for a private method, I guess the compiler could check all calls from a static method and add necessary null pointer checks, since it has access to the whole class, but then we would probably lose in jumps what we saved by adding an additional pointer to this.

Body:
Since your method is not final (sealed)nor private, it means that it could be overridden by a child class, which is at least one reason why the compiler can't transform that method into a static method.

Now, if you make it either private or final (sealed), then there's no reason not to make it static, but then the performance improvement would be minimal, since it's only passing one less parameter (no need for virtual call if method is private and/or final)
Also, as Bernard said, that would also remove the null check on the instance, which could still occur even with a private or a protected method.

For example with this code :

public static staticMethod() {
    MyClass class= ...
    class.FormatColumn("a", 1) // this should throw an exception if column is null, but not when FormatColumn becomes static
}

for a private method, I guess the compiler could check all calls from a static method and add necessary null pointer checks, since it has access to the whole class, but then we would probably lose in jumps what we saved by adding an additional pointer to this.


问:
Caching's Effect on Program Performance
How does caching effect the performance of a running program? From my understanding, the assumption that each instruction always takes the same amount of time is not always correct, because of the effects of caching. How does caching affect algorithmic performance? Thanks in advance.

EDIT 1:
To further elaborate, lets say I'm running this Java program that's reading one million integers. From what I understand about this program, it's order of growth is cubic and will take a while to finish running. How would caching improve the performance of this program while it is running?

答:
Cache allows you to "cheat" an algorithm in its pure form and just look up a value instead of calculating it. There are less instructions to execute and therefore caching speeds up the performance.

http://qntm.org/fib

Title: Caching's Effect on Program Performance


答:
Caching is a very wide topic, but ultimately the goal is the same : to improve performance and reduce the load of IO, CPU or memory intensive operations. If you can elaborate on which type of 'algorithmic caching' you are referring to, we can answer more specifically.

Examples of types of caching:

In an application:

Data Caching - e.g. caching values, entities, graphs etc without needing to go back to the database, disk to fetch data.

Page Caching (Web Apps) - caching all or just part of a web page means that the server doesn't need to render the page again.

Specific to the Web, browser caches, and network caching devices like proxies, save load on a server entirely, with static files like .js, .css, images, etc.

And at a hardware level:

Compilers can use registers to cache memory

CPU's have caches to save time retrieving data from RAM (e.g. L1 and L2 cache)

Title: Caching's Effect on Program Performance

Body:
How does caching effect the performance of a running program? From my understanding, the assumption that each instruction always takes the same amount of time is not always correct, because of the effects of caching. How does caching affect algorithmic performance? Thanks in advance.

EDIT 1:
To further elaborate, lets say I'm running this Java program that's reading one million integers. From what I understand about this program, it's order of growth is cubic and will take a while to finish running. How would caching improve the performance of this program while it is running?


答:
When any kind of caching is in effect, there's a "best case" performance with 100% hits and a "worst case" performance with 0% hits.  A well designed scheme with a suitable program will get close to the best case performance.  The difference between best an worst cases can be enormous, 10x, even 100x.

Unfortunately, there's no guarantee or simple formula that will guarantee caches effectiveness.  A small change in the size of a program, or the size of it's data set, can result in huge and largely mysterious changes in performance.

Title: Caching's Effect on Program Performance


答:
The biggest issue with the occasional System.out.println, as I see it, is that it's a "bad habit smell(tm)". If you find yourself doing this, then you could probably improve your effectivity by getting more comfortable using your favorite debugger.

Also with a debugger, you know for certain that a breakpoint won't slip into your production code, while a System.out.println might.

On a side note, if you're actually just doing a quick test and persists with not using a debugger, I think System.out.println is better than using a logging framework, since if you accidentally leave a log.debug statement when you're done, it's harder to root out.

Title: Why is using System.out.println() so bad?

Body:
Of course, it is very good use to use a logging framework for the error messages or warnings. But sometimes I use System.out.println() if I want to try something new in a short time.

Is it really so bad using System.out.println() for some quick test?


答:
Caching is a technique that exploits the distance data is away from the requester. In a modern computer system architecture there are several levels of data layers. All of these layers appear are at varying distances from the requester (the CPU).

It is usually the case that the closest data layers have a higher cost per gigabyte. A higher cost per gigabyte means that there is almost always less available space in a closer data layer than a further away data layer. This difference in space is why we employ caching techniques in our computer systems and in our software. Techniques that try to bring most likely required items closer to the requester and push stale items away so that cache memory is not exhausted.

In order to take advantage of caches you have to be aware of two terms: spatial locality and temporal locality.

Spatial locality is a term used with addressing systems like computer memory. Modern processor caches pull data down in blocks of adjacent memory (memory 'near' another). Algorithms can take advantage of this by accessing memory sequentially in addresses that differ by small units (1 being optimum). An example of good spatial locality is the following:

```<code>int sum = 0;
int[] array = { /* Some massive array with data */ };

for (int i = 0; i < ARRAY_SIZE; i++) {
    sum += array[i]; // Access elements with an address difference of 1.
}
</code>```

Temporal locality is a term used to describe using something in cache frequently. Use of a cache item (i.e. a variable) over and over again results in less fetches from a further away data layer. Algorithms can exploit temporal locality by re-using variables frequently. An example of good temporal locality is the following:

```<code>int sum = 0;

for (int i = 0; i < 32; i++) {
    sum += i; // Frequent access of variables sum and i.
}
</code>```

It is worth checking out this link to see the differences in time of common places that data is stored in computing.

Title: Caching's Effect on Program Performance

Body:
Caching is a technique that exploits the distance data is away from the requester. In a modern computer system architecture there are several levels of data layers. All of these layers appear are at varying distances from the requester (the CPU).

It is usually the case that the closest data layers have a higher cost per gigabyte. A higher cost per gigabyte means that there is almost always less available space in a closer data layer than a further away data layer. This difference in space is why we employ caching techniques in our computer systems and in our software. Techniques that try to bring most likely required items closer to the requester and push stale items away so that cache memory is not exhausted.

In order to take advantage of caches you have to be aware of two terms: spatial locality and temporal locality.

Spatial locality is a term used with addressing systems like computer memory. Modern processor caches pull data down in blocks of adjacent memory (memory 'near' another). Algorithms can take advantage of this by accessing memory sequentially in addresses that differ by small units (1 being optimum). An example of good spatial locality is the following:

int sum = 0;
int[] array = { /* Some massive array with data */ };

for (int i = 0; i < ARRAY_SIZE; i++) {
    sum += array[i]; // Access elements with an address difference of 1.
}

Temporal locality is a term used to describe using something in cache frequently. Use of a cache item (i.e. a variable) over and over again results in less fetches from a further away data layer. Algorithms can exploit temporal locality by re-using variables frequently. An example of good temporal locality is the following:

int sum = 0;

for (int i = 0; i < 32; i++) {
    sum += i; // Frequent access of variables sum and i.
}

It is worth checking out this link to see the differences in time of common places that data is stored in computing.


答:
Caching is a simple trade off.  You save the time needed to compute a result at the expense of having to allocate memory for a lookup table that holds all the results you're likely to need.  Whether or not the trade off is worth it depends on how expensive computing the result is and how much memory a lookup table with all the results you're likely to need will consume.

EDIT: I was of course talking about lookup tables rather than pure caching, while they're closely related concepts they're not quite the same.  Chalk that one up to the morning coffee not being in full effect yet.

Caching is not just computing a result, but also storing it in a lookup table for future use as well, so a subsequent request for the same value returns the cached version instead of running the computation again.  Lookup tables is precomputing a large collection of values, or loading them from a data file, and putting them in a lookup table before any calls to the method are ever made.  the former will result in methods that are slower to execute the first time, but are faster on subsequent calls, but which cause memory usage to steadily increase.  The latter means paying a large cost in computing all the values up front and allocating a large chunk of memory for the lookup table, but pays off in always getting consistently fast results when the method is actually called and constant memory usage.

Title: Caching's Effect on Program Performance


答:
Building an entire testing strategy around echoing out the content of internal state isn't the smartest move but for quick and dirty tests of code in development the odd println here and there won't hurt as long as you remember to remove them!  </p>

<p>The danger of forgetting to remove them is probably why it's advised against.  </p>

Body:
Building an entire testing strategy around echoing out the content of internal state isn't the smartest move but for quick and dirty tests of code in development the odd println here and there won't hurt as long as you remember to remove them!

The danger of forgetting to remove them is probably why it's advised against.


答:
There are a few caveats about using System.out, even in throwaway code.

One major problem is that it's usually slow. For example, if you're trying to get a rough idea about the speed of some code (note that microbenchmarks are hard), then adding a single System.out.println() anywhere can really mess up your timing (because it's synchronizing and often waits for the actual output to be visible to the user before returning).

Other than that, I wouldn't worry too much about it in throwaway code. If you intend to commit it (be it as production code or as test code), then you should get rid of it and replace it with a propper logging call (yes, even in test code).


问:
Will apple approve app which internally uses library developed by Google?
I am using GDataXML library developed by Google as part of their Objective-C client library. As its Google’s XML processing library and I heard that Apple don't allow to use any third party libraries in app, will they allow this one?.
(I am using this library because many iOS geeks suggest to use this one!!).

Thanks in advance. :)

答: ahh ok.. I got it... Apps which uses any NON - Public i.e. Private API's get rejected, otherwise its not! And the API I am using is public. </p>


问:
Why should I declare a class as an abstract class?
I know the syntax, rules applied to abstract class and I want know usage of an abstract class

Abstract class can not be instantiated directly but can be extended by other class

What is the advantage of doing so?

How it is different from an Interface?

I know that one class can implement multiple interfaces but can only extend one abstract class. Is that only difference between an interface and an abstract class?

I am aware about usage of an Interface. I have learned that from Event delegation model of AWT in Java.

In which situations I should declare class as an abstract class? What is benefits of that?

答:
Interface -- when a few classes share an API (method names and parameters)

Abstract class -- when a few classes share same code (implementation)

In other words, you should start with a question: "do these classes necessarily share the implementation, or do they just have a common interface?"

If the answer is mixed, such as -- these three classes must share the implementation, but these other two only share their API -- then you can make an interface for all five of them, and an abstract class for those three with the common code.

There are also other ways to share implementation, for example to encapsulate an object with that implementation (e.g. in Strategy pattern).


答:
This (or a similar thing) has often happened to me in a previous job where the framework was suffering from severe Inner Platform Effect.

Basically, their code base evolved from early days Windows C/C++, then started to be compiled under MFC - and so the maintainers started mixing MFC and their old in-house data structures and windowing components. The inner platform wasn't very well documented, but it was supposedly "The Way" to do things on that product, due to some internal facilities that it provided. I often found it easier and quicker to write my own stuff from scratch (from MFC fundamentals), rather than work out how to do it with the company's internal framework.

(Okay, so this seems to be almost the opposite of your initial point - but the principle is the same, hehe! Yeah, sometimes it really is quicker to do your own thing than to spend time and effort to find an existing re-usable solution.)

Title: Does "don't reinvent the wheel" ignore the limits of human memory?

Body:
One thing working in Haskell and F# has taught me is that someone in a university smarter than me has probably already found an abstraction for what I'm doing.  Likewise in C# and object-oriented programming, there's probably a library for "it", whatever it is that I'm doing.

There's such an emphasis on reusing abstractions in programming that I often feel a dilemma between: 1) just coding something short and dirty myself or 2) spending the same time to find someone else's more robust library/solution and just using that.

Like recently one of the coders here wrote up a (de)serializer for CSV files, and I couldn't help but think that something like that is probably very easy to find online, if it doesn't already come with the .NET standard APIs.

I don't blame him though, several times working in .NET I've patched together a solution based on what I know, only to realize that there was some method call or object or something  ,often in the same library, that did what I wanted and I just didn't know about it.

Is this just a sign of inexperience, or is there always an element of trade-off between writing new and reusing old?  What I hate the most is when I run across a solution that I already knew about and forgot.  I feel like one person just isn't capable of digesting the sheer quantities of code that comes prepackaged with most languages these days.


问:
Why it is necessary to to test my iPhone app on actual iPhone device
I developed one application for iPhone and now I want it on App Store. So many my iOS geek friends told me to test it on actual device i.e. on iPhone.

So I wonder that why it is necessary to to test my iPhone app on actual iPhone device though they (Apple) have given "simulator" which is near about same as my device?

答:
You need to test application on real device to at least to look how it behaves with:

Real device hardware

Real internet connection (including the use of a cell network vs WiFi)

Your fingers instead of mouse

Performance with other apps running in the background

The limitations of the iPhone, like cpu, disk capacity and memory (A Simulator is not an Emulator).

Real context: is it easy to use your app on the train, or while walking down the street? How about in bright sunlight or in the rain?

iOS developers, please continue this list.


答:
The iPhone Simulator implements some APIs that the iPhone itself does not (The main one that comes to mind being the DOM XML API, where the iPhone only supports SAX to my knowledge, this might have changed though now.)

It will also let you 'feel' the app, are your buttons the right size? Do the right buttons fall under one's thumb? Is the iPhone up to running the app? The simulator is not an emulator and works by just adding Cocoa Touch to your desktop Mac for that app. You have to simulate out of memory warnings and the like.

Title: Why it is necessary to to test my iPhone app on actual iPhone device

Body:
I developed one application for iPhone and now I want it on App Store. So many my iOS geek friends told me to test it on actual device i.e. on iPhone.

So I wonder that why it is necessary to to test my iPhone app on actual iPhone device though they (Apple) have given "simulator" which is near about same as my device?


答:
One thing you'll never know when testing with emulator is how it really feels for a user holding a real device in their hand, sliding fingers on its screen. As a result, user actions that seemed smooth when simulating with touchpad on your laptop, may turn out quite cumbersome for a real device usage. To make sure that your application is OK, test it with real device.

Another thing worth testing with real device is battery consumption. That one is really safer to just test with real device than rely on how well simulator developers managed to reproduce it in their tool.

There may be other things that just aren't close enough at simulator. Audio volume and balance for example - the way it sounds on your laptop, may differ from how it will be on a real phone. Vibration is another example that is barely possible to get right with simulator. The way how gyro sensors work at the real phone. GPS / location related stuff. Etc etc etc...

Simulator vs real device testing is quite an important issue. In one of my past projects, an important part of commercial success was a careful balancing between these kinds of testing, which essentially boils down to permanently re-asking questions like why on device?

Real work starts when one asks why, picking the reasons to choose between on-device and simulator testing in particular cases and situations.

Ignoring device testing exposes your product to a (pretty high) risk of breaking right in the hands of end user, completely destroying all the efforts you put into development. But thing is, simulator testing is much MUCH cheaper and much easier for automation. If one blindly sticks to on-device-only testing, their releases might become substantially later and more expensive than those of competitors.


答:
If your race-condition is security-related, you should always code to prevent it.

A common example are race conditions with creating/opening files in unix, which can in some circumstances lead to privilege escalation attacks if the program with the race condition is running with higher privileges than the user interacting with it, such as a system daemon process or worse still, the kernel.

Even if a race condition has something like 10^(-80) chance of happening randomly, it may well be the case that a determined attacker has a decent chance of creating such conditions deliberately and artificially.


问:
How related is coding/information theory to computer networking?
I am taking a networking class(data communication) this coming semester. In many courses in my computer engineering degree, the books lack mathematical content. I am not a math wizard, but I think mathematics has the potential to give a much deeper understanding of different concepts, but it requires more work. </p>

<p>Is it a good idea to focus on information theory(found a cool book by a researcher from Bell Labs) and use a more "high level" book like Computer networking, A top down approach as supplementary text? </p>

答:
At the very lowest level, information theory is highly relevant to networking, as it lays the foundation for getting the best combination of peak bandwidth and error resilence from your hwardware.

However, that part is probably not going to be covered in much detail in a class on networking, as it's mainly relevant to hardware developers. Higher levels of the networking stack are probably going to get more attention. So it's probably not ideal to focus your attention on that part.

But this is guesswork - why not ask the professor who will hold the class?


答:
When we implement things for iOS (or android, or windows phone), we develop not for the desktop but for the device. For some calculation/resource-heavy applications, this may mean to normal behavior on the simulator BUT issues on the actual device.

So situations like this can be encountered in later stages if we do not test on device from the beginning:-

Memory warnings/crashes

Single-digit OpenGL frame rates


问:
Which language features are considered harmful?
Please, explain why and list which languages have the (mis)feature implemented As far you know.

Post what you consider a harmful feature, not what you dislike.

答:
Although some folks disagree with the man or various things he says, a lot of Douglas Crockford's JavaScript: The Good Parts is basically this question applied to JS.  Amongst Crockford's complaints:

Global scope by default for everything (DC shows how to use function/objects as namespaces and scope delimiters to wrangle this in.)

Statements like with, whose failure behavior is to define things at the global namespace. (Gah! Its like the JS motto is if you fail, then fail as hard as possible!)

Unexpected behavior with the == operator, which basically requires you to always use the === operator.

Semicolon insertion.

Really a whole lot of JS should be considered harmful, maybe even the whole language, but the good parts are just so darn good that it kind of makes up for it (at least for me.)


问:
printf - source of bugs?
I'm using a lot of printf for tracing/logging purposes in my code, I've found that it's a source of programming error. I always found the insertion operator (<<) to be somewhat of a odd thing but I'm beginning to think that by using it instead I could avoid some of these bugs.

Anyone ever had a similar revelation or I'm just grasping at straws here?

Some take away points

My current line of thinking is that type-safety outweighs any benefit
of using printf. The real problem is the format string and the use of
non type-safe variadic functions.

Maybe I won't be using << and the stl output stream variants but I will certainly look into using a type-safe mechanism which is very similar.

A lot of the tracing/logging is conditional but I'd like to always run the code to not miss bugs in tests just because it's a rarely taken branch.

答:
Printf syntax is basically fine, minus some of obscure typing. If you think it's wrong why C#, Python and other languages use the very similar construct? The problem in C or C++: it's not part of a language and thus not checked by compiler for correct syntax(*) and not decomposed into series of native calls if optimizing for speed. Note that if optimizing for size, printf calls might turn out more efficient!
C++ streaming syntax is imho anything but good. It works, type-safety is there, but the verbose syntax... bleh. I mean I use it, but with no joy.

(*) some compilers DO this checking plus almost all static analysis tools (I use Lint and never had any problem with printf since).

Title: printf - source of bugs?


答:
You are not supposed to use printf in C++. Ever. The reason is, as you correctly noted, that it's a source of bugs and the fact that printing custom types, and in C++ almost everything should be custom types, is pain. C++ solution is the streams.

However there is a critical problem that makes streams unsuitable for any and user-visible output! The problem is translations. Borrowing example from the gettext manual say you want to write:

```<code>cout << "String '" << str << "' has " << str.size() << " characters\n";
</code>```

Now the German translator comes along and says: Ok, in German, the message should be

n Zeichen lang ist die Zeichenkette 's'

And now you are in trouble, because he needs the pieces shuffled around. It should be said, that even many implementation of printf have problem with this. Unless they support the extension so you can use

```<code>printf("%2$d Zeichen lang ist die Zeichenkette '%1$s'", ...);
</code>```

The Boost.Format supports printf-style formats and has this feature. So you write:

```<code>cout << format("String '%1' has %2 characters\n") % str % str.size();
</code>```

Unfortunately it carries a bit of performance penalty, because internally it creates a stringstream and uses the << operator to format each bit and in many implementation the << operator internally calls sprintf. I suspect more efficient implementation would be possible if really desired.

Title: printf - source of bugs?

Body:
I'm using a lot of printf for tracing/logging purposes in my code, I've found that it's a source of programming error. I always found the insertion operator (<<) to be somewhat of a odd thing but I'm beginning to think that by using it instead I could avoid some of these bugs.

Anyone ever had a similar revelation or I'm just grasping at straws here?

Some take away points

My current line of thinking is that type-safety outweighs any benefit
of using printf. The real problem is the format string and the use of
non type-safe variadic functions.

Maybe I won't be using << and the stl output stream variants but I will certainly look into using a type-safe mechanism which is very similar.

A lot of the tracing/logging is conditional but I'd like to always run the code to not miss bugs in tests just because it's a rarely taken branch.

Body:
You are not supposed to use printf in C++. Ever. The reason is, as you correctly noted, that it's a source of bugs and the fact that printing custom types, and in C++ almost everything should be custom types, is pain. C++ solution is the streams.

However there is a critical problem that makes streams unsuitable for any and user-visible output! The problem is translations. Borrowing example from the gettext manual say you want to write:

cout << "String '" << str << "' has " << str.size() << " characters\n";

Now the German translator comes along and says: Ok, in German, the message should be

n Zeichen lang ist die Zeichenkette 's'

And now you are in trouble, because he needs the pieces shuffled around. It should be said, that even many implementation of printf have problem with this. Unless they support the extension so you can use

printf("%2$d Zeichen lang ist die Zeichenkette '%1$s'", ...);

The Boost.Format supports printf-style formats and has this feature. So you write:

cout << format("String '%1' has %2 characters\n") % str % str.size();

Unfortunately it carries a bit of performance penalty, because internally it creates a stringstream and uses the << operator to format each bit and in many implementation the << operator internally calls sprintf. I suspect more efficient implementation would be possible if really desired.


问:
What are the benefits of prefixing function parameter names with p*?
I often see projects (in Java projects and teams using Eclipse) that prefix function parameters with p.

For example

```<code>public void filter (Result pResult) ...
</code>```

I personally don't see any benefit in this, but would like to know what the reasoning is. The best explanation I've heard yet is that it is to distinguish the name of identical named fields.I have my issues with that explanation but I can understand the point.

答: The practices of adding meaningful prefixes to symbols, such as the well-publicized Hungarian Notation, date back to the times when IDEs did not exist or were too primitive. Today, when finding a point of declaration is a mouse click away, there is no point in spoiling the most precious part of the name, its first few letters, by assigning a common prefix.


答: As you suspect, it is to avoid name collisions between the parameter name and either member or local variable names.  Member variables are sometimes given a prefix for the same reason (e.g., m_result).  Personally, I prefer to just use the this prefix for member variables if there's a name collision.  It's built in to the language and everyone already knows what it means.

Title: What are the benefits of prefixing function parameter names with p*?

Body:
I often see projects (in Java projects and teams using Eclipse) that prefix function parameters with p.

For example

```<code>public void filter (Result pResult) ...
</code>```

I personally don't see any benefit in this, but would like to know what the reasoning is. The best explanation I've heard yet is that it is to distinguish the name of identical named fields.I have my issues with that explanation but I can understand the point.


问:
If immutable objects are good, why do people keep creating mutable objects?
If immutable objects¹ are good, simple and offer benefits in concurrent programming why do programmers keep creating mutable objects²?

I have four years of experience in Java programming and as I see it, the first thing people do after creating a class is generate getters and setters in the IDE (thus making it mutable). Is there a lack of awareness or can we get away with using mutable objects in most scenarios?

¹ Immutable object is an object whose state cannot be modified after it is created.

² Mutable object is an object which can be modified after it is created.

答:
Mutable objects are used when you have to set multiples values after instantiating the object.

You shouldn't have a constructor with, say, six parameters. Instead you modify the object with setter methods.

An example of this is a Report object, with setters for font, orientation etc.

For short: mutables are useful when you have a lot of state to set to an object and it would not be practical to have a very long constructor signature.

EDIT: Builder pattern can be used build the whole state of the object.


问:
What is the best way to INSERT a large dataset into a MySQL database (or any database in general)
As part of a PHP project, I have to insert a row into a MySQL database. I'm obviously used to doing this, but this required inserting into 90 columns in one query. The resulting query looks horrible and monolithic (especially inserting my PHP variables as the values):

```<code>INSERT INTO mytable (column1, colum2, ..., column90)
VALUES
('value1', 'value2', ..., 'value90')
</code>```

and I'm concerned that I'm not going about this in the right way. It also took me a long (boring) time just to type everything in and testing writing the test code will be equally tedious I fear.

How do professionals go about quickly writing and testing these queries? Is there a way I can speed up the process?

答:
There is more efficient way to insert data into database using php and mysql. We can use LOAD COMMAND to insert the data. It inserts data remarkably fast.

For this create a flat file (for example I used .csv file) with your data using fputcsv() function. Then insert data using LOAD command. Syntax some what similar as below:

```<code>LOAD DATA LOCAL INFILE "C:/downloads/local/my_data_file.csv"
INTO TABLE  my_data
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;
</code>```

Body:
There is more efficient way to insert data into database using php and mysql. We can use LOAD COMMAND to insert the data. It inserts data remarkably fast.

For this create a flat file (for example I used .csv file) with your data using fputcsv() function. Then insert data using LOAD command. Syntax some what similar as below:

LOAD DATA LOCAL INFILE "C:/downloads/local/my_data_file.csv"
INTO TABLE  my_data
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;


答: I think that if yo already know how and why it could happen, might as well deal with it. That is if it doesn't take up an copious amount of resources.</p>


问:
B.A Computer Science Vs B.S Inf Tech?
Would a recruiter prefer a B.A in Comp Science from a more prestigious university or a B.S in Inf Tech from just an average university? Would it matter for someone already established in the field with plenty of experience?

The only difference in the B.A and B.S is essentially the mathematics.  The B.S is geared for those going on to master's programs, although one isn't excluded from going on to a masters program with a BA, many do require more mathematics.

Just for those curious, the information tech degree is typically geared more to real-world problems then the computer science and the quality of it will vary widely. Some inf tech programs are as in-depth as an ABET C.S degree, the information tech from Drexel looks extremely strong. The Management Information Systems is generally provided via the business school and is more of a traditional business degree.

I'm not sure really how well versed the recruiters/g.p are in the actual differences in all of these programs. Some non ABET BS Comp Science may only require 1 or 2 Calculus versus the ABET certified programs.

答:
When I look at an applicants education history on their resume I look at these things (in order of importance).  Keep in mind that all of these considerations essentially are out the window if the applicant has significant work experience, generally they only come into play for applicants coming out of college whose only work experience is one or two internships.  The place I work happens to do most of their recruiting through universities so the "education background" section of the resume isn't generally something I can just skip.

Is the degree relevant?

Degrees that require a lot of coding are most relevant, but beyond that I would never consider one coding-intensive degree more relevant than another.  Computer Science, Computer Engineering, Computer Information Systems, and whatever other coding-intensive degrees are out there are all equally relevant IMO.  Slightly less relevant, but still good degrees are anything technical, ie engineering, math, physics.  If their degree is something non-technical that's a different story.  I haven't seen many applicants without degrees just because my company does most of their recruiting through universities.

Was it a good school?

This measurement is even less precise, but there are three general categories.  Great, good, and not good.  If the school has an awesome reputation for engineering they get lumped in the great category (I'm in California so UC Berkeley, Cal-Tech, UCLA, Cal Poly SLO, etc are the "great" schools I've come in contact with).  And not to sound political, but generally for-profit schools get lumped into the "not good category" along with the associate degrees from community colleges, although being in the "not good" category definitely isn't a deal breaker.  Everyone else is in the good category.

What was their GPA?

The least important of the education considerations but still something to keep in mind.  I'd definitely rather see a great school than a great GPA.

Bachelors vs Master's degree doesn't mean a whole lot to me, although for bureaucratic reasons I'm supposed to favor the masters degree.  The Bachelors degree is plenty of education for our field in my opinion. The further education to get a masters degree just tells me the applicant is the academic type, which in my experience doesn't say much about how successful they will be as an employee.

If you can't tell by now, considering a BA vs BS isn't even on the radar screen, and for good reason.  Not only is the difference generally minor, the difference between the BA and BS is completely dependent on the college.  Some colleges call their Computer Science degrees BAs for some reason, and others choose to call it a BS. Even among the schools that offer both options, the difference between the BA and the BS isn't always the same.  It's simply not worth my time and effort to research every degree program from every university to just find out if the applicant was required to take vector calculus or not.

Title: B.A Computer Science Vs B.S Inf Tech?


答:
and some other thread is polling data over the network or something that is guaranteed to take 5-10 seconds to finish the job.

Until someone introduces a caching layer to improve performance. Suddenly that other tread finished near instantaneous and the race condition manifests more often than not.

Had exactly this happen a few weeks ago, took about 2 full developer days to find the bug.

Always fix race conditions if you recognize them.


答:
There are really two different definitions of caching.  The first is what the operating system does, moving blocks of storage that are slow to access into blocks that are much faster to access.  If you write your algorithm to take advantage of this kind of caching, your program will run faster, sometimes a lot faster, but the algorithmic complexity remains O(n3).

Sometimes when people say caching, they mean memoization.  This means you do the calculation the hard way the first time, but you store it in memory for the second and subsequent times you need it.  Effectively, the first time you run it for given data, your algorithm is O(n3), but after that it is O(1).

Title: Caching's Effect on Program Performance


问:
How to use the clients webcam for recording through a website?
I am building a site and idealy I would like to record the users interaction via their webcam. How do I intergrate webcam recording into my site. I have seen It done with flash. But Im trying to avoid using this. My site is being built using c#, javascript and designed for IE 7 and older.

I want to record the videos for later. They are not going to be used for chat e.t.c.

答:
This is possible using either HTML Media Capture or WEBRTC. Both of these are HTML5 though, so you won't support IE7 (or IE8, or IE9). The alternative is flash. There's a jQuery plugin that enables you to work with Javascript (but still uses flash underneath).

Also, do realize that recording videos of the users without their explicit consent is illegal in many countries.


问:
Using replacement to get possible outcomes to then search through HUGE amount of data
I have a database table holding 40 million records (table A).

Each record has a string a user can search for.

I also have a table with a list of character replacements (table B) i.e. i = Y, I = 1 etc.

I need to be able to take the string a user is searching for, iterate through each letter and create an array of every possible outcome (the users string, then each outcome with alternative letters used).

I need to check for alternatives on both lower and uppercase letters in the word

A search string can be no longer than 10 characters long.

I'm using PHP and a MySQL database.

Does anyone have any thoughts / articles / guidance on doing this in an efficient way?

答:
Here is what I see possible based on my understanding:

One way is to create a column (preferably on table A) and have a database trigger (or write code in your language) such that whenever a row is inserted or update, a new column (shown below as "SearchColumn") would get populated with ONLY ONE STANDARD FORMAT of the string value. In the example blow I have arbitrary chosen upper case.

The seach column need to have a non-unique index.

When the user performs a search for say,'yes', you do:

SELECT FROM myTable WHERE SearchColumn="YES" (see the last paragraph regarding the index cases sensitivity).

myTable would include the following columns (amongst others of course):

OriginalColumn, SearchColumn

YES, YES

Y3S, YES

Y55, YSS

yes, YES

NO,  NO

N0,  NO

...

By doing this, you don't need to perform non-indexed row searching. This method, since it uses an index will be very fast. The overhead of processing the extra column should not be significant, unless you have simultaneous thousands of concurrent inserts/updates.

In MySQL (and some other database), you can control whether an index uses case sensitivity or not via the column collating properties definition.


问:
Choosing between Single or multiple projects in a git repository?
In a git environment, where we have modularized most projects, we're facing the one project per repository or multiple projects per repository design issue. Let's consider a modularized project:

```<code>myProject/
   +-- gui
   +-- core
   +-- api
   +-- implA
   +-- implB
</code>```

Today we're having one project per repository. It gives freedom to

release individual components

tag individual components

But it's also cumbersome to branch components as often branching api requires equivalent branches in core, and perhaps other components.

Given we want to release individual components can we still get the similar flexibility by utilizing a multiple projects per repository design.

What experiences are there and how/why did you address these issues?

答:
As we use GitHub, we actually have multiple projects in one repo but ensure that those projects/modules are properly modularised (we use -api and -core conventions + Maven + static and runtime checking and might even go to OSGi one day to boot).

What does it save on?  Well we don't have to issue multiple Pull Requests if we're changing something small across multiple projects.  Issues and Wiki are kept centralised etc.

We still treat each module/project as a proper independent project and build and integrate them separately in our CI server etc.


答: If you have to explain what your degree does and how it is valid, perhaps it is a sign that you should steer away from it, purely for marketing reasons.

Title: B.A Computer Science Vs B.S Inf Tech?

Body:
Would a recruiter prefer a B.A in Comp Science from a more prestigious university or a B.S in Inf Tech from just an average university? Would it matter for someone already established in the field with plenty of experience?

The only difference in the B.A and B.S is essentially the mathematics.  The B.S is geared for those going on to master's programs, although one isn't excluded from going on to a masters program with a BA, many do require more mathematics.

Just for those curious, the information tech degree is typically geared more to real-world problems then the computer science and the quality of it will vary widely. Some inf tech programs are as in-depth as an ABET C.S degree, the information tech from Drexel looks extremely strong. The Management Information Systems is generally provided via the business school and is more of a traditional business degree.

I'm not sure really how well versed the recruiters/g.p are in the actual differences in all of these programs. Some non ABET BS Comp Science may only require 1 or 2 Calculus versus the ABET certified programs.


答:
I only use a parameter prefix when the parameter is intended to be assigned to a member variable, such as a constructor or a setter.

```<code>Paint (newColor) {
  color = newColor;
}
</code>```

For me, I find that using a different variable name is more blindingly obvious than using the "this" prefix.

For other situations, I avoid using a parameter that could be easily confused with a member variable.

If a method or class is so big that it is hard to tell what the variables mean, the real solution is to break it up into smaller methods/classes. Using prefixes is a band-aid solution that does address the underlying problem.

Body:
I only use a parameter prefix when the parameter is intended to be assigned to a member variable, such as a constructor or a setter.

Paint (newColor) {
  color = newColor;
}

For me, I find that using a different variable name is more blindingly obvious than using the "this" prefix.

For other situations, I avoid using a parameter that could be easily confused with a member variable.

If a method or class is so big that it is hard to tell what the variables mean, the real solution is to break it up into smaller methods/classes. Using prefixes is a band-aid solution that does address the underlying problem.


问:
Should I take care of race conditions which almost certainly has no chance of occuring?
Let's consider something like a GUI application where main thread is updating the UI almost instantaneously, and some other thread is polling data over the network or something that is guaranteed to take 5-10 seconds to finish the job.

I've received many different answers for this, but some people say that if it is a race condition of a statistical impossibility, don't worry about it at all but others have said that if there's even a 10-53% (I kid you not on the numbers, this is what I've heard) of some voodoo magic happening due to race condition, always obtain/release locks on the thread that needs it.

What are your thoughts? Is it a good programming practice to handle race condition in such statistically-impossible situations? or would it be totally unnecessary or even counterproductive to add more lines of code to hinder readability?

答:
would it be totally unnecessary or even counterproductive to add more lines of code to hinder readability?

Simplicity is only good when it's also correct.  Since this code is not correct, future programmers will inevitably look at it when looking for a related bug.

Whichever way you handle it (either by logging it, documenting it, or adding the locks -- this depends on the cost), you will save other programmers time when looking at the code.


问:
Is it bad practice to use public fields?

Possible Duplicate:

  When are Getters and Setters Justified

  Why are public and private accessors considered good practice?

In my time as developer I learned that properties can be very useful. I use properties to control read and write access or to add something like validation checks.

But assuming that I have an auto property with a public getter and setter.

```<code>public string LastName { get; set; }
</code>```

In that case I don't see any point in using properties over fields.

I could also do following:

```<code>public string LastName;
</code>```

Is there anything that speaks against a public field in this case?
Why should I use a property?

答: The setters and getters can be modified without making breaking API changes. This is the primary reason for using properties over fields. If you know without a doubt that you will not need to modify the getter/setter, then you might be ok, but why risk it? After all, it is not like it is that big of an inconvenience to make it a property.</p>


问:
Registration: Email hash and verifying only one account per email
I'm using a registration function that hashes the email in PBKDF2 with a random and unique Salt each time. The hashes email and his salt are saved in the DB. No problem with that.
The problem is that now I want to make sure that users only create one single account per email. Obviously to verify that I need to check my DB and that's where the problem starts. I either lose in security or in time.

Because as I see it I have 2 choices:

1 - I change my hash method and use a common Salt for all emails. Which make me lose a bit of security.

Or

2 - I hash the email with all the Salts from the DB and check for matches. My guess is that this will be horribly slow.

So my question are:

What should I do? Optimize security or "time"?

Maybe hashing emails with unique and random salts in PBKDF2 is too much? If yes, what hashing method should I use?

Is there any other solution?

PS: I didn't post any code because I think this is more of a theory discussion but if code is needed let me know, I will add it.

答:
Store a clear-text 'digest' of each email address alongside the hashed actual email. The digest should contain enough information to bring the number of candidates down to a reasonable handful (I'd say a factor of 1000 or more isn't unrealistic), but not enough to guess the entire email address. For example, you could use the first two characters from the user part of the address, two characters from the domain name, and the TLD part; this would turn 'john.doe@example.org' into 'jo@ex.org'.

Finding collisions now becomes a two-step process: first, find all entries with matching digests, then do the actual hash comparison only on those. Instead of downloading all hashes from the DB for each check, you pre-filter them down to about 1/1000. That is a significant improvement, and while you trade some security for it, it's better than either alternative.


答:
In general, yes, using public fields instead of properties is a bad practice.

The .NET framework by and large assumes that you will use properties instead of public fields. For example, databinding looks up properties by name:

```<code>tbLastName.DataBindings.Add("Text", person, "LastName"); // textbox binding
</code>```

Here are some things you can easily do with properties but not with fields:

You can add validation (or any other code, within reason) to values in a property:

```<code>private string lastName;
public string LastName
{
    get { return lastName; }
    set
    {
        if(string.IsNullOrEmpty(value))
            throw new ArgumentException("LastName cannot be null or empty");
        lastName = value;
    }
}
</code>```

You can easily change accessibility levels for getters and setters:

```<code>public string LastName { get; private set; }
</code>```

You can use them as part of an interface definition or an abstract class.

If you start out with public fields and assume it'll be easy to change to properties later, you will likely run into trouble. If you have any code in other assemblies that depends on accessing your public fields, you will have to rebuild and redeploy all of them if you switch to property-based access. You might also have code that uses reflection to get at the values... that'd also need to be changed.

And if you're really unlucky, those changes would have to be made in a part of the codebase you have no control over and you'll be stuck hacking around public fields.

For more gory details, check out item 1 in the first chapter of Effective C# by Bill Wagner.

Title: Is it bad practice to use public fields?

Body:
Possible Duplicate:

  When are Getters and Setters Justified

  Why are public and private accessors considered good practice?

In my time as developer I learned that properties can be very useful. I use properties to control read and write access or to add something like validation checks.

But assuming that I have an auto property with a public getter and setter.

```<code>public string LastName { get; set; }
</code>```

In that case I don't see any point in using properties over fields.

I could also do following:

```<code>public string LastName;
</code>```

Is there anything that speaks against a public field in this case?
Why should I use a property?

Body:
In general, yes, using public fields instead of properties is a bad practice.

The .NET framework by and large assumes that you will use properties instead of public fields. For example, databinding looks up properties by name:

tbLastName.DataBindings.Add("Text", person, "LastName"); // textbox binding

Here are some things you can easily do with properties but not with fields:

You can add validation (or any other code, within reason) to values in a property:

private string lastName;
public string LastName
{
    get { return lastName; }
    set
    {
        if(string.IsNullOrEmpty(value))
            throw new ArgumentException("LastName cannot be null or empty");
        lastName = value;
    }
}

You can easily change accessibility levels for getters and setters:

public string LastName { get; private set; }

You can use them as part of an interface definition or an abstract class.

If you start out with public fields and assume it'll be easy to change to properties later, you will likely run into trouble. If you have any code in other assemblies that depends on accessing your public fields, you will have to rebuild and redeploy all of them if you switch to property-based access. You might also have code that uses reflection to get at the values... that'd also need to be changed.

And if you're really unlucky, those changes would have to be made in a part of the codebase you have no control over and you'll be stuck hacking around public fields.

For more gory details, check out item 1 in the first chapter of Effective C# by Bill Wagner.


问:
Have you ever found yourself using a specific tool in favor of another just because it looks better?
I found that this was the case with Eclipse.
When I first started learning Java a lot of people told me to start with NetBeans because it's easier, comes with a lot of predefined functionality and most of the configuration is done by default. Indeed it seemed like an easy IDE but I just hated the way it looked. The UI to me was horrible.

Then I downloaded Eclipse. I was pretty impressed with it. Everything looked shiny, fonts looked awesome and the UI in general was amazing compared to NetBeans'. So I stayed with Eclipse.

Has something like this ever happen to you? Should the UI be of such a relevance to a programmer, is this bad ? The problem of the UI extends to everything for me, not only IDE's (e.g. even on linux I have to customize the WM the way I want before starting working with it).

答: I use stackexchange sites and not other forums, just because they read&feel better.</p>


答: It's bad because you're exposing the internal state of your object, and you don't have any control over how that state is changed.  With getters and setters, you can at least inspect the data and modify it if necessary, so your object's internal state remains consistent (and valid).</p>


答: I'm a fan of iParam for in, and oParam for out parameters.  I'd say cParam for change, but that's not acceptable</p>


答:
It all depends on what the consequences of a race condition is. I think the people answering your question are correct for their line of work. Mine is router configuration engines. For me, race conditions either makes systems stand still, corrupt or unconfigured even though it said it was successful. I always use semaphores per router so that I don't have to clean anything up by hand.

I think some of my GUI code still is prone for race conditions in such way that a user might be given an error because a race condition happened, but I would not have any such possibilities if there is a chance of data corruption or misbehaviour of the application after such event.


答:
practical reason:

1) You do not have "send mail" functioning.

2) You cannot put device
    upside-down..

and of course already said reason:

3) low bandwidth

4) very small computational power compared to simulator

5) Open GL calls are implemented a bit different in simulator

6) disk space / RAM..


答:
Yes, expect the unexpected.  I have spent hours (in other peoples code ^^) tracking down conditions that should never happen.

Things such as always have an else, always have a default on case, initialize variables (yes, really.. bugs happen from this), check your loops for reused variables for each iteration, etc.

If you are worried about threading issues specifically, read blogs, articles, and books on the subject.  The current theme seems to be immutable data.


问:
Is it better to target iOS 5 and ARC or an earlier version with MRC?
I personally don't know much about iOS 5, but it seems like with automatic reference counting (ARC), you get rid of much of the memory management issues of the previous operating systems.

So is it better to target iOS5 (and create apps that can only run on the newest iOS devices), or is it better for her to target iOS 4 or even iOS 3, so she understands the fundamentals of memory management in Objective-C? Are there any important aspects of iOS development that she might miss out on by jumping into iOS 5?

答:
1) as a serious programmer, you cannot miss full comprehension of MRC.

2) in certain situation (CF...) You must know it.

3) ARC is very fine and useful. (I came from malloc / free BUT appreciate it..)

4) Apple directions from last wwdc2012 (I were there..) was USE ARC! Period! Indeed all new code is written for ARC.


答:
Absolutely. I prefer uncluttered UIs with a very low graphical complexity level.

My UX is very important to me - the app needs to not get in my way. The iPod is a wonderful device for this, in my experience

FWIW, I find Eclipse-derived applications a complete pain to use. I use emacs for all editing.

Title: Have you ever found yourself using a specific tool in favor of another just because it looks better?

Body:
I found that this was the case with Eclipse.
When I first started learning Java a lot of people told me to start with NetBeans because it's easier, comes with a lot of predefined functionality and most of the configuration is done by default. Indeed it seemed like an easy IDE but I just hated the way it looked. The UI to me was horrible.

Then I downloaded Eclipse. I was pretty impressed with it. Everything looked shiny, fonts looked awesome and the UI in general was amazing compared to NetBeans'. So I stayed with Eclipse.

Has something like this ever happen to you? Should the UI be of such a relevance to a programmer, is this bad ? The problem of the UI extends to everything for me, not only IDE's (e.g. even on linux I have to customize the WM the way I want before starting working with it).


问:
In what language should I name my business classes?
I'm requesting best practice with this question. This is only an issue if the customer company is strictly national has a native language other than English, I think.

If the customer has a lot of mainly very domain specific (say, German) expressions, mixed with some lesser domain specific namings. The language of our code comments, class/method/variable names is English. Would you translate all domain specific names?

答:
I believe that since English is the lingua franca of the IT domain, limiting your source code to another language creates artificial obstacles to it's development. First you limit the pool of the people that can contribute to ones that speak a specific language. The same reason that you asked in stack exchange and not on a local site.

Also you do not know where contributions will come from and where will go to. What if you use a sample from a site, will you translate that? What if the product expands to be used from clients in another country? Case you need to hire a contractor/ outsource a bit? Why limit to one pool and not get the most fit from all over the world?

Can assume that it is OK for some domain specific structures that do not map easily to other languages, or if an existing code base is maintained.


问:
How do you keep the size of your application down (memory usage and physical storage size)?
I have a personal project that I'm working on although it's quite audio and graphic-intense and I was wondering if you guys had any suggestions or solutions as to how one could keep the size and memory-usage of their application to a minimum? My application is an iPhone application and, as Apple always make clear, the application is only allowed to use a certain amount of memory (in terms of performance and actual size).</p>

答:
I do not agree about using compression, i.e. JPG.
Preferred format is PNG, and if You use JPG anyway it will be expanded in memory.

So for example reduce size of PNG and draw with small tiles, draw in rects instead all view and do so on.

Use Instruments to see where and how You have big allocations and try to reduce them.

Make all loading "lazy" so you can free resources when done and reload on demand.

As You make a lot of graphics, is fine drawing directly objects, instead of loading images and drawing. (even if apple says is better to load image for performance reason... the trade-off is between processor usage and memory..)


问:
iPad app architecture with very large files
I am working on an iPad app.  It needs to contain some very large files.  I could put them into the app, but they would push it well over 20MB, which means that it would not be downloadable over the air -- only via iTunes.

Is there a way around this without too much pain for me?  I don't have a server or anything like that.

答:
definitively the BETTER solution is to download the first time

advantages:

1) Binary .IPA is smaller, so You can upload quickly first time AND in case of updates

2) if user download upgrades, data are already present

3) You can fix data without posting an update

4) Data updates are a nice feature You customers will like, NOT users, the customer who pay you to develop an app.


答:
Being Norwegian working in a Norwegian company I name my objects in English. Of course some words or concepts might not have a English counterpart and in that case one can argue that a native word might be used in place of a bad replacement or literal translation which has not meaning. Of course, much of these problems might be the fact that some of us should have a better vocabulary so I usually ask a colleague if I can't think of a good English name :)

Some of our staff are not Norwegian and thus writing in English benefits them. Being able to hire programmers from most of Europe is good for the economy so my company benefits from it too.

BTW: I remember I read the source of Hermes once (ebXML b2b implementation) and I would have had a hard time if they would have written and commented in Mandarin.

Title: In what language should I name my business classes?

Body:
I'm requesting best practice with this question. This is only an issue if the customer company is strictly national has a native language other than English, I think.

If the customer has a lot of mainly very domain specific (say, German) expressions, mixed with some lesser domain specific namings. The language of our code comments, class/method/variable names is English. Would you translate all domain specific names?


答:
There are three major disadvantages to "one project per repository", the way you've described it above. These are less true if they are truly distinct projects, but from the sounds of it changes to one often require changes to another, which can really exacerbate these problems:

It's harder to discover when bugs were introduced. Tools like git bisect become much more difficult to use when you fracture your repository into sub-repositories. It's possible, it's just not as easy, meaning bug-hunting in times of crisis is that much harder.

Tracking the entire history of a feature is much more difficult. History traversing commands like git log just don't output history as meaningfully with fractured repository structures. You can get some useful output with submodules or subtrees, or through other scriptable methods, but it's just not the same as typing tig --grep=<caseID> or git log --grep=<caseID> and scanning all the commits you care about. Your history becomes harder to understand, which makes it less useful when you really need it.

New developers spend more time learning the Version Control's structure before they can start coding. Every new job requires picking up procedures, but fracturing a project repository means they have to pick up the VC structure in addition the code's architecture. In my experience, this is particularly difficult for developers new to git who come from more traditional, centralized shops that use a single repository.

In the end, it's an opportunity cost calculation. At one former employer, we had our primary application divided into 35 different sub-repositories. On top of them we used a complicated set of scripts to search history, make sure state (i.e. production vs. development branches) was the same across them, and deploy them individually or en masse.

It was just too much; too much for us at least. The management overhead made our features less nimble, made deployments much harder, made teaching new devs take too much time, and by the end of it, we could barely recall why we fractured the repository in the first place. One beautiful spring day, I spent $10 for an afternoon of cluster compute time in EC2. I wove the repos back together with a couple dozen git filter-branch calls. We never looked back.

Title: Choosing between Single or multiple projects in a git repository?

Body:
In a git environment, where we have modularized most projects, we're facing the one project per repository or multiple projects per repository design issue. Let's consider a modularized project:

```<code>myProject/
   +-- gui
   +-- core
   +-- api
   +-- implA
   +-- implB
</code>```

Today we're having one project per repository. It gives freedom to

release individual components

tag individual components

But it's also cumbersome to branch components as often branching api requires equivalent branches in core, and perhaps other components.

Given we want to release individual components can we still get the similar flexibility by utilizing a multiple projects per repository design.

What experiences are there and how/why did you address these issues?


答:
Just fix it.

I've seen exactly this. One thread manages to make a network request to a server which does a complex database lookup and respond before the other thread has got to the next line of code. It happens.

Some customer somewhere will decide one day to run something that hogs all the CPU time for the "fast" thread while leaving the slow thread running, and you'll be sorry :)

Body:
Let's consider something like a GUI application where main thread is updating the UI almost instantaneously, and some other thread is polling data over the network or something that is guaranteed to take 5-10 seconds to finish the job.

I've received many different answers for this, but some people say that if it is a race condition of a statistical impossibility, don't worry about it at all but others have said that if there's even a 10-53% (I kid you not on the numbers, this is what I've heard) of some voodoo magic happening due to race condition, always obtain/release locks on the thread that needs it.

What are your thoughts? Is it a good programming practice to handle race condition in such statistically-impossible situations? or would it be totally unnecessary or even counterproductive to add more lines of code to hinder readability?


问:
What is the simplest/easiest way to display line of text only when printing a webpage using PHP?
I have a line of text I would like to display only when a webpage is being printed.  Is it possible to only display this line when printing the page or doing a print preview using PHP in some way?

Basically, I want to print a page without the print headers, but would like to include the page's URL within the page's content when it is printed.

答:
You can create a CSS stylesheet that only applies to Print media.

For example:

```<code>                                             Notice the media----v
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
</code>```

In your regular CSS stylesheet, just hide that element:

```<code>p.print-notice {
    visibility: hidden;
}
</code>```

And in your print CSS stylesheet, bring it up again:

```<code>p.print-notice {
    visibility: visible;
}
</code>```

Note: Setting visibility to hidden, only hides the element but does not remove it from the document flow. Use the Display property if you want to remove it from flow.

Body:
You can create a CSS stylesheet that only applies to Print media.

For example:

                                             Notice the media----v
<link rel="stylesheet" href="print.css" type="text/css" media="print" />

In your regular CSS stylesheet, just hide that element:

p.print-notice {
    visibility: hidden;
}

And in your print CSS stylesheet, bring it up again:

p.print-notice {
    visibility: visible;
}

Note: Setting visibility to hidden, only hides the element but does not remove it from the document flow. Use the Display property if you want to remove it from flow.


问:
What is abstraction?
Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?

答:
I categorically disagree with most of the answers.

This is my answer:

Given two sets G and H, a Galois connection (alpha, beta) can be defined between them, and one can be said to be a concretization of the other; reverse the connection, and one is an abstraction of the other. The functions are a concretization function and an abstraction function.

This is from the theory of abstract interpretation of computer programs, which typically is a static analysis approach to date.

Title: What is abstraction?


答: You might have more luck doing this with CSS and just showing or hiding the element(s) when printing using "@media print". A little more information is here: http://webdesign.about.com/cs/css/qt/tipcssatmedia.htm but you can probably find more by doing some searches for CSS media types.</p>

Title: What is the simplest/easiest way to display line of text only when printing a webpage using PHP?

Body:
I have a line of text I would like to display only when a webpage is being printed.  Is it possible to only display this line when printing the page or doing a print preview using PHP in some way?

Basically, I want to print a page without the print headers, but would like to include the page's URL within the page's content when it is printed.


问:
Work flow when editing files in /var/www. Constantly needing to input "sudo" commands
I installed Apache2 and PHP5 last night on my fresh Linux Mint machine.

I created a folder and created a simple index.php file with a call to phpinfo() to test out the installation and every works correctly.

However when I open the file with Sublime Text 2 or any other editor, I cannot save my changes. I can use the sudo nano command to open it with super user privileges and I can save just fine.

The same goes with Mercurial. I cannot hg commit because of permissions. I can only sudo hg commit.

Is this how the basic workflow is supposed to be? If I run the chmod command and recursively give 777 permissions to the folders and files within Apache can run it just fine, but if it's a dynamically created file (created by my web app) then it seems Apache cannot access or run it. I have to run the chmod command again!

Any suggestions on what I should do? I feel like 30% of my time is spent on redundant processes that shouldn't be done at all.

答:
You should store your code in source control (mercurial for example). Edit it on a local copy and push to your remote repository, then pull the changes to the server as needed.

Make a user/group for the web process to run under, and set the permissions & ownership for that user/group. Any new files will be owned by the process's user, so when configured correctly it should work just fine.


问:
If immutable objects are good, why do people keep creating mutable objects?
If immutable objects¹ are good, simple and offer benefits in concurrent programming why do programmers keep creating mutable objects²?

I have four years of experience in Java programming and as I see it, the first thing people do after creating a class is generate getters and setters in the IDE (thus making it mutable). Is there a lack of awareness or can we get away with using mutable objects in most scenarios?

¹ Immutable object is an object whose state cannot be modified after it is created.

² Mutable object is an object which can be modified after it is created.

答:
I think using mutable objects stems from imperative thinking: you compute a result by changing the content of mutable variables step by step (computation by side effect).

If you think functionally, you want to have immutable state and represent subsequent states of a system by applying functions and creating new values from old ones.

The functional approach can be cleaner and more robust, but it can be very inefficient because of copying, so that you want to fall back to a shared data structure that you modify incrementally.

The trade-off that I find most reasonable is: Start with immutable objects and then switch to mutable ones if your implementation is not fast enough. From this point of view, using mutable objects systematically from the beginning can be considered some kind of premature optimization: you choose the more efficient (but also more difficult to understand and to debug) implementation from the beginning.

So, why do many programmers use mutable objects? IMHO for two reasons:

Many programers have learnt how to program using an imperative (procedural or object-oriented) paradigm, therefore mutability is their basic approach to defining computation, i.e. they do not know when and how to use immutability because they are not familiar with it.

Many programmers worry about performance too early whereas it is often more effective to first focus on writing a program that is functionally correct, and then try to find bottlenecks and optimize it.


答:
Open-source / international community type projects

The common language of open-source and international community projects is English.  Case in point, the language of the Stack Exchange sites is English.  For broadest accessibility, English should be used for all code and object names.

Commercial Projects

Most international software firms mandate code to be written in English.  It's the greatest common denominator, so it makes sense to use English as a means to create consistency.

Many regional software firms write in their native language.  Not all follow this approach, but it makes sense from their point of view - they use the common language for all of their developers.

Naming business objects

The coding language of the team should be used to name objects.

The priority is for the developers to be able to communicate with each other regarding the objects and the project requirements.  If the team writes in French, then the business objects should be named in French.  If they code in English, then name the objects in English.

Your question adds a wrinkle because the client speaks a native language other than your team's coding language.  You should still use your team's coding language to name the objects.

When the business analysts or developers need to communicate with the client about the specific business objects, an as-needed translation of the object name from the coding-language to the client language may be required.  From my experience, it's pretty rare that I've talked about specific code objects with the client so the translation back to the client language hasn't really been needed.

The only exception to the naming rule is when an object has no other sufficiently concise term to capture the intent of the object.  IMO, this is really rare, but it can occur.  In reality though, it's the same thing spoken languages do to express particular concepts.  "Facade" is originally a French term but has been adapted by English in order to express the concept, and is a common design pattern.  "Schadenfreude" is another good example of a borrowed term although I don't think it has a corresponding pattern.


答:
You've indidcated this is your dev environment, so beyond Daenyth's suggestion of using source control (which you should definitely do) I'd suggest doing a little indirection.

In other words, simply use a symbolic link from /var/www to a working directory that you have permission to work in.  Then you can mess around in your working directory as needed and apache will happily serve it up.

Title: Work flow when editing files in /var/www. Constantly needing to input "sudo" commands

Body:
I installed Apache2 and PHP5 last night on my fresh Linux Mint machine.

I created a folder and created a simple index.php file with a call to phpinfo() to test out the installation and every works correctly.

However when I open the file with Sublime Text 2 or any other editor, I cannot save my changes. I can use the sudo nano command to open it with super user privileges and I can save just fine.

The same goes with Mercurial. I cannot hg commit because of permissions. I can only sudo hg commit.

Is this how the basic workflow is supposed to be? If I run the chmod command and recursively give 777 permissions to the folders and files within Apache can run it just fine, but if it's a dynamically created file (created by my web app) then it seems Apache cannot access or run it. I have to run the chmod command again!

Any suggestions on what I should do? I feel like 30% of my time is spent on redundant processes that shouldn't be done at all.


答: Why do people use any powerful feature? Why do people use meta-programming, laziness or dynamic typing? The answer is convenience. Mutable state is so easy. It's so easy to update in place and the threshold of project size where immutable state is more productive to work with than mutable state is quite high so the choice won't bite you back for a while. </p>

Title: If immutable objects are good, why do people keep creating mutable objects?

Body:
If immutable objects¹ are good, simple and offer benefits in concurrent programming why do programmers keep creating mutable objects²?

I have four years of experience in Java programming and as I see it, the first thing people do after creating a class is generate getters and setters in the IDE (thus making it mutable). Is there a lack of awareness or can we get away with using mutable objects in most scenarios?

¹ Immutable object is an object whose state cannot be modified after it is created.

² Mutable object is an object which can be modified after it is created.


问:
Caching's Effect on Program Performance
How does caching effect the performance of a running program? From my understanding, the assumption that each instruction always takes the same amount of time is not always correct, because of the effects of caching. How does caching affect algorithmic performance? Thanks in advance.

EDIT 1:
To further elaborate, lets say I'm running this Java program that's reading one million integers. From what I understand about this program, it's order of growth is cubic and will take a while to finish running. How would caching improve the performance of this program while it is running?

答:
Modern processors have lots of caching features that are intended to improve the performance of "normal" programs like this.  If you want to study the effect of this caching, you could set about creating an abnormal program that computes the same result.

For example, instead of ramping through the indexes of the arrays serially, go through them in pseudo-random order. (it will take a little thought to do this without a lot of overhead,
but the simple way is to allocate a permutation table the same size as the array).

Another example which can provide an "aha" moment is to unroll the inner loop.  At some size, unrolling the loop will start to produce worse results.

Title: Caching's Effect on Program Performance


问:
What are the benefits of prefixing function parameter names with p*?
I often see projects (in Java projects and teams using Eclipse) that prefix function parameters with p.

For example

```<code>public void filter (Result pResult) ...
</code>```

I personally don't see any benefit in this, but would like to know what the reasoning is. The best explanation I've heard yet is that it is to distinguish the name of identical named fields.I have my issues with that explanation but I can understand the point.

答:
If you make a standard to use 'p' as a prefix with each method parameter name, you can easily recognize the method parameters in rest of the method body.

It saves your time to find the method parameters. You can debug your code easily.


问:
How to generate random numbers without making new Random objects?
I'm using this as part of a game, but it's not really a game development question, so I'm putting it on this more general Stack Exchange.

The goal is to generate "random" outputs for a fixed integer input, but (and this is the clincher) to generate the same random output every time the same random input is put in.

The idea here is that the function will generate the world the same way every time, so we don't need to store anything; the function itself is the storage.  Unfortunately access speed is a little slow, because the only way I can find to generate random numbers is to create a new Random() object with a seed based on the input, which is surprisingly slow.

Is there a better way?  I'm not worried about crypto-safe generation; in fact I'm just going to pick a random seed in advance and expose it quite publicly.

The current code looks like this:

```<code>private const int seed;

public MapCell GetMapCell(int x, int y)
{
    Random ran = new Random(seed + (x ^ y));
    return new MapCell(ran.NextInt(0, 4));
}
</code>```

Where the MapCell is one of four types (in fact it's more complicated than this, but not a whole lot).  The point is that this could be called for any parameters, at any time, in no particular order, but it needs to return the same answer every time, if x and y are the same every time.  That's why I can't fix a certain Random object and use it repeatedly.

I also don't want to store anything, because I want to keep the RAM usage quite low, but allow the player to wander freely to the edges of Int.MaxValue

答:
In The Art of Computer programming, volume 2 there is a section dedicated to random numbers.  You might be able to find what you are looking for in there.

Project Euler uses the following psuedo random number generator in a few of its problems (252 and 375 are the ones I spotted first):

```<code>  S(0)   = 290797
  S(n+1) = (S(n))^2 mod 50515093
</code>```

Obviously, this doesn't give you a walk up to maxint, but it gives an approach to your own that only requires you save the last result.  If you are working with longs instead of ints, it would let work (for what its worth, 2^32-5 = 0xFFFFFFFB = 4,294,967,291 is the largest 32 bit prime).

In the talk rand() Considered Harmful the presenter goes over a number of different options for doing random numbers.  While that talks of C++, it does give information that can be used to find a the right method in other languages.

In particular, for well known uniform random number distributions the thing you want to find is mt19937 which stands for the Mersenne twister with very particular parameters - its based on 219937 - 1. (~11m into the talk).

The key with the Mersenne twister is that it is very high quality pseudo-random numbers.  If you poke around a bit, you can find implementations of it in a number of languages.  The original C source

Specfically, for C# you can use Jon Skeet's StaticRandom to get random numbers in a thread safe way - no instantiation of new objects needed (code).  A modification of the code should allow you to pass in a seed.

Body:
In The Art of Computer programming, volume 2 there is a section dedicated to random numbers.  You might be able to find what you are looking for in there.

Project Euler uses the following psuedo random number generator in a few of its problems (252 and 375 are the ones I spotted first):

  S(0)   = 290797
  S(n+1) = (S(n))^2 mod 50515093

Obviously, this doesn't give you a walk up to maxint, but it gives an approach to your own that only requires you save the last result.  If you are working with longs instead of ints, it would let work (for what its worth, 2^32-5 = 0xFFFFFFFB = 4,294,967,291 is the largest 32 bit prime).

In the talk rand() Considered Harmful the presenter goes over a number of different options for doing random numbers.  While that talks of C++, it does give information that can be used to find a the right method in other languages.

In particular, for well known uniform random number distributions the thing you want to find is mt19937 which stands for the Mersenne twister with very particular parameters - its based on 219937 - 1. (~11m into the talk).

The key with the Mersenne twister is that it is very high quality pseudo-random numbers.  If you poke around a bit, you can find implementations of it in a number of languages.  The original C source

Specfically, for C# you can use Jon Skeet's StaticRandom to get random numbers in a thread safe way - no instantiation of new objects needed (code).  A modification of the code should allow you to pass in a seed.


答:
Why not just combine the two numbers and hash them? something like

```<code>private const int seed;

public MapCell GetMapCell(int x, int y)
{
    int combined = seed + (x ^ y);
    return new MapCell(combined.GetHashCode() %5);
}
</code>```

You want to simply map each X,Y coordinate to a MapCell.

Title: How to generate random numbers without making new Random objects?

Body:
I'm using this as part of a game, but it's not really a game development question, so I'm putting it on this more general Stack Exchange.

The goal is to generate "random" outputs for a fixed integer input, but (and this is the clincher) to generate the same random output every time the same random input is put in.

The idea here is that the function will generate the world the same way every time, so we don't need to store anything; the function itself is the storage.  Unfortunately access speed is a little slow, because the only way I can find to generate random numbers is to create a new Random() object with a seed based on the input, which is surprisingly slow.

Is there a better way?  I'm not worried about crypto-safe generation; in fact I'm just going to pick a random seed in advance and expose it quite publicly.

The current code looks like this:

```<code>private const int seed;

public MapCell GetMapCell(int x, int y)
{
    Random ran = new Random(seed + (x ^ y));
    return new MapCell(ran.NextInt(0, 4));
}
</code>```

Where the MapCell is one of four types (in fact it's more complicated than this, but not a whole lot).  The point is that this could be called for any parameters, at any time, in no particular order, but it needs to return the same answer every time, if x and y are the same every time.  That's why I can't fix a certain Random object and use it repeatedly.

I also don't want to store anything, because I want to keep the RAM usage quite low, but allow the player to wander freely to the edges of Int.MaxValue

Body:
Why not just combine the two numbers and hash them? something like

private const int seed;

public MapCell GetMapCell(int x, int y)
{
    int combined = seed + (x ^ y);
    return new MapCell(combined.GetHashCode() %5);
}

You want to simply map each X,Y coordinate to a MapCell.


问:
What's the difference between the insert methods and why one is faster
I have insert 14.485 lines on MySQL like this:

```<code>INSERT INTO `bairros` (`id`,`cidade_id`,`descricao`) VALUES (1,8891,'VILA PELICIARI');
INSERT INTO `bairros` (`id`,`cidade_id`,`descricao`) VALUES (2,8891,'VILA MARIANA');
...
</code>```

It took around 5 minutes.

I had to insert in another table 16.021 lines, same database, so for test I did this:

```<code>INSERT INTO `bairros` (`id`,`cidade_id`,`descricao`) VALUES (1,8891,'VILA PELICIARI'),(2,8891,'VILA MARIANA');
...
</code>```

It took just a few seconds.

What is the difference, for the database, between the scripts? And why one is faster than the other?

答: The first one is many queries, the second is just one query. The DBMS can do a lot more optimizations when it has all the data to work with. Namely, it can do some sort of a bulk update which is much faster than adding individual rows to your tables. You also avoid the overhead of executing the query every single time (optimizing, logging, etc).</p>