答:
```<code>  > Is it appropriate to store these bitmaps as resources,
  > and then check the results are equal?
</code>```

In my opinion i would say yes, but instead of coding these comparisons yourself i would use  approvaltests for dotnet or java for this.

So instead of hiding the bitmap-comparison behind a junit-testmethod the approval test shows every test-result where the bitmaps are not equal any more to the tester, who can decide this result is ok or is not ok. if it is ok the expected result is overwritten.

so on the next run the approvaltest will not complain any more.

Body:
  > Is it appropriate to store these bitmaps as resources,
  > and then check the results are equal?

In my opinion i would say yes, but instead of coding these comparisons yourself i would use  approvaltests for dotnet or java for this.

So instead of hiding the bitmap-comparison behind a junit-testmethod the approval test shows every test-result where the bitmaps are not equal any more to the tester, who can decide this result is ok or is not ok. if it is ok the expected result is overwritten.

so on the next run the approvaltest will not complain any more.


问:
Use of malloc in C
Is it necessary to call free function every time we use malloc in C.
I am asking this because I have seen many times that it is not called .

Thank you

答:
As pointed out in this question, for the particular case of freeing memory immediately before terminating the program, free is a waste of time if your program runs on pretty much any modern operating system. You'll be making the allocator do the work of tracking down the memory and marking it as unused, despite the fact that the OS can free the memory in one fell swoop. As Raymond Chen points out, if the amount of memory to be freed at program exit is large, the time wasted can be significant.

However, this behavior is still OS-dependent. With respect to the language, it is always wrong to not free memory. More importantly, tools like lint or Valgrind will report this as an error, and if you get used to ignoring their errors you defeat the purpose of using them. So I'd treat the practice of not freeing at program exit as an optimization, and you shouldn't optimize prematurely.

If we're not talking about program exit, failing to free is most definitely a bug. No one would intentionally do that if their goal is to write a program that doesn't leak memory.

ContentLicense: CC BY-SA 3.0

Title: Use of malloc in C

ContentLicense: CC BY-SA 4.0


问:
Is Python Interpreted or Compiled?
This is just a wondering I had while reading about interpreted and compiled languages.

Ruby is no doubt an interpreted language since the source code is processed by an interpreter at the point of execution.

On the contrary C is a compiled language, as one have to compile the source code first according to the machine and then execute. This results is much faster execution.

Now coming to Python:

A python code (somefile.py) when imported creates a file (somefile.pyc) in the same directory. Let us say the import is done in a python shell or django module. After the import I change the code a bit and execute the imported functions again to find that it is still running the old code. This suggests that *.pyc files are compiled python files similar to executable created after compilation of a C file, though I can't execute *.pyc file directly.

When the python file (somefile.py) is executed directly ( ./somefile.py or python somefile.py ) no .pyc file is created and the code is executed as is indicating interpreted behavior.

These suggest that a python code is compiled every time it is imported in a new process to create a .pyc while it is interpreted when directly executed.

So which type of language should I consider it as? Interpreted or Compiled?
And how does its efficiency compare to interpreted and compiled languages?

According to wiki's Interpreted Languages page, it is listed as a language compiled to Virtual Machine Code, what is meant by that?

答:
Virtual Machine Code is a more compact version of the original source code (byte code). It still needs to be interpreted by a virtual machine, since it is no machine code. It's easier and faster to parse than the original code written by a human being, though.

Some virtual machines generate machine code while interpreting the virtual machine code for the first time (just in time compilation - JIT). The following invocations will use this machine code directly, which leads to faster execution.

As far as i know Ruby >= 1.9 uses a virtual machine like Python too.

Title: Is Python Interpreted or Compiled?

ContentLicense: CC BY-SA 2.5


问:
Why is Web SQL database deprecated?
I am making a hybrid Android app.

At first I decided to use localStorage, after spending 2 days, I realized that it is very strange and so dropped it.

Then, I picked up indexedDB, after spending today's whole day and actually getting the output in Google Chrome, it is not running inside a WebView of the android app.

And I never used Web SQL database at all because it was deprecated. Anyhow, it has come to my notice that PhoneGap still uses Web SQL and android's browsers support it.

Why was Web SQL deprecated in the first place? And will it be a good idea for me to go with Web SQL now?

答:
The reality is that the contributing parties reached an impasse on the direction of the standard. In short, no one could agree.

The W3C site explains this.

The specification reached an impasse: all interested implementors have
  used the same SQL backend (Sqlite), but we need multiple independent
  implementations to proceed along a standardisation path.

WSC site

Title: Why is Web SQL database deprecated?


问:
Why do C arrays not keep track of their length?
What was the reasoning behind not explicitly storing an array's length with an array in C?

The way I see it, there are overwhelming reasons to do so but not very many in support of the standard (C89). For instance:

Having length available in a buffer can prevent buffer overrun.

A Java-style arr.length is both clear and avoids the programmer from having to maintain many ints on the stack if dealing with several arrays

Function parameters become more cogent.

But perhaps the most motivating reason, in my opinion, is that usually, no space is saved without keeping the length. I would venture to say that most uses of arrays involve dynamic allocation. True, there may be some cases where people use an array allocated on the stack, but that's just one function call* - the stack can handle 4 or 8 bytes extra.

Since the heap manager has to track the free block size used up by the dynamically allocated array anyway, why not make that information usable (and add the additional rule, checked at compile time, that one can't manipulate the length explicitly unless one would like to shoot oneself in the foot).

The only thing I can think of on the other side is that no length tracking may have made compilers simpler, but not that much simpler.

*Technically, one could write some kind of recursive function with an array with automatic storage, and in this (very elaborate) case storing the length may indeed result in effectively more space usage.

答:
From The Development of the C Language:

Structures, it seemed, should map in an intuitive way onto memory in the machine, but in a structure containing an array, there was no good place to stash the pointer containing the base of the array, nor any convenient way to arrange that it be initialized. For example, the directory entries of early Unix systems might be described in C as

```<code>struct {
    int inumber;
    char    name[14];
};
</code>```
I wanted the structure not merely to characterize an abstract object but also to describe a collection of bits that might be read from a directory. Where could the compiler hide the pointer to name that the semantics demanded? Even if structures were thought of more abstractly, and the space for pointers could be hidden somehow, how could I handle the technical problem of properly initializing these pointers when allocating a complicated object, perhaps one that specified structures containing arrays containing structures to arbitrary depth?

The solution constituted the crucial jump in the evolutionary chain between typeless BCPL and typed C. It eliminated the materialization of the pointer in storage, and instead caused the creation of the pointer when the array name is mentioned in an expression. The rule, which survives in today's C, is that values of array type are converted, when they appear in expressions, into pointers to the first of the objects making up the array.

That passage addresses why array expressions decay to pointers in most circumstances, but the same reasoning applies to why the array length isn't stored with the array itself; if you want a one-to-one mapping between the type definition and its representation in memory (as Ritchie did), then there's no good place to store that metadata.

Also, think about multidimensional arrays; where would you store the length metadata for each dimension such that you could still walk through the array with something like

```<code>T *p = &a[0][0];

for ( size_t i = 0; i < rows; i++ )
  for ( size_t j = 0; j < cols; j++ )
    do_something_with( *p++ );
</code>```

Body:
From The Development of the C Language:

Structures, it seemed, should map in an intuitive way onto memory in the machine, but in a structure containing an array, there was no good place to stash the pointer containing the base of the array, nor any convenient way to arrange that it be initialized. For example, the directory entries of early Unix systems might be described in C as

struct {
    int inumber;
    char    name[14];
};

I wanted the structure not merely to characterize an abstract object but also to describe a collection of bits that might be read from a directory. Where could the compiler hide the pointer to name that the semantics demanded? Even if structures were thought of more abstractly, and the space for pointers could be hidden somehow, how could I handle the technical problem of properly initializing these pointers when allocating a complicated object, perhaps one that specified structures containing arrays containing structures to arbitrary depth?

The solution constituted the crucial jump in the evolutionary chain between typeless BCPL and typed C. It eliminated the materialization of the pointer in storage, and instead caused the creation of the pointer when the array name is mentioned in an expression. The rule, which survives in today's C, is that values of array type are converted, when they appear in expressions, into pointers to the first of the objects making up the array.

That passage addresses why array expressions decay to pointers in most circumstances, but the same reasoning applies to why the array length isn't stored with the array itself; if you want a one-to-one mapping between the type definition and its representation in memory (as Ritchie did), then there's no good place to store that metadata.

Also, think about multidimensional arrays; where would you store the length metadata for each dimension such that you could still walk through the array with something like

T *p = &a[0][0];

for ( size_t i = 0; i < rows; i++ )
  for ( size_t j = 0; j < cols; j++ )
    do_something_with( *p++ );


问:
Random forest ML algorithm suitable for use on cluster based HPC?
I need help in identifying a better algorithm.

I have developed a script using pythons scipy package to analyse a rather large model that I wish to solve.  The model contains over 12GB of data including over 500 parameters.

The problem is that when I run small simulations of about 0.5GB of data with 20 parameters it can take my computer a decent amount of time if I allow a reasonable number of iterations through the random forest classifier.

Currently my script is only using one core, so I guess that making the script multi-threaded would be the first step.  But I do not believe this will be enough given how complex the model is. I am willing to explore the use of a cluster based HPC solution but I am not sure how to go about this.

Are there better algorithms I can use, or is there a cluster based algorithm that would be more appropriate?

答:
It is a bit unclear in your question whether you ask about how to parallelize the Random Forests™ 1 algorithm, or you ask which other algorithm would perform better.

On the first issue, it seems that the Random Forests™ algorithm is embarrassingly parallel, and that there is a readily parallel implementation of the algorithm within scikit-learn, using the so-called Ensemble methods. (Do not miss the section on parallelization on that document).

On the second issue, the established opinion seems to be that Random Forests™ are

one of the most successful ensemble methods which exhibits performance on the level of boosting and support vector machines. The method is fast, robust to noise, does not overfit and offers possibilities for explanation and visualization of its output.

as quoted from Robnik-Šikonja, M. (2004). Improving random forests. In Machine Learning: ECML 2004 (pp. 359-370). Springer Berlin Heidelberg.

Which, to me, sounds like you should stick with RF™, then try Adaboost, then try SVM.  You can find them on scikit, too: svm and adaboost.

 1: Random Forests™ is a trademark of Leo Breiman and Adele Cutler.


答:
Python will fall under byte code interpreted. .py source code is first compiled to byte code as .pyc. This byte code can be interpreted (official CPython), or JIT compiled (PyPy). Python source code (.py) can be compiled to different byte code also like IronPython (.Net) or Jython (JVM). There are multiple implementations of Python language. The official one is a byte code interpreted one. There are byte code JIT compiled implementations too.

For speed comparisons of various implementations of languages you can try here.

Title: Is Python Interpreted or Compiled?

Body:
This is just a wondering I had while reading about interpreted and compiled languages.

Ruby is no doubt an interpreted language since the source code is processed by an interpreter at the point of execution.

On the contrary C is a compiled language, as one have to compile the source code first according to the machine and then execute. This results is much faster execution.

Now coming to Python:

A python code (somefile.py) when imported creates a file (somefile.pyc) in the same directory. Let us say the import is done in a python shell or django module. After the import I change the code a bit and execute the imported functions again to find that it is still running the old code. This suggests that *.pyc files are compiled python files similar to executable created after compilation of a C file, though I can't execute *.pyc file directly.

When the python file (somefile.py) is executed directly ( ./somefile.py or python somefile.py ) no .pyc file is created and the code is executed as is indicating interpreted behavior.

These suggest that a python code is compiled every time it is imported in a new process to create a .pyc while it is interpreted when directly executed.

So which type of language should I consider it as? Interpreted or Compiled?
And how does its efficiency compare to interpreted and compiled languages?

According to wiki's Interpreted Languages page, it is listed as a language compiled to Virtual Machine Code, what is meant by that?


问:
gcc -S seems a bit misshapen with shifting and ANDing bits
Example:

```<code>int c = 4;
int p = 5;

if (p & (1 << c))
   printf("ok\n");
else
   printf("nop\n");
</code>```

gcc -S:

```<code>movl    -4(%rbp), %eax   /* eax holds the variable c  */
movl    -8(%rbp), %edx   /* and edx holds p  */
movl    %eax, %ecx       /* tmp(ecx) = c  */
sarl    %cl, %edx        /* edx(p) >>= c  */
movl    %edx, %eax       /* eax = p shifted right by c */
andl    $1, %eax         /* eax(p shifted right by c) &= 1  */
testl   %eax, %eax       /* test if p is 0  */
... jumps and such ...
</code>```

As you can see, GCC for some reason converted my code to:

```<code>p >>= c;
p &= 1
if (p != 0)
    ...
else
    ...
</code>```

Something fishy is going on here or I am missing something...  It kinda made the operation backwards, although I had brackets around the 1 << c so it should've done it separately then AND it with p correct?

Can someone explain why did GCC do this?  Is it some sort of optimization (I had no optimization enabled when I compiled this, so doubt it) Or is it how it should be done in assembly?

答:
It is likely some sort of optimization.  Not all optimizations must be explicitly enabled.  The safest ones will be enabled unless explicitly disabled, which seems to be the case here.  Running the following command on my system shows 47 optimizations enabled by default:</p>

```<code>gcc -Q --help=optimizers
</code>```

Body:
It is likely some sort of optimization.  Not all optimizations must be explicitly enabled.  The safest ones will be enabled unless explicitly disabled, which seems to be the case here.  Running the following command on my system shows 47 optimizations enabled by default:

gcc -Q --help=optimizers


问:
Live search/filter as you type in client approach
As an exercise for myself to practice my JavaScript "skills" I'm trying to write a client-side filter. It should be able to filter "content blocks" as the user types.

By "content block", I mean a list of DomElements that each contain at least one text node - it is possible that they contain more, and even a different amount of text nodes, nested inside other nodes, etc.

I've thought of 2 approaches:

On page initialization, scan all nodes and store all the text in some kind of Map or a tree.

Simply iterate over every item and check whether it has the string to search/filter for. One could add performance here by caching, only filtering the current remaining items if text is added, etc.

Obviously, if the number of nodes is really big, option 1 will take a while to build the 'index' but it will perform faster once it is built. Option 2 however will be available right on page load since no initialization is performed. But of course it will take longer to search.

So my question is: what is the best approach here? And how would one implement 'caching' and/or 'index'?

答:
I would assign an index by placing a property on each element after putting them in some type of list or array.

textArray[index].Index = counter;
counter++;


问:
Why can't arrays be passed as function arguments in C?
Following this comment, I've tried to google why, but my google-fu failed.

Comment from link:

[...] But the important thing is that arrays and pointers are different things in C.

Assuming you're not using any compiler extensions, you can't generally pass an array itself to a function, but you can pass a pointer, and index a pointer as if it were an array.

You're effectively complaining that pointers have no length attached. You should be complaining that arrays can't be passed as function arguments, or that arrays degrade to pointers implicitly.

答:
My first guess for the reason was simply because of performance and memory saving reasons, and for the ease of compiler implementation as well  (especially for the kind of computers at the time when C was invented). Passing huge arrays "by value" seemed to have a huge impact at the stack, it needs a full array copy operation for each function call, and probably the compiler must be smarter to output the correct assembly code (though the last point is debatable). It would also be more difficult to treat dynamically allocated arrays the same way as statically allocated arrays (from the viewpoint of the language's syntax).

EDIT: after reading some parts from this link, I think the real reason (and the reason why arrays in structs are treated as value types, while sole arrays are not) is the backward compatibility to C's predecessor B. Here is the cite from Dennis Ritchie:

[...} The solution constituted the crucial jump in the evolutionary chain
between typeless BCPL and typed C. It eliminated the materialization
of the pointer in storage, and instead caused the creation of the
pointer when the array name is mentioned in an expression. The rule,
which survives in today's C, is that values of array type are
converted, when they appear in expressions, into pointers to the first
of the objects making up the array.

This invention enabled most existing B code to continue to work,
despite the underlying shift in the language's semantics. [..]


问:
Where are all the functional programming design patterns?
OO programming literature is full of design patterns. Most books on object oriented programming dedicate a chapter or two to design patterns like factories and decorators. So what are the equivalent patterns in functional languages and why hasn't anyone written a book about them yet? Is there something special about functional languages that obviates the need for design patterns?</p>

答:
If you're genuinely interested in learning the design patterns look no further than Haskell.  If you take the time to learn the language the hard way you'll run into and get cozy with most of the foundational patterns -- they're baked into the language.

Don't skip over monads.  There are a bunch of long-winded explanations out there and it takes some doing to have the ideas sink in, but if you keep plugging away, eventually it'll dawn on you and you'll be amazed at how many design patterns can be build on top of this one abstraction/interface.

Once you grok Haskell, you'll have enough of the FP arsenal at your disposal to be dangerous.  Point is, keep at it until you get it.  There are no shortcuts.


问:
What is a typical team size for a complex half million lines-of-code C# desktop application?
Imagine the following scenario:

Codebase of 600,000 lines of code (C#)

All in a single desktop application

All written by a single developer (myself) over 8 years (3 years worth of actual coding time).

The software is powerful and flexible (obviously vague), thus there is inherent complexity in the code, even if it is modular and low in debt.

The software is in a niche machine control industry, so there is a very long ramp up for domain knowledge of both the machines, and the code.

The software will become more and more custom where individual customers get their own addons and enhancements

What would be a recommended software team size for a half million line codebase (C# desktop) like the one above? What would be ideal for a typical 500k LOC C# desktop application?

This software is not 'end to end' lifecycle. It is 'end to infinity' meaning it will continue to grow and get bigger and and more powerful and complex. Especially as more engineers are added to the team.

答:
Size of the code base isn't really the right metric for determining team size.  Rather, look at the size of your backlog.  If you're still handling customer requests in a time frame that makes them happy, then a team size of one is all you need.  If you're losing money because you can't fulfill customer requests in time, then you add people until that's no longer the case, obviously taking the mythical man month effect into account.  It will take several months before you know if a newly trained team can handle your workload.

Where exactly that line is depends on the business more than the app, although obviously there is some correlation with app size and complexity.  For example, refactoring a messy code base will enable you to fulfill customer requests more quickly, but maybe not quickly enough to avoid hiring additional team members.


答:
The code size is not atypical for a single person three year project (as in, I've seen a few C++ projects with a similar number of semi-colons developed by single people in two or three years).

As with anything, the team size maintenance and feature enhancements will depend on several parameters, including

How much money there is to throw at it

How quickly enhancements need to be delivered

How well factored the code is

is there a plug-in system, or even a scripting system for domain experts to add code without having to be software engineers?

is the code modular so tasks such as 'tidy up the dialogs' can be done by coders without domain knowledge?

are there systems in the organisation for establishing specifications so expert testers can be brought it who are not domain experts?

How many features are required to be added?

Almost none of these actually depends on the code size, but on the quality. In my experience, larger projects developed by single authors over many years tend to be somewhat idiosyncratic and don't automatically get the features required for opening up to larger teams ( so I now try to stop getting to being the only dev on large projects ).

Title: What is a typical team size for a complex half million lines-of-code C# desktop application?

Body:
Imagine the following scenario:

Codebase of 600,000 lines of code (C#)

All in a single desktop application

All written by a single developer (myself) over 8 years (3 years worth of actual coding time).

The software is powerful and flexible (obviously vague), thus there is inherent complexity in the code, even if it is modular and low in debt.

The software is in a niche machine control industry, so there is a very long ramp up for domain knowledge of both the machines, and the code.

The software will become more and more custom where individual customers get their own addons and enhancements

What would be a recommended software team size for a half million line codebase (C# desktop) like the one above? What would be ideal for a typical 500k LOC C# desktop application?

This software is not 'end to end' lifecycle. It is 'end to infinity' meaning it will continue to grow and get bigger and and more powerful and complex. Especially as more engineers are added to the team.


问:
Is the GPL dangerous to the organisation in terms of exposure of its intellectual property?
GNU General Public License is a ‘Viral License”. If an organisation is using Linux and MySQL which come under this license, is it  dangerous to the organisation in terms of exposure of its intellectual property? As this license will demand the  software that is linked to or that incorporates a GPL program to also be made available in source form under the same license when it is “distributed.”</p>

答:
The GPL cannot compel you to release your source code!

The GPL is a license, not a contract.  If you are found in violation of the GPL license, all the copyright holder can compel you to do is to remedy the violation.  This can be done by either:

Releasing your source code, or

Discontinuing your use of the GPL code.

There may also possibly be damages levied, but since I'm not a lawyer I can't really speak to that.

Linux and MySQL

Linux is an operating system.  Suffice it to say that, unless you're writing some sort of kernel-specific code, using Linux  does not create a derived work, and therefore you can license your program that runs on Linux any way you wish, without worrying about GPL violations.

MySQL has a dual-licensing model.  You can use it in your application for free under the GPL (which requires you to open your source), or you can buy a commercial license and license your code any way you want.

Further Reading

The GPL is  a License, not a Contract.

How Scary are GPL Violations?

Violations of the GNU Licenses

When are you required to have a commercial MySQL license?


问:
Reconciling the Boy Scout Rule and Opportunistic Refactoring with code reviews
I am a great believer in the Boy Scout Rule:

Always check a module in cleaner than when you checked it out." No
  matter who the original author was, what if we always made some
  effort, no matter how small, to improve the module. What would be the
  result? I think if we all followed that simple rule, we'd see the end
  of the relentless deterioration of our software systems. Instead, our
  systems would gradually get better and better as they evolved. We'd
  also see teams caring for the system as a whole, rather than just
  individuals caring for their own small little part.

I am also a great believer in the related idea of Opportunistic Refactoring:

Although there are places for some scheduled refactoring efforts, I
  prefer to encourage refactoring as an opportunistic activity, done
  whenever and wherever code needs to cleaned up - by whoever.
  What this means is that at any time someone sees some code that isn't
  as clear as it should be, they should take the opportunity to fix it
  right there and then - or at least within a few minutes

Particularly note the following excerpt from the refactoring article:

I'm wary of any development practices that cause friction for
  opportunistic refactoring ... My sense is that most teams don't do
  enough refactoring, so it's important to pay attention to anything
  that is discouraging people from doing it. To help flush this out be
  aware of any time you feel discouraged from doing a small refactoring,
  one that you're sure will only take a minute or two. Any such barrier
  is a smell that should prompt a conversation. So make a note of the
  discouragement and bring it up with the team. At the very least it
  should be discussed during your next retrospective.

Where I work, there is one development practice that causes heavy friction - Code Review (CR). Whenever I change anything that's not in the scope of my "assignment" I'm being rebuked by my reviewers that I'm making the change harder to review. This is especially true when refactoring is involved, since it makes "line by line" diff comparison difficult. This approach is the standard here, which means opportunistic refactoring is seldom done, and only "planned" refactoring (which is usually too little, too late) takes place, if at all.

I claim that the benefits are worth it, and that 3 reviewers will work a little harder (to actually understand the code before and after, rather than look at the narrow scope of which lines changed - the review itself would be better due to that alone) so that the next 100 developers reading and maintaining the code will benefit. When I present this argument my reviewers, they say they have no problem with my refactoring, as long as it's not in the same CR. However I claim this is a myth:

(1) Most of the times you only realize what and how you want to refactor when you're in the midst of your assignment. As Martin Fowler puts it:

As you add the functionality, you realize that some code you're adding
  contains some duplication with some existing code, so you need to
  refactor the existing code to clean things up... You may get something
  working, but realize that it would be better if the interaction with
  existing classes was changed. Take that opportunity to do that before
  you consider yourself done.

(2) Nobody is going to look favorably at you releasing "refactoring" CRs you were not supposed to do. A CR has a certain overhead and your manager doesn't want you to "waste your time" on refactoring. When it's bundled with the change you're supposed to do, this issue is minimized.

The issue is exacerbated by Resharper, as each new file I add to the change (and I can't know in advance exactly which files would end up changed) is usually littered with errors and suggestions - most of which are spot on and totally deserve fixing.

The end result is that I see horrible code, and I just leave it there. Ironically, I feel that fixing such code not only will not improve my standings, but actually lower them and paint me as the "unfocused" guy who wastes time fixing things nobody cares about instead of doing his job. I feel bad about it because I truly despise bad code and can't stand watching it, let alone call it from my methods!

Any thoughts on how I can remedy this situation ?

答:
I too am a great believer in The Boyscout Rule and Opportunistic Refactoring.  The problem is often in getting management buy in.  Refactoring comes with both risk and cost.  What management often overlooks is that so too does technical debt.

It's human nature.  We're used to dealing with real problems, not trying to prevent them.  We're reactive, not proactive.

Software is intangible and so it's hard to understand that, like a car, it needs servicing.  No reasonable person would buy a car and never service it.  We accept that such negligence would decrease its longevity and, in the long run, be more costly.

Despite the fact that many managers understand this, they are held accountable for changes to production code.  There are politics that make it easier to leave well enough alone.  Often the person needing convincing is actually above your manager and he simply doesn't want to fight to get your "great ideas" into production.

To be honest, your manager is not always convinced that your remedy is, in fact, as great as you think it is.  (Snake oil?) There's salesmanship.  It's your job to help him see the benefit.

Management doesn't share your priorities.  Put on your management hat and see with management eyes.  You'll more likely find the right angle.  Be persistent.  You'll effect more change by not allowing the first negative response to deter you.


答:
The Python runtime runs custom object code(byte code) on a virtual machine.

The compilation process converts source code to object code.

To speed things up, the object code (or byte code, if you prefer) is stored on disk, so it can be reused the next time the program is run.

Title: Is Python Interpreted or Compiled?


答:
A PDP minicomputer with only 8 kB of memory can't allocate a very large stack.  So, on such a machine, one has to be careful in a language design (or evolution) to be able to minimize what needs to go on the stack for expected common subroutine call usage.  C is still used today to program extremely memory constrained (a few kB) embedded systems, so the trade-off is usually a good one.

On a processor architecture which has very few registers, passing any array by pointer rather than by value more often allows a register to be used as a subroutine call optimization.

Title: Why can't arrays be passed as function arguments in C?

Body:
Following this comment, I've tried to google why, but my google-fu failed.

Comment from link:

[...] But the important thing is that arrays and pointers are different things in C.

Assuming you're not using any compiler extensions, you can't generally pass an array itself to a function, but you can pass a pointer, and index a pointer as if it were an array.

You're effectively complaining that pointers have no length attached. You should be complaining that arrays can't be passed as function arguments, or that arrays degrade to pointers implicitly.


问:
Presenter accessing the value in text box using sender object
I have following method in my presenters which validates the user inputs on the UI. Basically to capture the value of the text property of the text box, it uses sender object which was passed in by the event fire on the form.

PRESENTER

```<code>_View.ValidateInPut += new EventHandler(_View_ValidateInPut);

private void _View_ValidateInPut(object sender,  EventArgs e)
{
    var controller = (TextBox)sender;
    var text = controller.Text;

    If (text is InValid)
    MessageBox.Show ("The value in the Text box is invalid");

}
</code>```

VIEW

```<code>private void txtACNo_Validating(object sender, CancelEventArgs e)
{
    ValidateInPut(sender, e); // Firing the event
}
</code>```

Will this lead to unexpected errors?

If so please let me know a better way to do this?

答:
I don't think it is a wise idea to have View and Presenter being coupled so tight.

Based on either the Passive Screen
or Supervising Presenter the presenter and the view are separated by an interface that is implemented by the view. The presenter calls the interface. Here is an example of a supervising presenter.

PRESENTER

this class has no dependency on the used GUI library

```<code>public class Presenter
{
    IView view;
    public Presenter(IView view)
    {
        this.view = view;
    }

    public void ValidateInPut(string value)
    {
        if (!String.IsEmptyOrNull(value) && value.Contains("9"))
        {
           view.ShowError("The value in the Text box is invalid");
        }
    }
}
</code>```

ViewInterface

```<code>public inteface IView
{
    void ShowError(string message);
}
</code>```

VIEW

```<code>public class Form1:Form, IView
{
    private Presenter presenter;
    public Form1()
    {
         this.presenter = new Presenter(this); // or have a Dependcy Injection Framework do this
    }

    private void txtACNo_Validating(object sender, CancelEventArgs e)
    {
        presenter.ValidateInPut(txtACNo); // validate
    }

    public void IView.ShowError(string message);
    {
        MessageBox.Show(mesage);
    }
}
</code>```

Rationale

By utilizing your view and presenter the presenter (with all its (busines)logic) becomes easily testable or the view can be replaced by a WebPage without the need to adapt your presenter logic.

Test

```<code>public class Test:IView
{
    bool showErrorCalled = false;

    public void Test()
    {
       var p = new Presenter(this);
       showErrorCalled = false;
       p.ValidateInput("8");
       Test.Assert(showErrrocalled);
    }

    public void IView.ShowError(string message);
    {
        showErrorCalled = true;
    }
}
</code>```

WebPage

```<code>public Default:Page, IView
{
      private Presenter presenter;
      public Default()
      {
          this.presenter = new Presenter(this);
      }

      public Page_Load(object sender, EventArgs e)
      {
          if (IsPostBack)
          {
               presenter.ValidateInput(txtAcNo.Text);
          }
      }

      public void IView.ShowError(string message);
      {
          Error.Text = message;
      }

}
</code>```

PS

Remember that the cast operator on an object may fail. Your code

```<code>var controller = (TextBox)sender;
</code>```

will only work as long as sender is a TextBox. It is better to check if there is a more generalized type up the hierarchy that still provides you with the needed interface. In your case that could be Control that has a Text property as well. A more defensive approach would be:

```<code>var controller = sender as Control; // try to cast, if not return null
if (controller != null)
{
     // do stuff with controller
}
else
{
    // logging
    Debug.WriteLine("controller is null");
}
</code>```

Body:
I don't think it is a wise idea to have View and Presenter being coupled so tight.

Based on either the Passive Screen
or Supervising Presenter the presenter and the view are separated by an interface that is implemented by the view. The presenter calls the interface. Here is an example of a supervising presenter.

PRESENTER

this class has no dependency on the used GUI library

public class Presenter
{
    IView view;
    public Presenter(IView view)
    {
        this.view = view;
    }

    public void ValidateInPut(string value)
    {
        if (!String.IsEmptyOrNull(value) && value.Contains("9"))
        {
           view.ShowError("The value in the Text box is invalid");
        }
    }
}

ViewInterface

public inteface IView
{
    void ShowError(string message);
}

VIEW

public class Form1:Form, IView
{
    private Presenter presenter;
    public Form1()
    {
         this.presenter = new Presenter(this); // or have a Dependcy Injection Framework do this
    }

    private void txtACNo_Validating(object sender, CancelEventArgs e)
    {
        presenter.ValidateInPut(txtACNo); // validate
    }

    public void IView.ShowError(string message);
    {
        MessageBox.Show(mesage);
    }
}

Rationale

By utilizing your view and presenter the presenter (with all its (busines)logic) becomes easily testable or the view can be replaced by a WebPage without the need to adapt your presenter logic.

Test

public class Test:IView
{
    bool showErrorCalled = false;

    public void Test()
    {
       var p = new Presenter(this);
       showErrorCalled = false;
       p.ValidateInput("8");
       Test.Assert(showErrrocalled);
    }

    public void IView.ShowError(string message);
    {
        showErrorCalled = true;
    }
}

WebPage

public Default:Page, IView
{
      private Presenter presenter;
      public Default()
      {
          this.presenter = new Presenter(this);
      }

      public Page_Load(object sender, EventArgs e)
      {
          if (IsPostBack)
          {
               presenter.ValidateInput(txtAcNo.Text);
          }
      }

      public void IView.ShowError(string message);
      {
          Error.Text = message;
      }

}

PS

Remember that the cast operator on an object may fail. Your code

var controller = (TextBox)sender;

will only work as long as sender is a TextBox. It is better to check if there is a more generalized type up the hierarchy that still provides you with the needed interface. In your case that could be Control that has a Text property as well. A more defensive approach would be:

var controller = sender as Control; // try to cast, if not return null
if (controller != null)
{
     // do stuff with controller
}
else
{
    // logging
    Debug.WriteLine("controller is null");
}


问:
When is a BIG Rewrite the answer?
Just read the question about the Big Rewrites and I remembered a question that I've been wanting answered myself.

I have a horrible project passed down to me, written in old Java, using Struts 1.0, tables with inconsistent relationships, or no relationships at all and even tables without primary keys or fields meant to be primary keys but aren't unique at all. Somehow most of the app "just works". Most of the pages are reused (copy pasted code) and hard-coded. Everyone who's ever worked on the project has cursed it in one form or the other.

Now I had long considered to propose to upper management a total rewrite of this horrendous application.  I'm slowly attempting to on personal time but I really feel that this deserves some dedicated resources to make it happen. Having read the articles on big rewrites I'm having second thoughts. And that's not good when I want to convince my superiors to support my rewrite. (I work in a fairly small company so the proposal has the possibility of being approved)

TL;DR
When is a big rewrite the answer and what arguments can you use to support it?

答:
It's the answer when the rewrite allows the organization to pursue a strategy that affords a competitive edge or allows it to better serve its customers in some manner that the current architecture cannot accommodate.

Instead, rewrites often happen to alleviate management worries:

everything should be in .NET,

our developers say our code sucks,

we're falling behind technically,

we won't be able to find resources to support our system or, very often,

it's been ten years so it's time.

Most of these worries won't materialize and, if they did, they could be handled.  That last one, however, is the worst.  It's essentially: we don't have a reason.

Yes, like car, a system will begin to show signs of wear.  This can be alleviated by routine servicing.  You know what they say about how a little preventative maintenance goes a long way.  As an investment, routine servicing (i.e. refactoring and standardizing) will almost always carry less cost than a rewrite.

However, we have to anticipate that a rewrite will eventually be necessary.  Set dates and tentatively plan for it, but as the date draws nearer delay in favor of realizing other strategic goals until you have a compelling reason like...

In recent years we've lost the opportunity to win big accounts because we couldn't accommodate their needs in a timely or costly fashion.  Our system will be rewritten using an extensible architecture that allows customizations to be plugged in (and not hardcoded as we currently do).  This will dramatically decrease the time and cost of accommodating customers with special needs.  We'll win more accounts and better meet the needs of our current customers.

Title: When is a BIG Rewrite the answer?


问:
What happens if you're unable to solve a problem?
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?

答:
In my experiece, sometimes there's problem that you can't solve, at least in time restriction. So seeking help as soon as possible, after some solving effort failed you.

Remember the rule of thumb: always look at the reason the boss hires you. Do whatever you think you can do for the best work result, and sometimes that's an early fail report (far better than a late one).

In short, if you think you may find the solution, feel free to try, but give your boss estimation about the risk and the time cost. It's their problem now.


问:
I'm doing 90% maintenance and 10% development, is this normal?
I have just recently started my career as a web developer for a medium sized company. As soon as I started I got the task of expanding an existing application (badly coded, developed by multiple programmers over the years, handles the same tasks in different ways, zero structure).

So after I had successfully extended this application with the requested functionality, they gave me the task to fully maintain the application. This was of course not a problem, or so I thought. But then I got to hear I wasn't allowed to improve the existing code and to only focus on bug fixes when a bug gets reported.

From then on I have had three more projects just like the above, that I now also have to maintain. And I got four projects where I was allowed to create the application from scratch, and I have to maintain those as well.

At this moment I'm slightly beginning to get crazy from the daily mails of users (read managers) for each application I have to maintain. They expect me to handle these mails directly while also working on two other new projects (and there are already five more projects lined up after those). The sad thing is I have yet to receive a bug report on anything that I have coded myself. For that I have only received the occasional let's-do-things-180-degrees-different change requests.

Anyway, is this normal? In my opinion I'm doing the work equivalent of a whole team of developers.

Was I an idiot when I initially expected things to be different?

I guess this post has turned into a big rant, but please tell me that this is not the same for every developer.

P.S. My salary is almost equal if not lower than that of a cashier at a supermarket.

答:
The answer is to try and explain it in terms that can be understood;

It's like oil changes.  They aren't urgent.... but must be done regularly none the less

paint over rust and it'll look great.  Until it bleeds through

build a new roof patio roof desk without strengthing supports.  It will work for a while maybe.  Then it will collapse and hurt people and you will be responsible.

a/c is great.  A window unit is great for one or two room.  Trying to put 146 window unit air-conditioners in an aartment building and you will have... problems.

Teaching 5 kids is fine.  10's not too bad.  But there ARE limits.  Try informally teaching 75 kids and you will see this.

If these are not resonating. Leave - THE DAY YOU GET AN OFFER ON WRITING, not the next day!  Once you HAVE a new job, leave with ZERO notice.  Literally just don't come in that day.  But make sure you have a colleague or two who know what you did.  This will actually help the company out, if the company can be helpd, by showing them that their disrespect and arrogance comes at a price.  Last company I was at THREE OF THE FOUR TECH'S LEFT WITHIN 6 MONTHS WITH NO JOB TO GO TO.  It made a statement at least and gave the leaving person once good chance to say, 'yeah, nice bs you say every day but you are so full of it, I'm not even giving you the satisfaction of my notice.

Finally, do know that this stae of affairs was the NORM and the standard 20 years ago before agile, tdd, bdd and refactoring became more then norm.  You may be talking with senior people who immediately respond "well I have done this myself and it worked fine, blah, blah, blah." Well, s ure horses and carriages worked well 150 years ago.  In technology areas, techniques from 20 years ago are as outdated as transportation from 150 years ago.  If they reject this fine.  Just know that they will never hire any decent current technology developers who will stick around.  They will get the worst of the worst and it will hurt their business terribly.  If they depend on technology and can't adapt they will fail and ultimately that may be the best reward for you.  It's just that it may take a while as dysfuntional organizations can continue for a long time.


问:
When to used static visibility?
I can't attain the primary used of Static Visibility. My question is why they used static method & properties in this code?</p>

```<code>class PassHash {

    // blowfish
    private static $algo = '$2a';
    // cost parameter
    private static $cost = '$10';

    // mainly for internal use
    public static function unique_salt() {
        return substr(sha1(mt_rand()), 0, 22);
    }

    // this will be used to generate a hash
    public static function hash($password) {

        return crypt($password, self::$algo .
                self::$cost .
                '$' . self::unique_salt());
    }

    // this will be used to compare a password against a hash
    public static function check_password($hash, $password) {
        $full_salt = substr($hash, 0, 29);
        $new_hash = crypt($password, $full_salt);
        return ($hash == $new_hash);
    }

}
</code>```

答:
Ask yourself if a given method requires any state that is specific to an object instance.  If it does not, static is appropriate, since the method is scoped to the class itself, not to the object instance.

static methods are essentially utility methods; they take parameters, and return a value; nothing more.

Consider

```<code>public static function check_password($hash, $password) {
    $full_salt = substr($hash, 0, 29);
    $new_hash = crypt($password, $full_salt);
    return ($hash == $new_hash);
}
</code>```

Does it require any state that is specific to an object instance?  Is everything that it needs passed in as parameters?  Does it store any state?  Does it return an idempotent value?

Also, do you want to be able to call it without requiring a class instance?

If all of these things are true, static scoping is more appropriate than object scoping.

Title: When to used static visibility?

Body:
Ask yourself if a given method requires any state that is specific to an object instance.  If it does not, static is appropriate, since the method is scoped to the class itself, not to the object instance.

static methods are essentially utility methods; they take parameters, and return a value; nothing more.

Consider

public static function check_password($hash, $password) {
    $full_salt = substr($hash, 0, 29);
    $new_hash = crypt($password, $full_salt);
    return ($hash == $new_hash);
}

Does it require any state that is specific to an object instance?  Is everything that it needs passed in as parameters?  Does it store any state?  Does it return an idempotent value?

Also, do you want to be able to call it without requiring a class instance?

If all of these things are true, static scoping is more appropriate than object scoping.


问:
Why doesn't C++ allow you to take the address of a constructor?
Is there a specific reason that this would break the language conceptually or a specific reason that this is technically infeasible in some cases?

The usage would be with new operator.

Edit: I'm going to give up hope on getting my "new operator" and "operator new" straight and be direct.

The point of the question is: why are constructors special? Keep in mind of course that language specifications tell us what is legal, but not necessarily moral. What is legal is typically informed by what is logically consistent with the rest of the language, what is simple and concise, and what is feasible for compilers to implement. The possible rationale of the standards committee in weighing these factors are deliberate and interesting -- hence the question.

答:
Pointers-to-member functions make only sense if you have more than one member function with the same signature - otherwise there would be only one possible value for your pointer. But that is not possible for contructors, since in C++ different constructors of the same class must have different signatures.

The alternative for Stroustrup would have been to choose a syntax for C++ where constructors could have a name different from the class name - but that would have prevented some very elegant aspects of the existing ctor syntax and had made the language more complicated. For me that looks like a high price just to allow a seldom needed feature which can be easily simulated by "outsourcing" the initialization of an object from the ctor to a different init function (a normal member function for which pointer-to-members can be created).


问:
Mental Models or Real-World-Metaphors for Functional Programming
Does anyone have a good mental model or metaphor for functional programming which references something in the real world?

Object Oriented programing intuitively makes sense to me. There are things that have properties and sometimes they also can do stuff or perform calculations on their properties (methods). (Ex: Car, Shape, Cat).

I bear functional programming no ill will whatsoever and I am not interested in a debate about the virtues of the two. I just need a metaphor or mental model to work with as I have with Object Oriented programming.

What are some good mental models or real world metaphors for programming in a functional paradigm? There is something about functions composed of functions processing functions which leaves one without a firm place to stand and cogitate.

答:
The key thing thing to realize about functional programing is that everything is a value - even the code itself is 'values'.

The best example of a simple functional programing environment is that of everyone's favorite business tool - the spreadsheet.  Every cell in the spreadsheet is either data, or the result of a function.  Whats more, this function can't go off and modify another cell.

When one moves to a functional languages, instead of a Cartesian grid of A1 and B42, the functions have names.  That's all it really is.

There are other aspects that one can add on beyond this... but that's functional programing at its core.  One needn't worry about the structure of lists or the grouping of things.  Functional programming is about passing a value into a function and getting a value back without having any mucking about elsewhere in memory.

Thats it.  Functional programming is a spreadsheet with names rather than a grid.


问:
Should accessible members of an internal class be internal too?
I'm designing a set of APIs for some applications I'm working on.  I want to keep the code style consistent in all the classes I write but I've found that there are a few inconsistencies that I'm introducing and I don't know what the best way to resolve them is.

My example here is specific to C# but this would apply to any language with similar mechanisms.

There are a few classes that I need for implementation purposes that I don't necessarily want to expose in the API so I make them internal whereever needed.

Generally what I would do is design the class as I normally would (e.g., make members public/protected/private where necessary) and change the visibility level of the class itself to internal.  So I might have a few classes that look like this:

internal interface IMyItem
{
    ItemSet AddTo(ItemSet set);
}

internal class _SmallItem : IMyItem
{
    private readonly /* parameters */;
    public _SmallItem(/* small item parameters */) { /* ... */ }

    public ItemSet AddTo(ItemSet set) { /* ... */ }
}

internal abstract class _CompositeItem: IMyItem
{
    private readonly /* parameters */;
    public _CompositeItem(/* composite item parameters */) { /* ... */ }

    public abstract object UsefulInformation { get; }
    protected void HelperMethod(/* parameters */) { /* ... */ }
}

internal class _BigItem : _CompositeItem
{
    private readonly /* parameters */;
    public _BigItem(/* big item parameters */) { /* ... */ }

    public override object UsefulInformation
    {
        get { /* ... */ }
    }

    public ItemSet AddTo(ItemSet set) { /* ... */ }
}
```

<p>In another generated class (part of a parser/scanner), there is a structure that contains fields for all possible values it can represent.  The class generated is <code>internal</code> too but I have control over the visibility of the members and decided to make them <code>internal</code> as well.</p>

<pre class="lang-cs prettyprint-override"><code>internal partial struct ValueType
{
    internal string               String;
    internal ItemSet              ItemSet;
    internal IMyItem              MyItem;
}

internal class TokenValue
{
    internal static int EQ(ItemSetScanner scanner) { /* ... */ }
    internal static int NAME(ItemSetScanner scanner, string value) { /* ... */ }
    internal static int VALUE(ItemSetScanner scanner, string value) { /* ... */ }
    //...
}
</code>```

To me, this feels odd because the first set of classes, I didn't necessarily have to make some members public, they very well could have been made internal.  internal members of an internal type can only be accessed internally anyway so why make them public?  I just don't like the idea that the way I write my classes has to change drastically (i.e., change all uses of public to internal) just because the class is internal.

Any thoughts on what I should do here?

It makes sense to me that I might want to make some members of a class declared public, internal.  But it's less clear to me when the class is declared internal.

答:
As far as C# specification is concerned, there is no difference when you make a method internal or public so long as the type that holds it is internal. The only consideration might be that if you were to make the class public in the future, whichever methods you are likely to make public then, you could do that now. However, you may find differences of opinion even on this topic.

It comes to a matter of preference on your part (and your team) and I doubt that you may even get an agreement within your team if it's more than a few developers, let alone on a community as broad as this.

In addition, these preferences work well for any new code being written, but for any existing code, there is no benefit to justify the cost of changing the code (except for developer's own sanity). I have seen code written in both styles, even within the same project by two different developers.

As for the specification, pertinent parts of section 3.5.2 (p. 61) of C# 5.0 language specification states the following (and I believe it is the same in previous versions too):

The accessibility domain of a nested member M declared in a type T
  within a program P is defined as follows (noting that M itself may
  possibly be a type):

If the declared accessibility of M is public, the accessibility domain of M is the accessibility domain of T.

If the declared accessibility of M is internal, the accessibility domain of M is the intersection of the accessibility domain of T with
  the program text of P.

Since accessibility domain of T in your case is internal, so accessibility domain of M is the same regardless of it being internal or public.

OwnerDisplayName: Jeff Mercado


问:
Is duplicate syntax for defining named functions a bad language design decision?
I am modelling a programming language for fun, and the syntax is heavily influenced by Scala - specifically function definitions.

I have encountered a design problem because my language does not differentiate between functions defined via the def syntax (class methods) and anonymous functions assigned to values (created using =>) - it removes the differences in both implementation and behaviour.

The result is that the following two definitions mean the same thing:

```<code>def square(x: Int) = x*x

val square = (x: Int) => x*x
</code>```

There is no reason for the latter form (immediate anonymous function assignment) to be used in any normal situation - it's simply possible to use it instead of the def form.

Would having such duplicate syntax for defining named functions hurt the orthogonality of the language or some other design aspect?

I prefer this solution because it allows for short and intuitive definitions of methods and named functions (via def), and short definitions of anonymous functions (using =>).

Edit: Scala does differentiate between the two - anonymous functions are not the same as methods defined with def in Scala. The differences are relatively subtle though - see the posts I linked before.

答:
What you've posted is valid scala and works fine.

Given that the doubling hasn't caused issues with scala (to my knowledge), I'm going to say that it won't be a problem for your language either.


问:
Best books on the theory and practice of software architecture?
I have a couple of developers at my company who wish to move from programming into architecture. What are the best books out there on the theory and practice of software architecture? Include a cover picture if you can.

Feel free to include general books, and also books that relate to a specific technology.

答: I recommend Expert One-on-One J2EE Design and Development. It's a very good book about J2EE, and is the theory basement of Spring Framework.</p>


问:
Would you get better performances by coding an application in C, then compile to JavaScript?
I am writing an interpreter for a functional programming language that is going to run in the browser. Needless to say, performance is the one and only concern in this application. Emscripten is an LLVM→JavaScript compiler which claims to produce programs that run only 2~3 times slower than native. It is really surprising, considering actual JavaScript applications tend to run 7 to 10 times slower than native, according to the Computer Benchmarks Game. And those are exactly the types of application I am worried about.

So, said that, would it be profitable to code my application in C, and then compile it to JavaScript using asm.js, or is there something I am missing?

答:
Your proposed approach is as follows:

Code your interpreter in C.

Compile the C to Javascript using Emscripten or asm.js.

Run Javascript using (I guess) a browser resident Javascript implementation.

(If the Javascript implementation is not browser resident, then I don't see the point of Javascript.  Compiling the C directly to native code will be faster.)

You postulate that (based on the assertions of the Emscripten / asm.js proponents), this would give you a faster interpreter than if you coded directly in Javascipt.

Now it may well be true that a C -> Javascript application runs faster than a typical hand-written Javascript version of a C application.  But when you think about it, if the tools capable of generating javascript that runs fast, then someone who understands how to write optimizable javascript should be able to write code that runs just as fast.  And in fact, they may even be able to do better, especially if they take the time to profile and tune the javascript.

And as comments pointed out, if you take the C -> Javascript route it will be impractical to hand optimize the generated Javascript.

But it really boils down to how good you are at writing Javascript ... compared to what those tools will generate it from some hypothethical C code that hasn't even been written yet.  Nobody can give you an answer that is both definite and credible.

But I think that your big picture thinking is a bit astray:

Needless to say, performance is the one and only concern in this application.

That is short-sighted.  There are other concerns; i.e. speed of coding, easy of debugging, maintainability, portability and ... correctness.  And in fact, these should be taken into account your choice of implementation approach.

And the flipside is that if interpreter performance is really your one and only concern, then maybe you should implement it in C, compile directly to native code and ship it as a native plugin.  Or implement a compiler for your functional language rather than an interpreter.


问:
A new i/o library: a good idea or a really bad one?
For a long time I worked almost exclusively with input/output streams in java. However a few years ago I started exploring async I/O as well (e.g. running on jboss netty).

However when working in the async I/O world, I could not reuse any of my sync utilities. I also had to start on a rather large library of new I/O utilities and wasn't sure whether to aim for blocking or non-blocking.

As things go...I wrote an API on top of the existing I/O which supports both blocking and non-blocking and the utilities are written against that.

However because I/O is such a pervasive thing, I am unsure whether it is a wise thing to do. As an example take a Base64 encoder. Yes apache has a sync I/O version and yes java 8 finally has an async encoder. But I needed an encoder that could do both.

Same for quoted-printable, deflate,... and of course it should work for sockets (regular & ssl), files,... in single-threaded and multithreaded situations,... I needed utilities to chain together I/O sources, use delimiter-based or fixed-length I/O wrappers,... I needed protocol handlers for http, ftp,...

Many of these problems can be expressed in a blocking-neutral fashion or -given enough thought- could support both async and sync, allowing wide reusability.

In short: is it wise to introduce an abstraction on top of I/O, forcing basically every library that uses it (directly or indirectly) to use it as well?

UPDATE

At the core are the ReadableByteContainer and WritableByteContainer that -to the discerning eye- will look like a cross between stream I/O and channel I/O.

```<code>public interface ReadableByteContainer extends Closeable {
    public int read(byte [] bytes);
    public int read(byte [] bytes, int offset, int length);
}

public interface WritableByteContainer extends Closeable {
    public int write(byte [] bytes);
    public int write(byte [] bytes, int offset, int length);
    public void flush();
}
</code>```

One of the utils built on it is the "Transcoder" api:

```<code>public interface ByteTranscoder {
    public void transcode(ReadableByteContainer in, WritableByteContainer out);
    public void flush(WritableByteContainer out);
}
</code>```

which allows you to do something like:

```<code>ByteContainer container = IOUtils.newByteContainer();
container = IOUtils.wrap(
    container,
    TranscoderUtils.wrapOutput(container, new Base64Encoder())
);
container.write("test".getBytes());
System.out.println(new String(IOUtils.toBytes(container)));
</code>```

This code will output the base64 encoded bytes of "test".

The thing is, the Base64Encoder is capable of encoding the data in an asynchronous manner, it won't block if the output container reports that no data was written nor will it block if the input container reports that no data is available. You can continue the transcoding by calling "transcode()" again.

This works both in a jboss netty context where you get the content piece by asynchronous piece and in the streaming world where everything blocks until it can read/write.

答:
I think you're abstracting the wrong thing. Your library does not need to actually handle the I/O. You already have libraries in hand that do synchronous or asynchronous I/O. Rewriting those libraries and merging them together is not abstraction. In fact, it might be a violation of the Single Responsibility Principle.

Why not simply write a library that provides a uniform interface to those libraries you mentioned? Underneath the covers, it is simply calling one library or the other. That's true abstraction.

Just my two cents.


问:
How to ideally calculate profit margin with zero sales
How do you handle the following scenario without null?

You have this problem (In Java):

```<code>BigDecimal sales = ...;
BigDecimal cost = ...;
BigDecimal profit = sales.subtract(cost);
// Profit Margin = profit / sales
BigDecimal profitMargin = profit.divide(sales, 20, RoundingMode.HALF_UP);
</code>```

Because sales is sometimes zero, we turn the last line into:

```<code>BigDecimal profitMargin = sales.compareTo(BigDecimal.ZERO) == 0 ? null : profit.divide(sales, 20, RoundingMode.HALF_UP);
</code>```

In which case if profitMargin == null, then we know what that means. If you make profitMargin = 0, that isn't really correct, nor is infinity a good value either. It seems best that it would remain undefined. Yet, it is an "unexploded bomb." So, what's the best way to handle this?

This questions as originally asked on Stack Overflow, and also referred me to the question Are null references really a bad thing?

答:
If sales are zero, profit margin is zero.

Zero is a perfectly good result to substitute for the undefined result of a divide by zero calculation in many cases, and it avoids the use of null unless you specifically want to know about the zero sales case.


问:
Is spying on tested class bad practice?
I am working on a project where class internal calls are usual but the results are many times simple values. Example (not real code):

```<code>public boolean findError(Set<Thing1> set1, Set<Thing2> set2) {
  if (!checkFirstCondition(set1, set2)) {
    return false;
  }
  if (!checkSecondCondition(set1, set2)) {
    return false;
  }
  return true;
}
</code>```

Writing unit tests for this type of code is really hard as I just want to test the condition system and not the implementation of the actual conditions. (I do that in separate tests.) In fact it would be better if I passed functions that implement the conditions and in tests I simply provide some mock. The issue with this approach is the noisiness: we use generics a lot.

A working solution; however, is to make the tested object a spy and mock out the calls to the internal functions.

```<code>systemUnderTest = Mockito.spy(systemUnderTest);
doReturn(true).when(systemUnderTest).checkFirstCondition(....);
</code>```

The concern here is that the SUT's implementation is effectively changed and it may be problematic to keep the tests in sync with the implementation. Is this true? Is there best practice to avoid this havoc of internal method calls?

Note that we are talking about parts of an algorithm, so breaking it out to several classes may not be a desired decision.

答:
Firstly, I'm wondering what is difficult to test about the example function you wrote? As far as I can see, you can simply pass in various inputs and check to make sure the correct boolean value is returned. What am I missing?

As for spies, the kind of so-called "white-box" testing that uses spies and mocks is orders of magnitude more work to write, not only because there is so much more test-code to write, but any time the implementation is changed, you must also change the tests (even if the interface remains the same). And this kind of testing is also less reliable than black-box testing, because you need to ensure that all that extra test code is correct, and while you can trust that black-box unit tests will fail if they don't match the interface, you can't trust that about code overusing mocks because sometimes the test doesn't even test much real code - only mocks. If the mocks are incorrect, the likelyhood is that your tests will succeed, but your code is still broken.

Anyone that has experience with white-box testing can tell you they're a pain in the ass to write and maintain. Coupled with the fact that they're less reliable, white-box testing is simply far inferior in most cases.

Title: Is spying on tested class bad practice?


问:
How do languages with Maybe types instead of nulls handle edge conditions?
Eric Lippert made a very interesting point in his discussion of why C# uses a null rather than a Maybe<T> type:

Consistency of the type system is important; can we always know that a non-nullable reference is never under any circumstances observed to be invalid? What about in the constructor of an object with a non-nullable field of reference type? What about in the finalizer of such an object, where the object is finalized because the code that was supposed to fill in the reference threw an exception? A type system that lies to you about its guarantees is dangerous.

That was a bit of an eye-opener.  The concepts involved interest me, and I've done some playing around with compilers and type systems, but I never thought about that scenario.  How do languages that have a Maybe type instead of a null handle edge cases such as initialization and error recovery, in which a supposedly guaranteed non-null reference is not, in fact, in a valid state?

答:
Here's how Haskell does it:
(not exactly a counter to Lippert's statements since Haskell is not an Object-Oriented language).

WARNING: long winded-answer from a serious Haskell fan-person ahead.

TL;DR

This example illustrates exactly how different Haskell is from C#. Instead of delegating the logistics of structure construction to a constructor, it must be handled in the surrounding code. There is no way for a null (Or Nothing in Haskell) value value to crop up where we are expecting a non-null value because null values can only occur within special wrapper types called Maybe which are not interchangeable with/directly convertible to regular, non-nullable types. In order to use an value made nullable by wrapping it in a Maybe, we must first extract the value using pattern matching, which forces us to divert control flow into a branch where we know for certain that we have a non-null value.

Therefore:

can we always know that a non-nullable reference is never under any
circumstances observed to be invalid?

Yes.  Int and Maybe Int are two completely separate types. Finding Nothing in a plain Int would be comparable to finding the string "fish" in an Int32.

What about in the constructor of
an object with a non-nullable field of reference type?

Not an issue: value constructors in Haskell can't do anything but take the values they're given and put them together. All initialization logic takes place before the constructor is called.

What about in
the finalizer of such an object, where the object is finalized because
the code that was supposed to fill in the reference threw an
exception?

There are no finalizers in Haskell, so I can't really address this. My first response still stands, however.

Full Answer:

Haskell has no null and uses the Maybe data type to represent nullables. Maybe is an algabraic data type defined like this:

```<code>data Maybe a = Just a | Nothing
</code>```

For those of you unfamiliar with Haskell, read this as "A Maybe is either a Nothing or a Just a". Specifically:

Maybe is the type constructor: it can be thought of (incorrectly) as a generic class (where a is the type variable). The C# analogy is class Maybe{}.

Just is a value constructor: it is a function that takes one argument of type a and returns a value of type Maybe a that contains the value. So the code x = Just 17 is analogous to int? x = 17;.

Nothing is another value constructor, but it takes no arguments and the Maybe returned has no value other than "Nothing". x = Nothing is analogous to int? x = null; (assuming we constrained our a in Haskell to be Int, which can be done by writing x = Nothing :: Maybe Int).

Now that the basics of the Maybe type are out of the way, how does Haskell avoid the issues discussed in the OP's question?

Well, Haskell is really different from most of the languages discussed so far, so I'll begin by explaining a few basic language principles.

First off, in Haskell, everything is immutable. Everything. Names refer to values, not to memory locations where values can be stored (this alone is an enormous source of bug elimination). Unlike in C#, where variable declaration and assignment are two separate operations, in Haskell values are created by defining their value (eg x = 15, y = "quux", z = Nothing), which can never change. Therefore, code like:

```<code>ReferenceType x;
</code>```

Is not possible in Haskell. There are no problems with initializing values to null because everything must be explicitly initialized to a value in order for it to exist.

Secondarily, Haskell is not an object-oriented language: it is a purely functional language, so there are no objects in the strict sense of the word. Instead, there are simply functions (value constructors) that take their arguments and return an amalgamated structure.

Next, there is absolutely no imperative style code. By this, I mean that most languages follow a pattern something like this:

```<code>do thing 1
add thing 2 to thing 3
do thing 4
if thing 5:
    do thing 6
return thing 7
</code>```

Program behavior is expressed as a series of instructions. In Object-Oriented languages, class and function declarations also play a huge role in program flow, but is essence, the "meat" of a program's execution takes the form of a series of instructions to be executed.

In Haskell, this is not possible. Instead, program flow is dictated entirely by chaining functions. Even the imperative-looking do-notation is just syntactic sugar for passing anonymous functions to the >>= operator. All functions take the form of:

```<code><optional explicit type signature>
functionName arg1 arg2 ... argn = body-expression
</code>```

Where body-expression can be anything that evaluates to a value. Obviously there are more syntax features available but the main point is the complete absence of sequences of statements.

Lastly, and probably most importantly, Haskell's type system is incredibly strict.  If I had to summarize the central design philosophy of Haskell's type system, I would say: "Make as many things as possible go wrong at compile time so as little as possible goes wrong at runtime." There are no implicit conversions whatsoever (want to promote an Int to a Double? Use the fromIntegral function). The only to possibly have an invalid value occur at runtime is to use Prelude.undefined (which apparently just has to be there and is impossible to remove).

With all of this in mind, let's look at amon's "broken" example and try to re-express this code in Haskell. First, the data declaration (using record syntax for named fields):

```<code>data NotSoBroken = NotSoBroken {foo :: Foo, bar :: Bar }
</code>```

(foo and bar are really accessor functions to anonymous fields here instead of actual fields, but we can ignore this detail).

The NotSoBroken value constructor is incapable of taking any action other than taking a Foo and a Bar (which are not nullable) and making a NotSoBroken out of them. There is no place to put imperative code or even manually assign the fields. All initialization logic must take place elsewhere, most likely in a dedicated factory function.

In the example, the construction of Broken always fails. There is no way to break the NotSoBroken value constructor in a similar fashion (there is simply nowhere to write the code), but we can create a factory function that is similarly defective.

```<code>makeNotSoBroken :: Foo -> Bar -> Maybe NotSoBroken
makeNotSoBroken foo bar = Nothing
</code>```

(the first line is a type signature declaration: makeNotSoBroken takes a Foo and a Bar as arguments and produces a Maybe NotSoBroken).

The return type must be Maybe NotSoBroken and not simply NotSoBroken because we told it to evaluate to Nothing, which is a value constructor for Maybe. The types simply wouldn't line up if we wrote anything different.

Aside from being absolutely pointless, this function doesn't even fulfill its real purpose, as we'll we see when we try to use it. Let's create a function called useNotSoBroken which expects a NotSoBroken as an argument:

```<code>useNotSoBroken :: NotSoBroken -> Whatever
</code>```

(useNotSoBroken accepts a NotSoBroken as an argument and produces a Whatever).

And use it like so:

```<code>useNotSoBroken (makeNotSoBroken)
</code>```

In most language, this sort of behavior might cause a null pointer exception. In Haskell, the types don't match up: makeNotSoBroken returns a Maybe NotSoBroken, but useNotSoBroken expects a NotSoBroken. These types are not interchangeable, and the code fails to compile.

To get around this, we can use a case statement to branch based on the structure of the Maybe value (using a feature called pattern matching):

```<code>case makeNotSoBroken of
    Nothing  -> --handle situation here
    (Just x) -> useNotSoBroken x
</code>```

Obviously this snippet needs to placed inside some context to actually compile, but it demonstrates the basics of how Haskell handles nullables. Here is a step-by-step explanation of the above code:

First, makeNotSoBroken is evaluated, which is guaranteed to produce a value of type Maybe NotSoBroken.

The case statement inspects the structure of this value.

If the value is Nothing, the "handle situation here" code is evaluated.

If the value instead matches against a Just value, the other branch is executed. Note how the matching clause simultaneously identifies the value as a Just construction and binds its internal NotSoBroken field to a name (in this case, x). x can then be used like the normal NotSoBroken value that is.

So, pattern matching provides a powerful facility for enforcing type safety, since the structure of the object is inseparably tied to the branching of control.

I hope this was a comprehensible explanation. If it doesn't make sense, jump into Learn You A Haskell For Great Good!, one of the best online language tutorials I've ever read. Hopefully you will see the same beauty in this language that I do.

Body:
Here's how Haskell does it:
(not exactly a counter to Lippert's statements since Haskell is not an Object-Oriented language).

WARNING: long winded-answer from a serious Haskell fan-person ahead.

TL;DR

This example illustrates exactly how different Haskell is from C#. Instead of delegating the logistics of structure construction to a constructor, it must be handled in the surrounding code. There is no way for a null (Or Nothing in Haskell) value value to crop up where we are expecting a non-null value because null values can only occur within special wrapper types called Maybe which are not interchangeable with/directly convertible to regular, non-nullable types. In order to use an value made nullable by wrapping it in a Maybe, we must first extract the value using pattern matching, which forces us to divert control flow into a branch where we know for certain that we have a non-null value.

Therefore:

can we always know that a non-nullable reference is never under any
circumstances observed to be invalid?

Yes.  Int and Maybe Int are two completely separate types. Finding Nothing in a plain Int would be comparable to finding the string "fish" in an Int32.

What about in the constructor of
an object with a non-nullable field of reference type?

Not an issue: value constructors in Haskell can't do anything but take the values they're given and put them together. All initialization logic takes place before the constructor is called.

What about in
the finalizer of such an object, where the object is finalized because
the code that was supposed to fill in the reference threw an
exception?

There are no finalizers in Haskell, so I can't really address this. My first response still stands, however.

Full Answer:

Haskell has no null and uses the Maybe data type to represent nullables. Maybe is an algabraic data type defined like this:

data Maybe a = Just a | Nothing

For those of you unfamiliar with Haskell, read this as "A Maybe is either a Nothing or a Just a". Specifically:

Maybe is the type constructor: it can be thought of (incorrectly) as a generic class (where a is the type variable). The C# analogy is class Maybe<a>{}.

Just is a value constructor: it is a function that takes one argument of type a and returns a value of type Maybe a that contains the value. So the code x = Just 17 is analogous to int? x = 17;.

Nothing is another value constructor, but it takes no arguments and the Maybe returned has no value other than "Nothing". x = Nothing is analogous to int? x = null; (assuming we constrained our a in Haskell to be Int, which can be done by writing x = Nothing :: Maybe Int).

Now that the basics of the Maybe type are out of the way, how does Haskell avoid the issues discussed in the OP's question?

Well, Haskell is really different from most of the languages discussed so far, so I'll begin by explaining a few basic language principles.

First off, in Haskell, everything is immutable. Everything. Names refer to values, not to memory locations where values can be stored (this alone is an enormous source of bug elimination). Unlike in C#, where variable declaration and assignment are two separate operations, in Haskell values are created by defining their value (eg x = 15, y = "quux", z = Nothing), which can never change. Therefore, code like:

ReferenceType x;

Is not possible in Haskell. There are no problems with initializing values to null because everything must be explicitly initialized to a value in order for it to exist.

Secondarily, Haskell is not an object-oriented language: it is a purely functional language, so there are no objects in the strict sense of the word. Instead, there are simply functions (value constructors) that take their arguments and return an amalgamated structure.

Next, there is absolutely no imperative style code. By this, I mean that most languages follow a pattern something like this:

do thing 1
add thing 2 to thing 3
do thing 4
if thing 5:
    do thing 6
return thing 7

Program behavior is expressed as a series of instructions. In Object-Oriented languages, class and function declarations also play a huge role in program flow, but is essence, the "meat" of a program's execution takes the form of a series of instructions to be executed.

In Haskell, this is not possible. Instead, program flow is dictated entirely by chaining functions. Even the imperative-looking do-notation is just syntactic sugar for passing anonymous functions to the >>= operator. All functions take the form of:

<optional explicit type signature>
functionName arg1 arg2 ... argn = body-expression

Where body-expression can be anything that evaluates to a value. Obviously there are more syntax features available but the main point is the complete absence of sequences of statements.

Lastly, and probably most importantly, Haskell's type system is incredibly strict.  If I had to summarize the central design philosophy of Haskell's type system, I would say: "Make as many things as possible go wrong at compile time so as little as possible goes wrong at runtime." There are no implicit conversions whatsoever (want to promote an Int to a Double? Use the fromIntegral function). The only to possibly have an invalid value occur at runtime is to use Prelude.undefined (which apparently just has to be there and is impossible to remove).

With all of this in mind, let's look at amon's "broken" example and try to re-express this code in Haskell. First, the data declaration (using record syntax for named fields):

data NotSoBroken = NotSoBroken {foo :: Foo, bar :: Bar }

(foo and bar are really accessor functions to anonymous fields here instead of actual fields, but we can ignore this detail).

The NotSoBroken value constructor is incapable of taking any action other than taking a Foo and a Bar (which are not nullable) and making a NotSoBroken out of them. There is no place to put imperative code or even manually assign the fields. All initialization logic must take place elsewhere, most likely in a dedicated factory function.

In the example, the construction of Broken always fails. There is no way to break the NotSoBroken value constructor in a similar fashion (there is simply nowhere to write the code), but we can create a factory function that is similarly defective.

makeNotSoBroken :: Foo -> Bar -> Maybe NotSoBroken
makeNotSoBroken foo bar = Nothing

(the first line is a type signature declaration: makeNotSoBroken takes a Foo and a Bar as arguments and produces a Maybe NotSoBroken).

The return type must be Maybe NotSoBroken and not simply NotSoBroken because we told it to evaluate to Nothing, which is a value constructor for Maybe. The types simply wouldn't line up if we wrote anything different.

Aside from being absolutely pointless, this function doesn't even fulfill its real purpose, as we'll we see when we try to use it. Let's create a function called useNotSoBroken which expects a NotSoBroken as an argument:

useNotSoBroken :: NotSoBroken -> Whatever

(useNotSoBroken accepts a NotSoBroken as an argument and produces a Whatever).

And use it like so:

useNotSoBroken (makeNotSoBroken)

In most language, this sort of behavior might cause a null pointer exception. In Haskell, the types don't match up: makeNotSoBroken returns a Maybe NotSoBroken, but useNotSoBroken expects a NotSoBroken. These types are not interchangeable, and the code fails to compile.

To get around this, we can use a case statement to branch based on the structure of the Maybe value (using a feature called pattern matching):

case makeNotSoBroken of
    Nothing  -> --handle situation here
    (Just x) -> useNotSoBroken x

Obviously this snippet needs to placed inside some context to actually compile, but it demonstrates the basics of how Haskell handles nullables. Here is a step-by-step explanation of the above code:

First, makeNotSoBroken is evaluated, which is guaranteed to produce a value of type Maybe NotSoBroken.

The case statement inspects the structure of this value.

If the value is Nothing, the "handle situation here" code is evaluated.

If the value instead matches against a Just value, the other branch is executed. Note how the matching clause simultaneously identifies the value as a Just construction and binds its internal NotSoBroken field to a name (in this case, x). x can then be used like the normal NotSoBroken value that is.

So, pattern matching provides a powerful facility for enforcing type safety, since the structure of the object is inseparably tied to the branching of control.

I hope this was a comprehensible explanation. If it doesn't make sense, jump into Learn You A Haskell For Great Good!, one of the best online language tutorials I've ever read. Hopefully you will see the same beauty in this language that I do.


问:
Is the GPL dangerous to the organisation in terms of exposure of its intellectual property?
GNU General Public License is a ‘Viral License”. If an organisation is using Linux and MySQL which come under this license, is it  dangerous to the organisation in terms of exposure of its intellectual property? As this license will demand the  software that is linked to or that incorporates a GPL program to also be made available in source form under the same license when it is “distributed.”</p>

答:
The answer is no. The GPL is a licence, not a contract, so it has no enforcement terms. Your organisation's intellectual property is not at risk, at least not directly.

But is that the end of it? Unfortunately no. If you breach the terms of a GPL licence by distributing something containing it ('merged with it') and fail to distribute the source code you may have infringed the licence. The consequence of that is you may have lost any rights to use the software. if you don't do what the GPL says, you can't use the GPL.

Now you are in breach of copyright law, which can be serious. The holder of the copyright in the software (whoever that may be) can sue you for using their software without their permission.

So the final situation is that your organisation could be at risk of court action and substantial penalties, which it might only be able to avoid by complying with the GPL, which means distributing source code. To that extent you could say there is a risk, although quite indirect.


答:
A constructor is a function that you call when the object does not yet exist, so it could not be a member function. It could be static.

A constructor actually gets called with a this pointer, after the memory has been allocated but before it has been completely initialised. As a consequence a constructor has a number of privileged features.

If you had a pointer to a constructor it would either have to be a static pointer, something like a factory function, or a special pointer to something that would be called immediately after memory allocation. It could not be an ordinary member function and still work as a constructor.

The only useful purpose that comes to mind is a special kind of pointer that could be passed to the new operator to allow it to indirect on which constructor to use. I guess that could be handy, but it would require significant new syntax and presumably the answer is: they thought about it and it wasn't worth the effort.

If you just want to refactor out common initialisation code then an ordinary memory function is usually a sufficient answer, and you can get a pointer to one of those.

Title: Why doesn't C++ allow you to take the address of a constructor?

Body:
Is there a specific reason that this would break the language conceptually or a specific reason that this is technically infeasible in some cases?

The usage would be with new operator.

Edit: I'm going to give up hope on getting my "new operator" and "operator new" straight and be direct.

The point of the question is: why are constructors special? Keep in mind of course that language specifications tell us what is legal, but not necessarily moral. What is legal is typically informed by what is logically consistent with the rest of the language, what is simple and concise, and what is feasible for compilers to implement. The possible rationale of the standards committee in weighing these factors are deliberate and interesting -- hence the question.


问:
Understanding Arithmetic In C
I have an embarrassingly simple question, but I need to make sure I understand this correctly. I have a *.c file with the following line:

```<code>    CSRConstant = 2*macroParticleCharge*particleCharge/pow(3*rho0*rho0, 1./3.)/(4*PI*epsilon_o*particleMass*sqr(c_mks));
</code>```

Is this interpreted as:

答:
The answer is almost as embarrassingly simple. No, absolutely not, and anything you do to change what you have written will most likely be wrong until you have read and understood What Every Computer Scientist Should Know About Floating-Point Arithmetic

I only understand about 1/4 of that paper, but I understand enough of it to know that my chances of getting floating point correct are low. Fortunately in my line of work, like many programmers, floating point is either easily avoided or quite simple so when I do have to go there I can spend effort on getting it right.

Essentially the paper describes how floating point on computers is achieved, and what kinds of errors can occur that can generate incorrect results. At first glance, your implementation of the formula will likely exhibit most of the errors described in the link.

Title: Understanding Arithmetic In C


答:
@Robert answer requires that you can use a profit margin of 0 if sales are 0, or have the ability at later times to access sales to test if they are 0 before using profit margin.  If this is the case, then his answer is acceptable.

If however you need to know if the profit margin is 'NaN' at some future processing stage, another approach would be to extend BigDecimal so the fact that sales was 0 when trying to calculate it is preserved.

It would be my preferred approach to extend BigDecimal and create a new class for Profit Margin regardless, as the improved type correctness makes programs easier to understand and maintain.

Title: How to ideally calculate profit margin with zero sales

Body:
How do you handle the following scenario without null?

You have this problem (In Java):

```<code>BigDecimal sales = ...;
BigDecimal cost = ...;
BigDecimal profit = sales.subtract(cost);
// Profit Margin = profit / sales
BigDecimal profitMargin = profit.divide(sales, 20, RoundingMode.HALF_UP);
</code>```

Because sales is sometimes zero, we turn the last line into:

```<code>BigDecimal profitMargin = sales.compareTo(BigDecimal.ZERO) == 0 ? null : profit.divide(sales, 20, RoundingMode.HALF_UP);
</code>```

In which case if profitMargin == null, then we know what that means. If you make profitMargin = 0, that isn't really correct, nor is infinity a good value either. It seems best that it would remain undefined. Yet, it is an "unexploded bomb." So, what's the best way to handle this?

This questions as originally asked on Stack Overflow, and also referred me to the question Are null references really a bad thing?


答:
My question is: how do you handle the following scenario without null?

The way you would handle it on a balance sheet (i.e. it's 0).

Maths is a bad example for nulls. Maths has worked without nulls for centuries, and there is never a balance sheet or a general ledger or a kid's maths homework book that says "null".

Programming had the problem of what to assign to a variable for which memory was not yet allocated, and that's where null was born. Perhaps you need to find another example for null (and you'll find many), but definitely not maths :-)