问:
Overloading Methods With Different Behavior - Style
I have a style question about overloading methods/constructors. I have a constructor which
does something very simple, and then calls a method with some side effects. Sometimes however I don't want the side effects so I made a separate overloaded constructor. I show two versions here. Version 1 is simple: if I pass any bool then TrickyFunction won't be called. But maybe that's confusing, because the value of no_tricks does not affect the behavior (only that no_tricks exists). Version 2 actually does process no_tricks and makes a decision to run TrickyFunction based on that.

Which version, or another version, is more stylistically "correct?"

```<code>public foo MyFunction(string a)
{
    variable = a
    TrickyFunction(a)
}

#Version 1
public foo MyFunction(string a, bool no_tricks)
{
    variable = a
}

#Version 2
public foo MyFunction(string a, bool no_tricks)
{
    variable = a
    if (notricks == true)
    {
        TrickyFunction(a)
    }
}
</code>```

答:
Version #2 is FAR preferable, although the overall design is often considered a code smell.

Note that more recent C# dialects allow for optional parameters, so you could combine your base and overload.

```<code>class foo {
  public foo(string a, bool no_tricks = false) {
    variable = a;
    if(no_tricks == false) {
      TrickyFunction(a);
    }
  }
}
</code>```

(And, of course, note that passing a false value to override default is kinda counter-intuitive by itself, especially when your logical value doens't match the name of the variable, as in your text.)

Body:
Version #2 is FAR preferable, although the overall design is often considered a code smell.

Note that more recent C# dialects allow for optional parameters, so you could combine your base and overload.

class foo {
  public foo(string a, bool no_tricks = false) {
    variable = a;
    if(no_tricks == false) {
      TrickyFunction(a);
    }
  }
}

(And, of course, note that passing a false value to override default is kinda counter-intuitive by itself, especially when your logical value doens't match the name of the variable, as in your text.)


答:
Version 2, kinda.

I would only have one constructor, but the second parameter doExtraWork is optional, and defaulted to true. This follows the general guideline that boolean true should represent doing things rather than not doing things. And this approach would simplify your code. If optional params are forbidden in your codebase, then just have the "little" constructor call the other.

Though I'd look to remove tricky stuff from any constructor - do just enough to initialize your invariants.

ContentLicense: CC BY-SA 3.0

Title: Overloading Methods With Different Behavior - Style

Body:
I have a style question about overloading methods/constructors. I have a constructor which
does something very simple, and then calls a method with some side effects. Sometimes however I don't want the side effects so I made a separate overloaded constructor. I show two versions here. Version 1 is simple: if I pass any bool then TrickyFunction won't be called. But maybe that's confusing, because the value of no_tricks does not affect the behavior (only that no_tricks exists). Version 2 actually does process no_tricks and makes a decision to run TrickyFunction based on that.

Which version, or another version, is more stylistically "correct?"

```<code>public foo MyFunction(string a)
{
    variable = a
    TrickyFunction(a)
}

#Version 1
public foo MyFunction(string a, bool no_tricks)
{
    variable = a
}

#Version 2
public foo MyFunction(string a, bool no_tricks)
{
    variable = a
    if (notricks == true)
    {
        TrickyFunction(a)
    }
}
</code>```


问:
Why are threads called threads?
I understand that a process a unit of resource ownership and executable instructions. Threads allow a process to share its resources with multiple executions, and it's easier for an OS to schedule threads because of all the overhead associated with whole processes.

But why the name thread? Does it have some reference to string or the interleaving of execution? Even so, this isn't an intuitive term in my opinion.

答:
It is difficult to untangle (pun fully intended) the source of the term "Thread" because various things muddy the waters.

The usage of thread in the forum or email sense almost certainly stems from the phrase "thread of conversation" which according to this dates back as far as 1593.

Things seem to be less clear for the meaning of thread you are asking about though since according to this link, threads as we know them weren't actually called "threads" until the 70s or possibly early 80s despite the implementation of a shared memory process actually predating what we think of as heavyweight processes today. Given that a related form of shared memory multiprocessing is called a "fiber" I strongly suspect that the word "thread" is suppose be reminiscent of weaving cloth or some other textile-related analogy.

Title: Why are threads called threads?


问:
Is there already a "Binder" data-structure?
I was thinking of a data structure that I cannot describe better than with the word "book", or more exactly "binder".
I was wondering if this had already been implemented in libraries like Boost or others.

Principle

It's a data structure that allows constant-time random access and amortized constant time insertion/deletion (as long as the sequence of those are performed on indexes not too far away from each other).

It consists of two stacks "left" and "right" representing the state of a binder that would be open on a particular page. Inserting and deleting elements near this page is pretty fast since it consists in pushing/popping the pages to/from the left stack, and flipping some pages if necessary. Of course in the worst case one would have to flip from the first page to the last page (fill one stack with the other), for example if the user inserts something at the beginning and then something at the end.

Here is a very rudimentary implementation in C++:

#include <iostream>
#include <vector>

using namespace std;

template<class T>
class Book {

    vector<T> left, right;

public:

    inline size_t size()
    {
        return left.size() + right.size();
    }

    void push(T t)
    {
        insert(size(),t);
    }

    T& get(size_t i)
    {
        if (i < left.size())
             return left[i];
        else return right[right.size()-i+left.size()-1];
    }

    void insert(size_t i, T t)
    {
        reposition(i-1);
        left.push_back(t);
    }

    void remove(size_t i)
    {
        reposition(i);
        left.pop_back();
    }

protected:

    void reposition(size_t i)
        // puts the element at position i on the top of the left stack
    {
        while (i < left.size()-1)
        {
            right.push_back(left.back());
            left.pop_back();
        }
        while (right.size() >= size()-i)
        {
            left.push_back(right.back());
            right.pop_back();
        }
    }

};

int main()
{
    Book<int> b;
    for (int i = 0; i < 15; i++)
        b.push(i);

    b.insert(5,42);
    b.remove(10);

    int i = 0;
    while (i < b.size())
    {
        if (b.get(i)%2 != 0)
             b.remove(i);
        else i++;
    }

    for (int i = 0; i < b.size(); i++)
    {
        cout << b.get(i) << " ";
    }
    cout << endl;
    return 0;
}
```

Note: A possible nice optimizations would be to have the two stacks in reverse order, to allow a memcpy of the whole portion to be moved from on stack to the other instead of moving elements one by one (memcpy is usually much faster).

Use

So a good use case of this DS would be an algorithm that runs through a sequence of elements and can, for each index, add new elements or remove old elements near this index.

A particular case of this is filtering an array of elements. All you need to do is to iterate over all the indexes and simply call binder.remove(i) if the element at index i is to be removed.

An efficient (and optimal) way to do it, given an array of elements, would usually be to allocate another array of the same size, and copy only the elements that we want to save. It is easy to see that this does the same amount of operations than our Binder implementation (if it starts on the first page), the main difference being that Binder allows a simpler algorithm hiding the dirty details of implementation. (And we don't end up with a different object.)

Things get even messier to implement when we need to handle deletion of close elements or a mix of deletion and addition, while with the Binder DS it is all encapsulated and the algorithm stays very simple.

So the Binder DS can be seen as an array (or "vector" in the sense of C++) which allows efficiently working on its content by including a working buffer, so one never has to allocate extra space by hand (so it helps reduce dynamic memory allocations). It makes the whole mutation processes transparent.

Conclusion

I haven't time-tested it against more conventional algorithms, but I expect it would be a little slower in element access than a plain vector because of the higher complexity of having two buffers instead of one.

Do you think this is a good idea of a data structure, and it would prove efficient? Has it already been done, and in which library? Do you have a better alternative to propose?

答:
It's basically a list zipper, a well-known functional data structure. In the form described on Wikipedia, it is a persistent data structure, which means that after you do an update (delete or insert), the old version of the data structure is still accessible. By using arrays instead of singly linked lists to implement the stacks, you give up persistency and instead gain the ability for random access, which is actually a cool idea.

Since insert and delete are only efficient if they occur near the current position, I would suggest the following modification, inspired by the typical usage pattern of a zipper in functional programming: Instead of giving the position as an argument to insert/delete, I'd introduce the concept of a focus. The focus of your data structure is the index that is currently in the middle of your two stacks. It is the place where you can efficiently insert and delete. So I'd provide interfaces to read the focus and methods next() and previous() to move it. You can only insert and delete at the current focus, so you can't make the mistake of introducing a costly operation into your algorithm by accident.


问:
How do I explain a ruby method with a real-world analogy?
I am looking for a good analogy to help the concept of a method in ruby stick in my head. When I truly understand a concept, an image flashes in my mind that relates something physical to the abstract concepts I am trying to learn.

For example, someone explained the concept of a variable to me in the following way:

A variable is like a box you can put things in. The name of the variable is like taking a sharpie and writing a word, like "forks" on the side of the box. Picking a good name is important. You can stick anything in the box, but if you write 'forks' on the side of the box, you would expect forks to be in the box. You can put anything in the box, then carry it around to various people, and tell them "there are forks in this box." When they need a fork, they go to the fork box and get out a fork.

That's the sort of physical, image-based, concrete analogy I am looking for for a ruby method.

Right now most definitions I have found are useless to me. For example, at turtorialspoint, the first result for the google search 'what is a ruby method,' has the folowing definition.

Ruby methods are very similar to functions in any other programming language. Ruby methods are used to bundle one or more repeatable statements into a single unit.

Let me give you an example of why this definitions is useless to me. I'm going to replace every word and concept in this definition that I don't understand with the word 'blah.'

Ruby blah are very similar to blah in any other programming language. Ruby blah are used to blah one or more blah blah into a single blah.

In summary, can I get a good, physical analogy for the concept of a method in ruby?

答:
One typical way to explain methods, interfaces, and polymorphism is to take several similar real-world objects as an example.

For instance, take a hen, a duck, and a turkey.

They all implement an interface for moving over a solid surface that consists of method walk(direction). This method is implemented slightly differently in each (you can tell one gait from another) but consistently.

They all implement an interface for producing sounds, that consists of method that we'd call quack(). Again, it has distinctly different implementations in all three.

Unlike two others, the duck implements another, aquatic interface, by having methods swim(depth) and dive. An attempt to call either of these on the hen or the turkey will end up in an infuriated and loud error message, or even in an abnormal termination of them.

One more important interface is aerial, consisting of take_off, fly, and land methods.  Support of this interface is uneven. While the duck and the turkey reasonably implement all three, the hen has mere stub implementations of take_off and land and lacks an implementation of fly. The latter is a regression in implementation, because hen's ancestors have a well-working implementation. But since nobody seems to ever invoke hen.fly(), it is not even planned to be fixed. On the other hand, duck has an enhanced implementation of land(surface) that accepts both land and water objects as the argument.

In languages with a static class hierarchy a bird should be formally certified as a duck to function as one. Ruby implements duck typing, allowing a bird that quacks like a duck and walks like a duck to be accepted as a duck.

Note that the above only applies to situations where locomotion and sound production is involved. In other contexts, e.g. roasting, a bird that does not implement correct cooking and tasting interfaces could make a subsequent operation of eating fail unexpectedly. Ruby lacks built-in means to check for this beforehand, but has enough flexibility to implement such a check manually when required, at an additional cost.

It's important to notice that all methods has an implicit parameter, self. There's no way to quack abstractly, one needs an instance of a e.g. duck; duck's self defines concrete details of method invocation. The whole point of objects (that is, of self) is to hold some state. For instance, duck's hunger level is a part of the duck's state. The implementation of quack consults the hunger value of self, and increases volume accordingly.

Importance of internal state can be seen on methods like get_mass. Various other methods, like peck, drink, or excrete change the summary mass. get_mass is shared by all objects in the universe. It is likely to have only one canonical implementation, inherited by all objects, including our three birds. Different implementations of quack and walk by different birds is an example of implementation polymorphism.

Hope this helps :)


答: I read somewhere the analogy of threads in programming.Think CPU as a sewing needle, and the thread as the actual string. Now, if you have multiple sewing needles but just a one thread. Don't you think, it will be quite inefficient. The other CPU/sewing needle will be waiting for the thread to be available. However, if we have multiple threads, then the job can be accomplished in a short time.</p>

Title: Why are threads called threads?

Body:
I understand that a process a unit of resource ownership and executable instructions. Threads allow a process to share its resources with multiple executions, and it's easier for an OS to schedule threads because of all the overhead associated with whole processes.

But why the name thread? Does it have some reference to string or the interleaving of execution? Even so, this isn't an intuitive term in my opinion.


问:
How should I charge for programming things which take two minutes to fix?
I am really confused with this. I believe that the more I am getting experience, the more I am becoming an expert at finding mistakes and fixing them quickly.

Now my boss got website from a programmer who does very very bad coding.
Now he sends the list of problems to fix.

Suppose it's the stylesheet problem, and the old guy does not know how to fix it, but due to my experience I know straightaway what the problem is, and I can fix it in two minutes and many similar problems like that.

But after fixing all that I realise that I fixed all problems in 15 minutes which other guy was not able to solve.

I get 25$ per hour, so I feel very bad charging 6$ for that list of things which took many years of experience to learn.

Is it OK to charge 6$ or should there be some way to charge things?

答: Others have already pointed out that the time to read and understand the bug list should be included as billable hours, so that it is very unlikely you really only spent 15m on it. But what I expected to see mentioned and was not: if you really are that good, why are you settling for only 25$ an hour? That is the rate I was getting many years of inflation ago, when I was not very experienced. Do some searches here or in Ask.com http://www.oncontracting.com/, dice.com or even Google to see what rates people of your experience usually get. You may find it is a lot more than just 25$, even when going through an agency.</p>


问:
Best practice or design patterns for retrieval of data for reporting and dashboards in a domain-rich application
First, I want to say this seems to be a neglected question/area, so if this question needs improvement, help me make this a great question that can benefit others! I'm looking for advice and help from people who have implemented solutions that solve this problem, not just ideas to try.

In my experience, there are two sides of an application - the "task" side, which is largely domain driven and is where the users interact richly with the domain model (the "engine" of the application) and the reporting side, where users get data based on what happens on the task side.

On the task side, it's clear that an application with a rich domain model should have business logic in the domain model and the database should be used mostly for persistence. Separation of concerns, every book is written about it, we know what to do, awesome.

What about the reporting side? Are data warehouses acceptable, or are they bad design because they incorporate business logic in the database and the very data itself? In order to aggregate the data from the database into data warehouse data, you must have applied business logic and rules to the data, and that logic and rules didn't come from your domain model, it came from your data aggregating processes. Is that wrong?

I work on large financial and project management applications where the business logic is extensive. When reporting on this data, I will often have a LOT of aggregations to do to pull the information required for the report/dashboard, and the aggregations have a lot of business logic in them. For performance sake, I have been doing it with highly aggregated tables and stored procedures.

As an example, let's say a report/dashboard is needed to show a list of active projects (imagine 10,000 projects). Each project will need a set of metrics shown with it, for example:

total budget

effort to date

burn rate

budget exhaustion date at current burn rate

etc.

Each of these involves a lot of business logic. And I'm not just talking about multiplying numbers or some simple logic. I'm talking about in order to get the budget, you have to apply a rate sheet with 500 different rates, one for each employee's time (on some projects, other's have a multiplier), applying expenses and any appropriate markup, etc. The logic is extensive. It took a lot of aggregating and query tuning to get this data in a reasonable amount of time for the client.

Should this be run through the domain first? What about performance? Even with straight SQL queries, I'm barely getting this data fast enough for the client to display in a reasonable amount of time. I can't imagine trying to get this data to the client fast enough if I am rehydrating all these domain objects, and mixing and matching and aggregating their data in the application layer, or trying to aggregate the data in the application.

It seems in these cases that SQL is good at crunching data, and why not use it? But then you have business logic outside your domain model. Any change to the business logic will have to be changed in your domain model and your reporting aggregation schemes.

I'm really at a loss for how to design the reporting/dashboard part of any application with respect to domain driven design and good practices.

I added the MVC tag because MVC is the design flavor du jour and I am using it in my current design, but can't figure out how the reporting data fits into this type of application.

I'm looking for any help in this area - books, design patterns, key words to google, articles, anything. I can't find any information on this topic.

EDIT AND ANOTHER EXAMPLE

Another perfect example I ran across today. Customer wants a report for Customer Sales Team. They want what seems like a simple metric:

For each Sales person, what is their annual sales to date?

But that is complicated. Each sales person participated in multiple sales opportunities. Some they won, some they didn't. In each sales opportunity, there are multiple sales people who are each allocated a percentage of credit for the sale per their role and participation. So now imagine going through the domain for this...the amount of object rehydration you would have to do to pull this data from the database for every Sales person:

Get all the SalesPeople->

  For each get their SalesOpportunities->

  For each get their percentage of the sale and calculate their Sales amount

  then Add up all their SalesOpportunity Sales amount.

And that's ONE metric. Or you can write a SQL query which can do it quickly and efficiently and tune it to be fast.

EDIT 2 - CQRS Pattern

I've read about the CQRS Pattern and, while intriguing, even Martin Fowler says it's not tested. So how has this problem BEEN solved in the past. This has to have been faced by everyone at some point or another. What is an established or well-worn approach with a track record of success?

Edit 3 - Reporting Systems/Tools

Another thing to consider in this context is reporting tools. Reporting Services/Crystal Reports, Analysis Services and Cognoscenti, etc. all expect data from SQL/database. I doubt your data will come through your business later for these. And yet they and others like them are a vital part of the reporting in a lot of large systems.
How is the data for these properly handled where there is even business logic in the data source for these systems as well as possibly in the reports themselves?

答:
My understanding from your question is this:
Application for daily task has

View >>   Controller >>   Model (BL) >>     Database (Data)

Application for reporting purpose

View >>   Controller >>   Model     >>      Database (Data + BL)

So change in BL for 'task application' will lead to change in 'reporting' BL too. That is your real problem right? Well thats OK to do changes twice, that pain you have to take anyway. The reason is both the BLs are separated by their respective concerns. One is for fetching data and one for aggregrating data. Also, your original BL and aggregrating BL will be written in different technology or language (C#/java and SQL proc). There is no escape to it.

Lets take another example not related to reporting specifically. Suppose a company XXX tracks mails of all users for interpretation and sell that info to marketing companies. Now it will have one BL for interpretation and one BL for aggregrating data for marketing companies. Concerns are different for both the BLs. Tomorrow if their BL changes such that mails coming from Cuba should be ignored, then business logic will be changed at both sides.

OwnerDisplayName: Richard DesLonde


问:
Where does non-MVVM code belong in an MVVM app?
By non-MVVM code, I mean things like highly generalized components, like one with common extension methods for CLR types, and other 'homeless' helper classes etc? I have a Core project that most others reference, but to resolve circular dependencies I had to refactor the extensions to another project. This seems a common challenge in a well layered project.

In some cases it's easier and produces a better project structure to have one copy of a class in each of two or more components, and I can't use symlinks for these copies because the namespace differs.

Or else I'm going to end up with quite a fat Core project, hosting disparate groups of helper classes. Down to what granularity can I factor these out and increase the dependency count of clients of these servives. What is a general convention here?

答:
In most of the MVVM Projects I have worked on, there are usually a number of "cross-cutting" libraries that are accessible to every layer of the MVVM model. This is where we would put UI helpers / Logging / general utilities such as extension methods that can be used anywhere. In our solution there would be a solution folder for each of the following:

Host (This is where the executable will reside)

DA ( Data Access Layer)

BL (Business Layer, the Model)

PL (Presentation Layer, the ViewModels)

UI (User Interface, the Views)

Services (This is where all of the cross cutting code would be hosted, e.g. MyProject.Services.UIHelpers)

I hope this helps.


问:
Where is Smalltalk-80 best used?
I want to know in which applications/programming domain are most suitable for Smalltalk. Could anyone please provide me some useful links that could answer my query?

Through googling I learned that some companies use it for:

logistics and foreign trade application
desktop, server and script development
data processing and logistics, scripts and presentations
but I cant find documents/research papers that can tell me which programming domain Smalltalk-80 (or Smalltalk) is best suited.

Some of the programming domains are: - Artificial intelligence reasoning - General purpose applications - Financial time series analysis - Natural language processing - Relational database querying - Application scripting - Internet - Symbolic mathematics - Numerical mathematics - Statistical applications - Text processing - Matrix algorithms

I hope you guys can help me. I am doing this for my case study. Thanks in advance.

答:
I have the impression it's nowadays mostly used for Seaside-projects. Some rare counter-examples:

http://impara.de/projekt_plopp_engl.html

http://www.huv.com/uSeeker/smalltalk/simulator.html

http://www.maxscheduler.com/

http://www.minidata.ca/

http://www.pharo-project.org/about/success-stories

In general it should be usable in any context where you find dynamically typed OO-programming languages.

OwnerDisplayName: njay

ContentLicense: CC BY-SA 2.5

Title: Where is Smalltalk-80 best used?


问:
Dangers when implementing features as plugins
What kind of problems have you encountered when building plugin interfaces for your application?  And how did you resolve them?

Background

I want to refactor an application so that various features can be moved into plugins, allowing them to be easily added and removed in future.

I hope this will be a neater system than scattering if (FeatureX_is_enabled) branches throughout the code.  (I may be wrong!)  I believe I will need to define interfaces for each part of the system into which a features may plug in.

I would like to benefit from your experience if you have already undertaken this kind of project.  Perhaps you have endured mistaken designs, and can advise what not to do.  Perhaps you can recommend patterns or architectures that can make such a system more manageable.

Concerns

A few issues already spring to mind:

I will need to provide some power to plugins so that they can get their job done.  If I pass too little control, new plugins may be too restricted to do what they need (e.g. some Google Chrome extension authors complain about the inability to modify the core interface).  However if I pass too much control, irresponsible plugins will have the power to break the whole application (e.g. Mozilla Firefox extensions).

Some plugins may need to run in a different order on different events.  I could register event handlers with a priority, e.g. 1-100, so that plugins can hook themselves into the appropriate order.  Or I could just create post_ and pre_ events and hope nothing more finely grained is needed.

If two plugins depend on another plugin to be available first then the plugin architecture will need some kind of dependency (and naming) system.

Related, some plugins will need to know when other plugins are present, and perhaps even make calls into each other to handle edge cases.

There may be difficulties maintaining the state of the application if plugins are enabled and disabled at runtime.  (Chrome seems to handle this well, but many applications require a restart.)

This kind of architecture will obfusticate the flow of execution (in exchange for keeping additional behaviour out of the core code).  I will need to write neat interfaces so that unexpected behaviour is minimised.

Sometimes the monolothic if (FeatureX_is_enabled) approach might be a better way to handle the situation than breaking out to a plugin, but I don't know how to recognise such situations.

It is likely there are other concerns I have not considered, so I would love to hear what you have had to deal with!

Related

Related question: How to turn on/off code modules?

Related library: Bemson's curious Flow library for Javascript seems to provide various features to help adding and removing features to/from a program at runtime, but I have trouble getting my head around it!

答: I think the first thing to do is to ask who the plugin coder will be. Are you letting people outside your company create plugins or are plugins just a way to separate functionality? That determines how strict the interface must be. It is even possible to let diffrent plugins get different levels of functionality.</p>


答:
On the similar level as your variable boxes - as a distant analogy - these methods can be seen as recipes. e.g:

to make spaghetti you:

boil salted water

throw in the spaghetti

check repeatedly if spaghetti are ready

take out the spaghetti

in pseudocode:

```<code>def make_spaghetti()
    boil_salted_water()
    while not ready()
        wait(30)
    take_out()
</code>```

You have a name and some instructions, and - as with the boxes - the name of the recipe should give a precise idea of what is done.

Note how the instructions like boil_salted_water are smaller recipes themselves (take a pot, pour in some water, etc.).

ps: now if you ask for the context of the recipe like who's the cook, the kitchen, ingredients, etc, refer to @9000's answer.

Title: How do I explain a ruby method with a real-world analogy?

Body:
I am looking for a good analogy to help the concept of a method in ruby stick in my head. When I truly understand a concept, an image flashes in my mind that relates something physical to the abstract concepts I am trying to learn.

For example, someone explained the concept of a variable to me in the following way:

A variable is like a box you can put things in. The name of the variable is like taking a sharpie and writing a word, like "forks" on the side of the box. Picking a good name is important. You can stick anything in the box, but if you write 'forks' on the side of the box, you would expect forks to be in the box. You can put anything in the box, then carry it around to various people, and tell them "there are forks in this box." When they need a fork, they go to the fork box and get out a fork.

That's the sort of physical, image-based, concrete analogy I am looking for for a ruby method.

Right now most definitions I have found are useless to me. For example, at turtorialspoint, the first result for the google search 'what is a ruby method,' has the folowing definition.

Ruby methods are very similar to functions in any other programming language. Ruby methods are used to bundle one or more repeatable statements into a single unit.

Let me give you an example of why this definitions is useless to me. I'm going to replace every word and concept in this definition that I don't understand with the word 'blah.'

Ruby blah are very similar to blah in any other programming language. Ruby blah are used to blah one or more blah blah into a single blah.

In summary, can I get a good, physical analogy for the concept of a method in ruby?

Body:
On the similar level as your variable boxes - as a distant analogy - these methods can be seen as recipes. e.g:

to make spaghetti you:

boil salted water

throw in the spaghetti

check repeatedly if spaghetti are ready

take out the spaghetti

in pseudocode:

def make_spaghetti()
    boil_salted_water()
    while not ready()
        wait(30)
    take_out()

You have a name and some instructions, and - as with the boxes - the name of the recipe should give a precise idea of what is done.

Note how the instructions like boil_salted_water are smaller recipes themselves (take a pot, pour in some water, etc.).

ps: now if you ask for the context of the recipe like who's the cook, the kitchen, ingredients, etc, refer to @9000's answer.


答:
I DON'T use analogies but if I were it'd be like this (non ruby specific)

A variable is post it note. It can have values of any kind and usually theres a type written or associated with the post it note. Also post it notes may be different sizes (tiny such as byte and extra large for double and decimal cause you know its a lot of digits to write down).

An array is box of post it notes. The box may have 0 to many notes and you can put more into it or take some out

An interface is a cable adapter. Kind of like a micro<->usb cable. You computer, power adapter or another device uses a USB slot but the other end you are using something else (your phone which uses a micro usb).

A class is a device like your phone. It does stuff and has an interfaces to it. Like the touchscreen or micro usb (two different interfaces, one for human other for machine). Or a memory stick if you want something different.

A method is a recipe. It tells you what it needs (ingredients) and what it produces (other ingredients or a muffin).

You MAY have a post-it note refer to a recipe

A virtual method is an advance recipe. You can change the cake or muffin it creates by adding frosting or even changing an ingredient (carrot instead of chocolate).

A class with a base class is a hacked phone. It does more and things it wasn't meant to do. Or a the 32x for sega genesis. It makes it do way more then it should be able to do (it has its own processing chip)

A Tuple is a shish kabob. It can have really as many things as it wants and way different types (meat, pepper, fruits, cheese ANYTHING)

IDK if you want any more. These were pretty fun to do and many of these I havent thought until now and were easy to think up.


答:
I think it has to do with a 'thread of reasoning' or 'thread of thought'. </p>

<p>In contrast to a process, threads share memory. So if a process is likened with a person with his/her own mind (memory), a thread can be likened with one line of thought within that mind. </p>

Title: Why are threads called threads?

Body:
I think it has to do with a 'thread of reasoning' or 'thread of thought'.

In contrast to a process, threads share memory. So if a process is likened with a person with his/her own mind (memory), a thread can be likened with one line of thought within that mind.


问:
expressing the speed of a sorting algorithm
How would I express the speed of the following sort algorithm? I know bubblesort is n^n (er, I mean n^2...as someone pointed out below). In the following the array decreases each time you call it recursively.

thanks.

```<code>$myarray = array("21","4","8","8","1","2","19","21");
mysort($myarray);

function mysort($myarray,$sorted = null){
    if(!isset($sorted)){
        $sorted = array();
    }
    $lowest = $myarray[0];
    $lowindex = 0;
    for($x = 1;$x < count($myarray);$x++){
        if($myarray[$x] < $lowest){
            $lowest = $myarray[$x];
            $lowindex = $x;
        }
    }
    $sorted[] = $lowest;
    array_splice($myarray,$lowindex,1);
    if(count($myarray) > 1){
        echo "calling recursively \n";
        mysort($myarray,$sorted);
    }
    else if(count($myarray) == 1){
        $sorted[] = $myarray[0];
        $arraystr = print_r($sorted,true);
        echo "sorting finished. Array is $arraystr \n";
        return;
    }
}
</code>```

答:
array_splice is at worst linear time, but let's assume it's constant time (if it's not, one can write that part differently to make it constant time). The algorithm nevertheless has the same asymptotic complexity as Bubblesort:

It finds the smallest element in n comparisons, moves it to the front (leaving n-1 elements to be sorted) and sorts the rest.

It finds the second smallest element in n - 1 comparisons, moves it to the front (leaving n-2 elements to be sorted) and sorts the rest.

It finds the third smallest element in n - 2 comparisons, moves it to the front (leaving n-3 elements to be sorted) and sorts the rest.

...

In total, there are about n + (n-1) + (n-2) + (n-3) + ... + 1 = 1 + 2 + 3 + ... + n comparisons. This is the triangular number n * (n - 1) / 2, which is in Θ(n^2), the same complexity as Bubblesort.

Not surprisingly, this algorithm is well-known, though it's more commonly done in-place and using a loop instead of recursion. It's called selection sort.


问:
How to reduce close points
input: C matrix 2xN (2D points)

output: C matrix 2xM (2D points) with equal or less points.

Lets say we have C matrix 2xN that contains several 2D points, and it looks something like that:

What we want is to group "close" points to one point, measured by the average of the other points. For example, in the second image, every group of blue circle will be one point, the point coordinate will be the average point off all points in the blue circle. also by saying "close", I mean that: their distance one to each other will be smaller then DELTA (known scalar). So wanted output is:

About running time of the algorithm, I don't have upper-limit request but I call that method several times...

I am using Matlab, and what i have tried is this:

```<code>function C = ReduceClosePoints(C ,l_boundry)
    x_size = abs(l_boundry(1,1)-l_boundry(1,2)); %220
    DELTA = x_size/10;
    T = [];
    for i=1:size(C,2)
        sum = C(:,i);
        n=1;
        for j=1:size(C,2)
            if i~=j     %not same point
                D = DistancePointToPoint(C(:,i),C(:,j));
                if D < DELTA
                    sum = sum + C(:,j);
                    n=n+1;
                end
            end
        end
        sum = sum./n; %new point -> save in T matrix
        T = [T sum];
    end
    C = T;
end
</code>```

And its not working :(
Also I am new to Matlab.

Thank you for your help!!

答:
You need to do this in two steps. First, group nearby points together. Then, replace each group by one point.

Let s be a nonempty subset of your points and  distance(p,s) the smallest distance between p and some element of s. Now here is some pseudocode for creating groups of "point clusters":

```<code> input: pointlist
 groups:={}   // will contain groups of points, disjoint subsets of "pointlist"
 for each p in pointlist
     let newgroup:={p}
     for each g in groups where `distance(p,g)<DELTA`
          newgroup := join(newgroup, g)  // join the two sets
          remove g from groups
     next g
     add newgroup to groups
 next p
 output: groups
</code>```

Note that this algorithm does not guarantee that each pair of points of a group has a distance < DELTA, only that each found group cannot be divided into two smaller groups with distance >= DELTA. You have to decide for yourself if that is sufficient, but as @DieterLücking has pointed out, don't expect to find an algorithm to solve the problem exactly the way you have described it originally.

Once you have your groups of points calculated, you can replace each group by the median value of it's points.

Concerning running time: the running time depends heavily of calculating the distance function fast. So in case the straight forward implementation of subsets by lists or arrays is not fast enough (which you should test first before starting to optimize!), then you might consider to use an improved data structure here. For example, you could keep track of the "bounding box" of all elements of a subset, since if distance(p, boundingbox(s))>=DELTA, then you can be sure that distance(p, s)>=DELTA as well.

Title: How to reduce close points

Body:
You need to do this in two steps. First, group nearby points together. Then, replace each group by one point.

Let s be a nonempty subset of your points and  distance(p,s) the smallest distance between p and some element of s. Now here is some pseudocode for creating groups of "point clusters":

 input: pointlist
 groups:={}   // will contain groups of points, disjoint subsets of "pointlist"
 for each p in pointlist
     let newgroup:={p}
     for each g in groups where `distance(p,g)<DELTA`
          newgroup := join(newgroup, g)  // join the two sets
          remove g from groups
     next g
     add newgroup to groups
 next p
 output: groups

Note that this algorithm does not guarantee that each pair of points of a group has a distance < DELTA, only that each found group cannot be divided into two smaller groups with distance >= DELTA. You have to decide for yourself if that is sufficient, but as @DieterLücking has pointed out, don't expect to find an algorithm to solve the problem exactly the way you have described it originally.

Once you have your groups of points calculated, you can replace each group by the median value of it's points.

Concerning running time: the running time depends heavily of calculating the distance function fast. So in case the straight forward implementation of subsets by lists or arrays is not fast enough (which you should test first before starting to optimize!), then you might consider to use an improved data structure here. For example, you could keep track of the "bounding box" of all elements of a subset, since if distance(p, boundingbox(s))>=DELTA, then you can be sure that distance(p, s)>=DELTA as well.


答:
Disclaimer:

I'm quite inexperienced in applications with domain models.

I understand all the concepts, and I've already been thinking for a long time about how to apply these concepts to the applications I'm working on (which ARE domain-rich, but lack OO, actual domain models etc.).

This question is one of the key problems that I faced as well. I have an idea how to solve this, but as I just said...it's just an idea that I came up with.

I didn't implement it in an actual project yet, but I don't see a reason why it shouldn't work, though.

Now that I've made that clear, here's what I came up with - I'll use your first example (the project metrics) to explain:

When someone edits a project, you're loading and saving it via your domain model anyway.

In this moment, you have all the information loaded to calculate all your metrics (total budget, effort to date etc.) for this project.

You can calculate this in the domain model, and save it to the database with the rest of the domain model.

So the Project class in your domain model will have some properties like TotalBudget, EffortToDate etc., and there also will be columns with those names in the database tables where your domain model is stored (in the same tables, or in a separate table...doesn't matter).

Of course, you need to do a one-time run to calculate the value for all existing projects as you are starting with this. But after that, the data is automatically updated with the current calculated values each time a project is edited via the domain model.

So whenever you need any kind report, all the required data is already there (pre-calculated) and you can just do something like this:

```<code>select ProjectName, TotalBudget, EffortToDate from Projects where TotalBudget > X
</code>```

It doesn't matter whether you get the data directly from the tables where the domain model is stored, or if you somehow extract the data to a second database, to a data warehouse or whatever:

If your reporting store is different from your actual data store, you can just copy the data from the "domain model tables"

If you directly query your actual data store, the data is already there and you don't need to calculate anything

In either case, the business logic for the calculations is in exactly one place: the domain model.

You don't need it anywhere else, so it's not necessary to duplicate it.

Title: Best practice or design patterns for retrieval of data for reporting and dashboards in a domain-rich application

Body:
First, I want to say this seems to be a neglected question/area, so if this question needs improvement, help me make this a great question that can benefit others! I'm looking for advice and help from people who have implemented solutions that solve this problem, not just ideas to try.

In my experience, there are two sides of an application - the "task" side, which is largely domain driven and is where the users interact richly with the domain model (the "engine" of the application) and the reporting side, where users get data based on what happens on the task side.

On the task side, it's clear that an application with a rich domain model should have business logic in the domain model and the database should be used mostly for persistence. Separation of concerns, every book is written about it, we know what to do, awesome.

What about the reporting side? Are data warehouses acceptable, or are they bad design because they incorporate business logic in the database and the very data itself? In order to aggregate the data from the database into data warehouse data, you must have applied business logic and rules to the data, and that logic and rules didn't come from your domain model, it came from your data aggregating processes. Is that wrong?

I work on large financial and project management applications where the business logic is extensive. When reporting on this data, I will often have a LOT of aggregations to do to pull the information required for the report/dashboard, and the aggregations have a lot of business logic in them. For performance sake, I have been doing it with highly aggregated tables and stored procedures.

As an example, let's say a report/dashboard is needed to show a list of active projects (imagine 10,000 projects). Each project will need a set of metrics shown with it, for example:

total budget

effort to date

burn rate

budget exhaustion date at current burn rate

etc.

Each of these involves a lot of business logic. And I'm not just talking about multiplying numbers or some simple logic. I'm talking about in order to get the budget, you have to apply a rate sheet with 500 different rates, one for each employee's time (on some projects, other's have a multiplier), applying expenses and any appropriate markup, etc. The logic is extensive. It took a lot of aggregating and query tuning to get this data in a reasonable amount of time for the client.

Should this be run through the domain first? What about performance? Even with straight SQL queries, I'm barely getting this data fast enough for the client to display in a reasonable amount of time. I can't imagine trying to get this data to the client fast enough if I am rehydrating all these domain objects, and mixing and matching and aggregating their data in the application layer, or trying to aggregate the data in the application.

It seems in these cases that SQL is good at crunching data, and why not use it? But then you have business logic outside your domain model. Any change to the business logic will have to be changed in your domain model and your reporting aggregation schemes.

I'm really at a loss for how to design the reporting/dashboard part of any application with respect to domain driven design and good practices.

I added the MVC tag because MVC is the design flavor du jour and I am using it in my current design, but can't figure out how the reporting data fits into this type of application.

I'm looking for any help in this area - books, design patterns, key words to google, articles, anything. I can't find any information on this topic.

EDIT AND ANOTHER EXAMPLE

Another perfect example I ran across today. Customer wants a report for Customer Sales Team. They want what seems like a simple metric:

For each Sales person, what is their annual sales to date?

But that is complicated. Each sales person participated in multiple sales opportunities. Some they won, some they didn't. In each sales opportunity, there are multiple sales people who are each allocated a percentage of credit for the sale per their role and participation. So now imagine going through the domain for this...the amount of object rehydration you would have to do to pull this data from the database for every Sales person:

Get all the SalesPeople->

  For each get their SalesOpportunities->

  For each get their percentage of the sale and calculate their Sales amount

  then Add up all their SalesOpportunity Sales amount.

And that's ONE metric. Or you can write a SQL query which can do it quickly and efficiently and tune it to be fast.

EDIT 2 - CQRS Pattern

I've read about the CQRS Pattern and, while intriguing, even Martin Fowler says it's not tested. So how has this problem BEEN solved in the past. This has to have been faced by everyone at some point or another. What is an established or well-worn approach with a track record of success?

Edit 3 - Reporting Systems/Tools

Another thing to consider in this context is reporting tools. Reporting Services/Crystal Reports, Analysis Services and Cognoscenti, etc. all expect data from SQL/database. I doubt your data will come through your business later for these. And yet they and others like them are a vital part of the reporting in a lot of large systems.
How is the data for these properly handled where there is even business logic in the data source for these systems as well as possibly in the reports themselves?

Body:
Disclaimer:

I'm quite inexperienced in applications with domain models.

I understand all the concepts, and I've already been thinking for a long time about how to apply these concepts to the applications I'm working on (which ARE domain-rich, but lack OO, actual domain models etc.).

This question is one of the key problems that I faced as well. I have an idea how to solve this, but as I just said...it's just an idea that I came up with.

I didn't implement it in an actual project yet, but I don't see a reason why it shouldn't work, though.

Now that I've made that clear, here's what I came up with - I'll use your first example (the project metrics) to explain:

When someone edits a project, you're loading and saving it via your domain model anyway.

In this moment, you have all the information loaded to calculate all your metrics (total budget, effort to date etc.) for this project.

You can calculate this in the domain model, and save it to the database with the rest of the domain model.

So the Project class in your domain model will have some properties like TotalBudget, EffortToDate etc., and there also will be columns with those names in the database tables where your domain model is stored (in the same tables, or in a separate table...doesn't matter).

Of course, you need to do a one-time run to calculate the value for all existing projects as you are starting with this. But after that, the data is automatically updated with the current calculated values each time a project is edited via the domain model.

So whenever you need any kind report, all the required data is already there (pre-calculated) and you can just do something like this:

select ProjectName, TotalBudget, EffortToDate from Projects where TotalBudget > X

It doesn't matter whether you get the data directly from the tables where the domain model is stored, or if you somehow extract the data to a second database, to a data warehouse or whatever:

If your reporting store is different from your actual data store, you can just copy the data from the "domain model tables"

If you directly query your actual data store, the data is already there and you don't need to calculate anything

In either case, the business logic for the calculations is in exactly one place: the domain model.

You don't need it anywhere else, so it's not necessary to duplicate it.


答:
The problem is not trivial!

Assume three points A, B, C where the distance d(A, B) is less than DELTA, d(B, C) is less than DELTA, but not d(A, C). Now you could select the minimum distance to join two points (lets say A and B) and get an intermediate result AB and C. Assume further the distance d(AB, C) is less than DELTA you will get a point ABC which is not the 'average' of three points.

I guess putting a grid over all points and clamping point coordinates to that grid might be better.

Title: How to reduce close points

Body:
input: C matrix 2xN (2D points)

output: C matrix 2xM (2D points) with equal or less points.

Lets say we have C matrix 2xN that contains several 2D points, and it looks something like that:

What we want is to group "close" points to one point, measured by the average of the other points. For example, in the second image, every group of blue circle will be one point, the point coordinate will be the average point off all points in the blue circle. also by saying "close", I mean that: their distance one to each other will be smaller then DELTA (known scalar). So wanted output is:

About running time of the algorithm, I don't have upper-limit request but I call that method several times...

I am using Matlab, and what i have tried is this:

```<code>function C = ReduceClosePoints(C ,l_boundry)
    x_size = abs(l_boundry(1,1)-l_boundry(1,2)); %220
    DELTA = x_size/10;
    T = [];
    for i=1:size(C,2)
        sum = C(:,i);
        n=1;
        for j=1:size(C,2)
            if i~=j     %not same point
                D = DistancePointToPoint(C(:,i),C(:,j));
                if D < DELTA
                    sum = sum + C(:,j);
                    n=n+1;
                end
            end
        end
        sum = sum./n; %new point -> save in T matrix
        T = [T sum];
    end
    C = T;
end
</code>```

And its not working :(
Also I am new to Matlab.

Thank you for your help!!


问:
Mapping 40 unique integers to 41 and back
This was a question proposed by a friend of mine. Define an algorithm that, given 40 unique integers in the range 1-1000, returns 41 unique integers in this range. Given these 41 integers, we must then be able to map them back to our original 40.

Does anyone have any insights? I have an idea, but it definitely isn't eloquent.

Thanks!

EDIT: I think I may need to clarify with an example. One naive solution would be: find the largest number in the set of 40. Increment it by 1 and this is your 41st number. When converting back, just get rid of the largest number. This obviously fails when the largest number in the set is 1000.

答:
Let's think about 4 unique integers in the range 1–10 first. We get the input set I = {1, 2, 3, 4}. We have to produce an output set O with |O| = |I| + 1. The most trivial solution is to return the input set and the smallest unused number n:

```<code>n = min([1, ..., 10] \ I)
O = I u {n}
</code>```

This is now a mapping I → O. The reverse operation can be implemented by remembering the pair (I, O) and looking the other set up. There is no way to get the original set without storing this connection!

If we want to have a mapping o → i forall o in O with i in I, then we can map each number to itself except n which could map to the lowest number in I. This means we have to remember the n separately.

As Python code:

```<code>numbers = range(1, 10+1)
def create_mapping(I):
  for n in numbers:
    if not n in I:
      break
  return (I + [n], n)

def map_back(mapping, x):
  O, n = mapping
  if x == n:
    return min(O)
  if x in O:
    return x
  return None

I = range(1, 5)
mapping = create_mapping(I)
back =  [map_back(mapping, x) for x in range(1, 10+1)]
assert back == [1, 2, 3, 4, 1, None, None, None, None, None]
</code>```

Also:

```<code>O, _ = mapping
assert set(I) == set(map_back(mapping, x) for x in O)
</code>```

which means that the mapping is reversible

Body:
Let's think about 4 unique integers in the range 1–10 first. We get the input set I = {1, 2, 3, 4}. We have to produce an output set O with |O| = |I| + 1. The most trivial solution is to return the input set and the smallest unused number n:

n = min([1, ..., 10] \ I)
O = I u {n}

This is now a mapping I → O. The reverse operation can be implemented by remembering the pair (I, O) and looking the other set up. There is no way to get the original set without storing this connection!

If we want to have a mapping o → i forall o in O with i in I, then we can map each number to itself except n which could map to the lowest number in I. This means we have to remember the n separately.

As Python code:

numbers = range(1, 10+1)
def create_mapping(I):
  for n in numbers:
    if not n in I:
      break
  return (I + [n], n)

def map_back(mapping, x):
  O, n = mapping
  if x == n:
    return min(O)
  if x in O:
    return x
  return None

I = range(1, 5)
mapping = create_mapping(I)
back =  [map_back(mapping, x) for x in range(1, 10+1)]
assert back == [1, 2, 3, 4, 1, None, None, None, None, None]

Also:

O, _ = mapping
assert set(I) == set(map_back(mapping, x) for x in O)

which means that the mapping is reversible


答:
report/dashboard is needed to show a list of active projects

State of each projects should be stored as static, per-calculated and well-formatted information in the database and any simulations should be handled on the client as WebApp.

budget exhaustion date at current burn rate

this type of projection should not be run on demand. Managing this information upon request, like perform calculations on resources, rate, tasks, milestones, etc, will result in an extensive use of the calculation layer without any re-use of these results for future calls.

Imagining a distributed environment (private or public cloud), you will get the enormous costs in the layer of computation, low use of database, and total lack of cache.

Should this be run through the domain first? What about performance?

The design of your software should include the ability to perform the normalization of the calculations necessary to obtain the required result during "data input", not during the reading. This approach greatly reduces the use of computing resources, and above all creates tables that could be considered as "read only" by the customer. This is the first step to create a caching mechanism solid and simple.

So a search first, before completing the software architecture, it could be Distributed Cache System.

(request:aggregation) != 1:1

My consideration is therefore (for both first and second example), try to understand when it is proper to normalize the data, having as objective to reduce the aggregations per client requests. Which can not be 1:1 (request: aggregation) if one goal is obtain a sustainable system.

Distribute the calculation on the client

Another question, before finishing the design of the software, it could be, how much normalization, we want to delegate the client's browser?

It was named MV*, it is true that it is fashionable today, in addition to this, one of its purposes is to create WebApp (single page app), which can be considered the present of many complex applications (and fortunately for bills that we pay to the cloud provider, these are executed in the client).

My conclusion is therefore to:

Understanding how many operations are really necessary to carry out the presentation of the data;

Analyze how many of these can be done in background (and then distributed through a cache system, after their normalization);

Understanding how many operations can be executed in the client, getting the configuration of the projects, running it on Views on the WebApp and thus reduce the calculation performed in back-end;


问:
Why are the Java 8 java.time classes missing a getMillis() method?
Java 8 has a whole new library for dates and times in the package java.time which is very welcome thing to anyone who has had to use JodaTime before or hassle with making it's own date processing helper methods. Many classes in this package represent timestamps and have helper methods like getHour() to get hours from timestamp, getMinute() to get minutes from timestamp, getNano() to get nanos from timestamp etc...

I noticed that they don't have a method called getMillis() to get the millis of the time stamp. Instead one would have to call method get(ChronoField.MILLI_OF_SECOND). To me it seems like an inconsistency in the library. Does anyone know why such a method is missing, or as Java 8 is still in development is there a possibility that it will be added later?

https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html

The classes defined here represent the principal date-time concepts, including instants, durations, dates, times, time-zones and periods. They are based on the ISO calendar system, which is the de facto world calendar following the proleptic Gregorian rules. All the classes are immutable and thread-safe.

Each date time instance is composed of fields that are conveniently made available by the APIs. For lower level access to the fields refer to the java.time.temporal package. Each class includes support for printing and parsing all manner of dates and times. Refer to the java.time.format package for customization options...

Example of this kind of class:

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html

A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime...

答:
Before being part of openJDK, threeten was on github and before that it was on sourceforge. Back then, Stephen Colebourne, who is a specification lead on jsr-310, made a survey tha you can still find on the sourceforge site.

The fourth question on the survey covered the method names for LocalTime:
1) getHourOfDay(), getMinuteOfHour(), getSecondOfMinute(), getNanoOfSecond()
2) getHour(), getMinute(), getSecond(), getNanoOfSecond()
3) getHour(), getMinute(), getSecond(), getNano()
4) another idea
```

only 6.23% chose answer #4 and among them approximately 15% asked for a getMillis(), i.e. less than 1% of the total votes.

That is probably why there was no getMillis in the first place and I could not find anything related on the openjdk mailing list so the matter was apparently not discussed afterwards.

ContentLicense: CC BY-SA 4.0

Body:
Before being part of openJDK, threeten was on github and before that it was on sourceforge. Back then, Stephen Colebourne, who is a specification lead on jsr-310, made a survey tha you can still find on the sourceforge site.

The fourth question on the survey covered the method names for LocalTime:
1) getHourOfDay(), getMinuteOfHour(), getSecondOfMinute(), getNanoOfSecond()
2) getHour(), getMinute(), getSecond(), getNanoOfSecond()
3) getHour(), getMinute(), getSecond(), getNano()
4) another idea

only 6.23% chose answer #4 and among them approximately 15% asked for a getMillis(), i.e. less than 1% of the total votes.

That is probably why there was no getMillis in the first place and I could not find anything related on the openjdk mailing list so the matter was apparently not discussed afterwards.


问:
How To Know When To Stop Testing?
I know this is a very very basic question. For some software applications there are a large almost infinitely high number of test cases for an application. It is not practical to test all those test cases. How do we decide when to stop testing? (other than "when money runs out"). </p>

答:
"Program testing can be used to show the presence of bugs, but never to show their absence!" --Edsger Dijkstra

Something good to keep in mind when doing any testing, automated or otherwise.  You can only prove that you haven't found any more bugs, not that there aren't any more.

But the more eyes you put on a section of code, the more confident you can be of its proper operation.  Its a lot like Knuth's quote on optimization in that regard: you can test the wrong stuff very easily, and you can test at the wrong times in your development.

Essentially, you want to be covered in two big places:

Does the software pass the BDD tests that demonstrate it meets the specified requirements.  The software can't even be called done if this isn't true.

Do the most critical, complex, and unsure segments have adequate tests to provide confidence?  If it's a core loop, or something you had to optimize or hack at: put a test on it.  If it's complicated and has a lot of logical splits: put a lot of tests on it.  If you can't unit test it, or it is embedded too deep to practically test directly: ensure the code has been reviewed, and the code indirectly tested by hand.

Title: How To Know When To Stop Testing?


答:
Edit:  This answer assumes the set of 41 has to include the original set of 40.

You really have two problems:

Finding a 41st Number

What you're looking for here is a gap where you can sneak in a new number, so the first thing you'll need to do is sort it.

With your sorted list in hand, the easy shortcuts are to see if there's a gap at the beginning (first number is greater than 1) or the end (last number is less than 1,000).  If either of those is true, the 41st item can be 1 or a 1,000 depending on which it is.  You're done.

If the sorted list contains 1 and 1,000, you have to traverse it until you find two adjacent numbers that have a difference greater than one.  The space between those two numbers represent the gap, and the 41st item is some number in that gap.  The easiest thing to do would be one greater than the lesser of the two numbers of one less than the greater.

Restoring the Original 40 Numbers

Your friend's problem has a flaw in that it doesn't provide any information about how the original set of 40 numbers are provided (unordered set, list, etc.) or how the set containing the 41st number should be returned.

If the sets provided and returned are actually a 40-item ordered (just ordered, not necessarily sorted) list, the new number can be appended as the 41st item and then lopped off later to get back to the original.

If the sets are unordered, there's no way to figure out which item has to be removed to restore the original 40.  You just don't know what was added.

You might think there's some clever way of giving the number you add some intelligence that will reveal the identity of the added number when you're handed a set of 41 later, but there isn't.  Someone who knows your algorithm could construct a valid set of 40 that will result in a set of 41 that yields the wrong answer when cut back to 40.

Title: Mapping 40 unique integers to 41 and back

Body:
This was a question proposed by a friend of mine. Define an algorithm that, given 40 unique integers in the range 1-1000, returns 41 unique integers in this range. Given these 41 integers, we must then be able to map them back to our original 40.

Does anyone have any insights? I have an idea, but it definitely isn't eloquent.

Thanks!

EDIT: I think I may need to clarify with an example. One naive solution would be: find the largest number in the set of 40. Increment it by 1 and this is your 41st number. When converting back, just get rid of the largest number. This obviously fails when the largest number in the set is 1000.


问:
Why speaks basic http authentication always of a username
In RFC 2617 HTTP Authentication: Basic and Digest Access Authentication they speak always of username and password for the authentication.

Why should I choose to take a username as identifier for a website? Usernames are often hard to choose a not existing one or one which is unique. But everyone getting an account somewhere has an email which is unique.

Why does the RFC not speak of something abstract like a unique string identifier? That would make much more sense to me where everyone logs into his account with his email...

When someone starts with security/authentication the first thing he will think reading the RFC 2617 that he can not do basic auth because I want email + password. What am I missing here?

答:
The problem here isn't so much the spec, as it is your interpretation.

It seems there's a habit among computer professional to always expect verbally spoken and written language to have the same well-defined meaning as programming languages (i.e. if you use this word in a sentence, you must mean this).

What's worse is that different people have different preconceptions of the exact and true meaning of certain words and that leads to all kinds of discussions, arguments and all-out battles. Here's an example of someone trying to understand a difference between fragile and brutal and you can read my ranty answer: https://softwareengineering.stackexchange.com/questions/131240/difference-between-brittle-and-fragile/131259#131259

You have fallen into the same trap with this auth spec. They mention "username" and "password" but all it really means is that your credentials have two parts: public part that everyone knows about and can uniquely identify you by and a private secret part that only the user knows so he can get authenticated.  But at the end, the public part (aka a "username") can be just about anything you want, including someone's e-mail, or in some dumb cases, their social security# or in corporate case their unique identifier which puts then on the same level as all other resources.


答:
Edit: This answer is based on the incorrect assumption that the OP wanted the original 40 integers to be included in the set of 41. As such, it's wrong but I am leaving it for now because it adds an interesting twist to the problem.

I don't know if this is possible with a set of 40 numbers, but it is possible to add an unique integer to sets of one or two numbers and get it back out. Here's the decoding logic for these two cases:

Set of 1: If the numbers in the encoded set are consecutive, the added number is the larger number, else the added number is the smaller of the two.

Set of 2:
If any two numbers in the encoded set are separated by a gap of one or less, the added number is the number that is not part of this pair, else the added number is the one that falls between the smallest and largest numbers.

It might be possible able construct encoding/decoding logic for sets of 3, 4, 5 ... 998. It is not possible to creating decoding logic for a set of 999. 999 Doesn't work because there is only one missing number in its set and the encoded set will fill in that one missing number, resulting in a set containing every number from 1 to 1000.

That's about as far my little brain can take it. The folks over at https://cs.stackexchange.com/ might be able to come up with a formal proof and method for determining exactly how large a set can be and still be reversible for your range of 1 to 1000.


问:
Fortran 90 - How to create a coordinate system
So I need to code a simple program, and I need to define 2D coordinates?

Is there any coordinate system I can use in Fortran?

I was told it might have to be all in arrays? And if so, can anybody push me in the right direction as to how to set up 2d arrays?

Many thanks.

答:
You could create a 2D array. Googling for fortran 2d array led me to: How to initialize two-dimensional arrays in Fortran

Which includes:

```<code>INTEGER, DIMENSION(3, 3) :: array
array = reshape((/ 1, 2, 3, 4, 5, 6, 7, 8, 9 /), shape(array))
</code>```

which you can easily change to your situation.

Alternatively, you can create a custom coordinate type, and fill an array with those custom types. See for example: Array of derived type: select entry

which includes:

```<code>type Element
    logical active
    integer type
    real width
    ! etc
end type

type(Element), allocatable :: elements(:)
</code>```

Which, if adapted to your situation, would provide a nice way to having an allocatable array of 2D coordinates.

Body:
You could create a 2D array. Googling for fortran 2d array led me to: How to initialize two-dimensional arrays in Fortran

Which includes:

INTEGER, DIMENSION(3, 3) :: array
array = reshape((/ 1, 2, 3, 4, 5, 6, 7, 8, 9 /), shape(array))

which you can easily change to your situation.

Alternatively, you can create a custom coordinate type, and fill an array with those custom types. See for example: Array of derived type: select entry

which includes:

type Element
    logical active
    integer type
    real width
    ! etc
end type

type(Element), allocatable :: elements(:)

Which, if adapted to your situation, would provide a nice way to having an allocatable array of 2D coordinates.


答:
It is possible, there are 960/41 more sets of 41 numbers than sets of 40 numbers.  Decide of any arbitrary mapping.

As and example of algorithmic mapping, we will consider an extended problem: adding N numbers starting from M to a set (the original problem can be solved by adding 1 number starting from 1 to the set).

If M is not present in the set, add M to the set and then add N-1 numbers starting from M+1 to the set.
If M is present in the set, remove M from the set and add N+1 numbers starting from M+1 to the set.

To decode, we have to remove N numbers starting from M from a set (the original problem can be solved by removing 1 number starting from 1).

If M is present in the set, remove M from the set and then remove N-1 numbers starting from M+1.
If M is not present in the set, add M to the set and then remove N+1 numbers starting from M+1.

Another way of seeing this, is to consider the set as a bit set.  Then the encode and decode procedure are the same: flip the bits from the first one until you get the number of element you want in the set.

Here is a lisp encoder

```<code>(defun encode (l)
  (helper 1 1 l nil))

(defun decode (l)
  (helper -1 1 l nil))

(defun helper (cnt cur rem res)
  (cond
   ((= cnt 0)
    (append res rem))
   ((or (null rem) (/= cur (car rem)))
    (helper (- cnt 1) (+ cur 1) rem (append res (list cur))))
   (t
    (helper (+ cnt 1) (+ cur 1) (cdr rem) res))))
</code>```

and what you get when starting from a set of 3 elements.

```<code>(1 2 3) -> (4 5 6 7)
(1 2 4) -> (3 5 6 7)
(1 2 5) -> (3 4 6 7)
(1 2 a) -> (3 4 5 a)
(1 3 4) -> (2 5 6 7)
(1 3 5) -> (2 4 6 7)
(1 3 a) -> (2 4 5 a)
(1 a b) -> (2 3 a b)
(a b c) -> (1 a b c)
</code>```

Body:
It is possible, there are 960/41 more sets of 41 numbers than sets of 40 numbers.  Decide of any arbitrary mapping.

As and example of algorithmic mapping, we will consider an extended problem: adding N numbers starting from M to a set (the original problem can be solved by adding 1 number starting from 1 to the set).

If M is not present in the set, add M to the set and then add N-1 numbers starting from M+1 to the set.
If M is present in the set, remove M from the set and add N+1 numbers starting from M+1 to the set.

To decode, we have to remove N numbers starting from M from a set (the original problem can be solved by removing 1 number starting from 1).

If M is present in the set, remove M from the set and then remove N-1 numbers starting from M+1.
If M is not present in the set, add M to the set and then remove N+1 numbers starting from M+1.

Another way of seeing this, is to consider the set as a bit set.  Then the encode and decode procedure are the same: flip the bits from the first one until you get the number of element you want in the set.

Here is a lisp encoder

(defun encode (l)
  (helper 1 1 l nil))

(defun decode (l)
  (helper -1 1 l nil))

(defun helper (cnt cur rem res)
  (cond
   ((= cnt 0)
    (append res rem))
   ((or (null rem) (/= cur (car rem)))
    (helper (- cnt 1) (+ cur 1) rem (append res (list cur))))
   (t
    (helper (+ cnt 1) (+ cur 1) (cdr rem) res))))

and what you get when starting from a set of 3 elements.

(1 2 3) -> (4 5 6 7)
(1 2 4) -> (3 5 6 7)
(1 2 5) -> (3 4 6 7)
(1 2 a) -> (3 4 5 a)
(1 3 4) -> (2 5 6 7)
(1 3 5) -> (2 4 6 7)
(1 3 a) -> (2 4 5 a)
(1 a b) -> (2 3 a b)
(a b c) -> (1 a b c)


答:
At no point does it say that your email address (as one example) cannot be your username. At no point does it say that the website issuing the login cannot insist that your email address (as one example) is your username.

The term for a string used to identify a user, is username. Whether it can always, never, or sometimes be an email address is out of implementation-dependent.

Title: Why speaks basic http authentication always of a username

Body:
In RFC 2617 HTTP Authentication: Basic and Digest Access Authentication they speak always of username and password for the authentication.

Why should I choose to take a username as identifier for a website? Usernames are often hard to choose a not existing one or one which is unique. But everyone getting an account somewhere has an email which is unique.

Why does the RFC not speak of something abstract like a unique string identifier? That would make much more sense to me where everyone logs into his account with his email...

When someone starts with security/authentication the first thing he will think reading the RFC 2617 that he can not do basic auth because I want email + password. What am I missing here?


答:
In general, being more precisely specific with word choice can at times make communication more difficult and cumbersome. The authors of the document assumed that their audience would understand that "username", "user name", "user ID", "UID", "userid", "user-id", ad infinitum, are all considered synonymous for the purposes of HTTP-Auth discussion - and indeed most discussions in this field.

Your username is the name that the "user" (and their associated account) is known by. This
"name" "identifies" the user uniquely. Their name is their ID, their passport, their Globally Unique Prearranged Realm-Dependent Identification Resource, etc.

In most cases I've encountered, these terms are used interchangeably, freely, and it is simply assumed that - being a part of the common culture - you'll understand what they mean as easily as you needn't have the precise meaning of "server/client" defined or their relationship made explicit.

So, why don't they speak more abstractly or precisely? Tradition, and it works. It is unlikely any system was ever mis-configured or improperly designed because of the word choice, and the valid format for a user-id is defined. User/pass is just so common a construct as to be assumed to be instantaneously understand by the target audience.


答:
You can order all 40-sets, like:

```<code>{1,2,...,40}
{1,2,...,38,39,41}
...
{961,...,1000}
</code>```

You can order all 41-sets as well (there is more of them).

So just count the order of your 40-set, and return the 41-set at the same position.

(code to perform it is not trivial to make, but should not be really hard with some playing with multiplications and modulus)

Body:
You can order all 40-sets, like:

{1,2,...,40}
{1,2,...,38,39,41}
...
{961,...,1000}

You can order all 41-sets as well (there is more of them).

So just count the order of your 40-set, and return the 41-set at the same position.

(code to perform it is not trivial to make, but should not be really hard with some playing with multiplications and modulus)


问:
Is it better expose a collection or an API to the collection?
Take for example the following:

```<code>public interface IManager
{
    void AddItem(CollectionItem item);
    void RemoveItem(CollectionItem item);
}

public interface IManagerCustomCollection
{
    ManagerCollection Systems;
}
</code>```

Is it usually more preferable to create a collection, and allow the consumer to operate directly on the collection?

答:
I would prefer to expose the API to the collection, that way when you are doing testing you don't need to worry about constructing the proper collection and you could also do tests where the collection is null etc.

You would also be able to implement your own conditions on which type of items get added to the collection, i.e. no duplicates etc.


问:
What's the career path for a developer who doesn't like management?
If you're developer (Senior or Lead Developer) and you'd rather stay with code/design than pursue a management career, what are the available career paths at your company, or any you've heard of? How far can you go?

Is it possible to continue being a geek until you bite the dust or is that too naive?

Are people like Uncle Bob for example still considered developers, as they claim?

答:
If you work for the right kind of company then there should be no limit to being a developer as long as you are really good at it.  Management is actually one of the easiest ways to climb the career ladder if you are less technically proficient.  I have seen this very often in the world of software development.

So I think that if you want to live in the code world but get to the top of the tree, you need to make sure you work for the right company - if you are good enough for long enough, they will make a position for you - ultimately you may end up being a decision maker (but not a manager) due to your vast experience.  I have seen developers move into Senior Vice President roles without having anyone to manage, but due to their knowledge, experience and enthusiasm.

Also, it may sound obvious but you should speak to your boss about what your career advancement options are - you may be surprised.  It helps if you think about some potential job titles that do not exist in your company and you can ask your boss if you can work towards changing to that - something like "Head of Code Quality" or essentially a title which hints at more than just a developer even though you may still just be a developer - this will make you stand out when it comes to future promotions or even pay reviews.  You have to remember that there are less jobs at the top, so you need to stand out.  A lot of people say a job title means very little, but that's not true - it can make your career if you choose your own - doing this simple act also shows some ambition.


问:
Any tips to learn how to program with severe ADHD?
I have a difficult time trying to learn how to program from straight text-books. Video training seems to work well for me in my past experiences with PHP. I am trying my hardest to stay focussed and push through. Specifically I am looking to start indie game development.

Over the last two weeks I have been trying to pick the "right" language and framework to develop with. I started going through Python, but I am not really enjoying the language so far. I am constantly looking through this website to compare this language to that, and keep getting distracted.

Aside from all of this, is it possible to become a programmer when you have trouble focussing? Has anyone been through this that can recommend some advice?

答:
Do a little bit at a time...is that a squirrel?  just kidding

First you need an accurate diagnosis.  Use your insurance to find a qualified psychologist that specializes in processing issues.  They have a battery of tests you take to diagnose your distractibility.

You may have mild to severe to normal distractibility.  You don't know for sure and you probably won't get much help until you do know.  Start the process now to find out about you and so you can be happy.  Also, even with "mild" distractibility medicine can help.  Training will also help you.  Furthermore, you could have other issues that will surface and that you might know but not be relaying here.

First bit of advice:  find the specialist and take the test.  If you've done that what did they say?

edit:  after reading one of your other answers.  Why did you stop your medication?


答:
Expose access to the collection using an interface, such as IList<T>, ICollection<T> or ISet<T>. Developers are familiar with these interfaces while not tying it to a specific implementation.  Throw a NotImplementedException for methods or properties you do not want to implement.

You lose some functionality. For example, as Jon Skeet points out, the interfaces are subsets of the features offered by concrete classes - IList<T> has fewer methods and properties than List<T>, for example. However, LINQ and similar mechanisms still work, unlike implementing your own interfaces or classes.

Title: Is it better expose a collection or an API to the collection?

Body:
Take for example the following:

```<code>public interface IManager
{
    void AddItem(CollectionItem item);
    void RemoveItem(CollectionItem item);
}

public interface IManagerCustomCollection
{
    ManagerCollection Systems;
}
</code>```

Is it usually more preferable to create a collection, and allow the consumer to operate directly on the collection?


答:
Is it usually more preferable to create a collection, and allow the consumer to operate directly on the collection?

It depends. Do you expect your user to create, manipulate, and otherwise use the collection? Or do you want to let them to do a few collection-like operations on something... that's not really a collection?

But before you answer: consider that this is a code smell. Well, it's two possible code smells:

You're making your own collection type. - The standard library collections (and interfaces) are good, extensive, and everyone knows them. Be really sure you need to before making a new one.

You're maybe violating single responsibility. - If you have some thing, and then that thing also has Add, Remove, etc... your thing might be doing two things. Look to separate those responsibilities.

All that said, I tend to prefer option 1. It provides stronger control over whatever weird invariants you need to protect if you're not just using a List (or whatever other basic collection). Usually these sort of things need to associate the collection with some other instance, which gets hairy if you decouple the collection from its paired instance.


问:
Console Application vs GUI?
I'm trying to develop a minimal MP3 player with some cool but light features. It is so simple that it doesn't matter if it is console application or not.

Since my purpose is to consume the sources as small as possible which one should I pick?

Extra info: I will be using a single textbox if it's going to be an application with GUI. Also, I am using VS 2010 C++

答:
I would ask three questions:

First, who is the target audience for the application? Most non-technical users are unfamiliar with console or command line interfaces. Console apps are usually OK for technical users, since they are used to legacy console applications.

Second, what platform will the application run on? A console app may be a good way of keeping a consistent UI across platforms. Most platforms have very different GUI styles. I also assume this will run on Windows or a *nix where console apps are supported.

Third, what are you trying to achieve? For example, if you want to focus on an unobtrusive UI, many platforms have ways of achieving this, such as the Windows task tray or the Mac menu bar. A console app may not be the best solution.

If you want as few lines of source code as possible, a console app may not give you that. Many GUI development environments have GUI editors or helpers that make writing GUIs relatively straight forward. Console app libraries, by comparison, have not received the same attention.

Do you want to write a console app for the sake of writing a console app? You could write the application as a library, keeping the UI separate. Afterwards, you write a console app as one UI over the app for quick development then, when you have a better idea of the features and design, invest time in a more robust, feature rich GUI.

Ultimately, particularly if this is freeware, maybe experiment with a console UI or with both. Release it with the product and see who uses it. Maybe people might like it or parts of it.

Title: Console Application vs GUI?


问:
Mapping values over a curve
I have a value between 0 and 8000 and I want this number to resolve to another number between 0 and 2000. I could just divide it by 4 but I have a special need here.

For values above 4000 I want the mapped value to be biased towards the 2000. But for values lower than 4000 I want the mapped value to be biased towards 0.

This is actually for a game where you are given bonus points between 0 and 2000 depending on how quickly you complete the task. So if you are very fast and do it in 7500 milliseconds you should get 1875 points (exactly 7500 / 4). If you do it in 6000 milliseconds you would get 1450 points (a little under 6000 / 4). If you are slow and do it in 1000 milliseconds you would get 50 milliseconds (well under 1000 / 4). The idea is to reward fast players more than slow players but still let slow players feel like they've achieved something. I feel an "eased-out" value mapping would achieve this.

I hope this makes sense. Can you help me figure out some code that achieves this?

答:
Try the sigmoid function:

It will map values from -(range/2) to +(range/2) to a scale between 0.0 and 1.0, with the midpoint at 0 *). The nice thing is that changing the range yields different curves. Here's an example with values from 1-2000 mapped on using the sigmoid:

Here are two runs of the function using different values of the range (r):

```<code>  ms     r=6    r=20
    0      94       0
  500     135       0
 1000     190       1
 1500     265       3
 2000     364      13
 2500     490      45
 3000     641     151
 3500     814     445
 4000    1000    1000
 4500    1186    1555
 5000    1359    1849
 5500    1510    1955
 6000    1636    1987
 6500    1735    1997
 7000    1810    1999
 7500    1865    2000
 8000    1906    2000
</code>```

*) actually, it maps between -infinity to +infinity, but for your purpose selecting a range between -10/+10 up to -30/+30 should work.

Title: Mapping values over a curve

Body:
Try the sigmoid function:

It will map values from -(range/2) to +(range/2) to a scale between 0.0 and 1.0, with the midpoint at 0 *). The nice thing is that changing the range yields different curves. Here's an example with values from 1-2000 mapped on using the sigmoid:

Here are two runs of the function using different values of the range (r):

  ms     r=6    r=20
    0      94       0
  500     135       0
 1000     190       1
 1500     265       3
 2000     364      13
 2500     490      45
 3000     641     151
 3500     814     445
 4000    1000    1000
 4500    1186    1555
 5000    1359    1849
 5500    1510    1955
 6000    1636    1987
 6500    1735    1997
 7000    1810    1999
 7500    1865    2000
 8000    1906    2000

*) actually, it maps between -infinity to +infinity, but for your purpose selecting a range between -10/+10 up to -30/+30 should work.


问:
Is it normal to look back on codes when coding?
the title says it all. I'm still a university student studying IT. Whenever I'm doing coding, I will frequently look back on codes that I've done before or looking for codes online or on reference book on how to do certain task like using classes, HTML stuffs and such. Is this behaviour acceptable on working place or do I need to learn to code without looking at references?</p>

答: This is perfectly normal, and if there is one thing to learn it's how to be efficient at looking for references/examples/documentation.</p>


答:
The nature of this particular beast - computer programming - is so vast that you will never be without the need of references, documentation, examples, and past work.

As you gain experience you will naturally need to look back less often for some tasks, as you come to memorize and gain insights into fundamental orderliness in various systems and topics.

You will eventually come to "chunk" things differently as you move towards being an expert and you'll be able to recall and reconstruct ever more complex and involved sets of codes and varying approaches, but you will always need references because our computer languages themselves are not entirely consistent.

And I must fully agree with pytyx's answer, that getting better at looking things up is an important part of the job.

Title: Is it normal to look back on codes when coding?

Body: the title says it all. I'm still a university student studying IT. Whenever I'm doing coding, I will frequently look back on codes that I've done before or looking for codes online or on reference book on how to do certain task like using classes, HTML stuffs and such. Is this behaviour acceptable on working place or do I need to learn to code without looking at references?</p>


问:
When must arbitrary precision arithmetic functions be used in PHP?
My colleague uses the Binary Calculator functions in bandwidth calculations; as much as terrabytes, and with percentage splitting on allocation. His usage of these functions appears correct in order not to lose a byte; although he seems to be using them now for everything.

The manual only says:

For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.

How much is any size? Is it really necessary? How big is the default float in PHP? Are there any good advice regarding this or things to keep in mind?

答:
```<code>"When must arbitrary precision arithmetic functions be used in PHP?"
</code>```

I have never heard of a site having to use bcmath functions in PHP for what could be considered normal practices, and keep in mind that most of the largest sites on the internet use use substantial amounts of PHP, and over 240 million of the "smaller" sites are coded using PHP.

bcmath is typically used for extreme cases where numbers are likely to become either very large or very small, rather than situations where a 'long' is needed rather than an int, or when the specific size of an int or float is a concern.

```<code>"How much is any size?"
</code>```

bcmath is only limited by memory, and in truth this is not a real limitation. A quick test with bcmath shows it can handle numbers greater than 2^1000000 (which is 301,030+ digits, one million is only seven digits) and '0.1 - 2^1000000' which results in a negative of equal proportion.

As far as performance goes, bcmath is fast but can consume a lot of memory. It basically calculates numbers the same way that we would (as humans) using a pen in pad. Realistic numbers can be processed in just a few hundred steps, typically resulting in just a few milliseconds of time. But these 'few hundred' string copies will add up in memory. Note the numbers above (2^1000000) are unfathomably large and take my fairly old laptop 2-3 seconds to deal with.

```<code>"Is it really necessary?"
</code>```

In short, yes, but very rarely.

For example, SHA-1 hashes are actually numbers, not strings. The highest possible number using SHA-1 is 2^160, or 1,461,501,637,330,902,918,203,684,832,716,283,019,655,932,542,976. There's no way to work with such numbers using native data types, and working with SHA-1 hashes (as numbers) is fairly common in distributed algorithms.

Again, this is rare, but when it's needed there really isn't a substitute, regardless of your system or framework of preference.

```<code>"Advise"
</code>```

Do not use bcmath unless you either know it is what you need or just enjoy playing with numbers. It won't break anything and shouldn't cause noticeable performance issues, but most problems can be solved using PHP's standard datatypes.

Body:
"When must arbitrary precision arithmetic functions be used in PHP?"

I have never heard of a site having to use bcmath functions in PHP for what could be considered normal practices, and keep in mind that most of the largest sites on the internet use use substantial amounts of PHP, and over 240 million of the "smaller" sites are coded using PHP.

bcmath is typically used for extreme cases where numbers are likely to become either very large or very small, rather than situations where a 'long' is needed rather than an int, or when the specific size of an int or float is a concern.

"How much is any size?"

bcmath is only limited by memory, and in truth this is not a real limitation. A quick test with bcmath shows it can handle numbers greater than 2^1000000 (which is 301,030+ digits, one million is only seven digits) and '0.1 - 2^1000000' which results in a negative of equal proportion.

As far as performance goes, bcmath is fast but can consume a lot of memory. It basically calculates numbers the same way that we would (as humans) using a pen in pad. Realistic numbers can be processed in just a few hundred steps, typically resulting in just a few milliseconds of time. But these 'few hundred' string copies will add up in memory. Note the numbers above (2^1000000) are unfathomably large and take my fairly old laptop 2-3 seconds to deal with.

"Is it really necessary?"

In short, yes, but very rarely.

For example, SHA-1 hashes are actually numbers, not strings. The highest possible number using SHA-1 is 2^160, or 1,461,501,637,330,902,918,203,684,832,716,283,019,655,932,542,976. There's no way to work with such numbers using native data types, and working with SHA-1 hashes (as numbers) is fairly common in distributed algorithms.

Again, this is rare, but when it's needed there really isn't a substitute, regardless of your system or framework of preference.

"Advise"

Do not use bcmath unless you either know it is what you need or just enjoy playing with numbers. It won't break anything and shouldn't cause noticeable performance issues, but most problems can be solved using PHP's standard datatypes.