问:
Best way to set sys.path for "hot library" development in Python?
I have my Python source structured as follows:

```<code>+-branchname/
  +-dst/
  +-src/
  | +-library/
  | | +-cleese/
  | | | +-test/
  | | | | +-__init__.py
  | | | | +-test_cleese.py
  | | | +-__init__.py
  | | | +-cleese.py
  | | +-palin/
  | |   +-test/
  | |   | +-__init__.py
  | |   | +-test_palin.py
  | |   +-__init__.py
  | |   +-palin.py
  | +-productline/
  |    +-circus/
  |    | +-test/
  |    | | +-__init__.py
  |    | | +-test_circus.py
  |    | +-__init__.py
  |    | +-circus.py
  |    +-grail/
  |      +-test/
  |      | +-__init__.py
  |      | +-test_grail.py
  |      +-__init__.py
  |      +-grail.py
  +-branch_root_marker
</code>```

Entry points are in circus/ and grail/, as well as (possibly) each of the test/ directories, depending on how testing is implemented.

I have multiple copies of this source tree present on local storage at any one point in time (corresponding to various maintenance and feature branches), so I cannot set PYTHONPATH in my shell without some pain. (I would need to remember to change it each time I switched to work on a different branch, and I am very forgetful)

Instead, I have some logic that walks up the file tree, starting at the "current" file location, moving from leaf towards root, looking for branch_root_marker. Once the root directory of the current working copy is found, it adds library/ and productline/ to sys.path. I call this function from each entry-point in the system.

```<code>"""Add working copy (branch) to sys.path"""

import os
import sys

def _setpath():
    """Add working copy (branch) to sys.path"""

    markerfile = "branch_root_marker"
    path = ""
    if ("__file__" in locals() or globals()) and __file__ != "__main__":
        path = __file__
    elif sys.argv and sys.argv[0] and not sys.argv[0] == "-c":
        path = sys.argv[0]
    path = os.path.realpath(os.path.expandvars(path))
    while os.path.exists(path):
        if os.path.exists(os.path.join(path, markerfile)):
            break
        else:
            path = os.path.dirname(path)
        errormsg = " ".join(("Could not find", markerfile))
        assert os.path.exists(path) and path != os.path.dirname(path), errormsg

    path = os.path.join(path, "src")
    (_, subdir_list, _) = os.walk(path).next()
    for subdir in subdir_list:
        if subdir.startswith("."):
            continue
        subdir_path = os.path.join(path, subdir)
        if subdir_path in sys.path:
            continue
        sys.path.append(subdir_path)
_setpath()
</code>```

Currently, I need to keep a separate but identical copy of this function in each entry point. Even though it is quite a short function, I am quite distressed by how fragrantly the DRY principle is being violated by this approach, and would love to find a way to keep the sys.path modification logic in one place. Any ideas?

Note:- One thing that springs to mind is to install the sys.path modifying logic into a common location that is always on PYTHONPATH. Whilst this is not a terrible idea, it means introducing an installation step that needs to be carried out each time I move to a fresh environment; another thing to remember (or, more likely, forget), so I would like to avoid this if at all possible.

答:
My workflow is somehow similar to yours: I have multiple branches checked out at different directories. I tried creating a virtualenv for each branch, but it's too much hassle.

I ended up setting PYTHONPATH relative to $PWD since I only have runnable code at one directory level: PYTHONPATH=$PWD/.. python code-to-run.py. This uses current dir's source tree, and, after it, virtualenv's and system modules.

This does not work under Windows, obviously.

Another way that I tried was a 'self-modifying' .pth file; it included

```<code>import sys, os; sys.path.insert(0. os.path.abspath('..'))
</code>```

You might use more complex logic if you want.

Body:
My workflow is somehow similar to yours: I have multiple branches checked out at different directories. I tried creating a virtualenv for each branch, but it's too much hassle.

I ended up setting PYTHONPATH relative to $PWD since I only have runnable code at one directory level: PYTHONPATH=$PWD/.. python code-to-run.py. This uses current dir's source tree, and, after it, virtualenv's and system modules.

This does not work under Windows, obviously.

Another way that I tried was a 'self-modifying' .pth file; it included

import sys, os; sys.path.insert(0. os.path.abspath('..'))

You might use more complex logic if you want.


问:
What code format has been verified by case studies as most readable?
Are there any eye-tracking case studies, or similar research done to verify what code format is easiest to read, maintain and work with?

I always format my code the following way:

```<code>function thing()
{
    if(something)
    {
      // do something
    }
    else
    {
      // do something else
    }
}
</code>```

However, I never see this followed elsewhere. In most APIs or open-source projects, it's done like this.

```<code>function thing() {
    if(something) {
      // do something
    } else {
      // do something else
    }
}
</code>```

Can you provide an answer that is not based upon your personal preference, but is supported by research or some kind of fact?

Has there been any visual eye-scanning studies done to confirm which format is best?

答:
Whatever format a programmer is most used to reading is the format they will read fastest in.  However, the minor differences between formatting matter little compared to how clear and concise the code and design is.  In other words, I would not worry about newlines vs no-newlines and worry about terrible vs good code.

But to answer your question I prefer the second method, particularly when the // do something is one or two lines.  If they are large blocks then you can refactor them into methods with clear names.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
When should an Aggregate Root contain another AR (and when should it not)
Let me begin by first apologizing for the length of the post, but I really wanted to convey as much detail up-front so I don't take your time going back and forth in comments.

I am designing an application following a DDD approach and am wondering what guidance I can follow to determine whether an Aggregate Root should contain another AR or if they should be left as separate, "free-standing" ARs.

Take the case of a simple Time Clock application that allows Employees to clock themselves in or out for the day.  The UI allows them to enter their employee ID and PIN which is then validated and the current state of the employee retrieved.  If the employee is currently clocked-in, the UI displays a "Clock Out" button; and, conversely, if they are not clocked-in, the button reads "Clock In".  The action taken by the button corresponds to the state of the employee as well.

The application is a web client that calls a back-end server exposed via a RESTful service interface.  My first pass at creating intuitive, readable URLs resulted in the following two endpoints:

```<code>http://myhost/employees/{id}/clockin
http://myhost/employees/{id}/clockout
</code>```

NOTE: These are used after the employee ID and PIN have been validated and a "token" representing the "user" is passed in a header. This is because there is a "manager-mode" that allows a manager or supervisor to clock-in or out another employee. But, for the sake of this discussion, I'm trying to keep it simple.

On the server, I have an ApplicationService that provides the API.  My initial idea for the ClockIn method is something like:

```<code>public void ClockIn(String id)
{
    var employee = EmployeeRepository.FindById(id);

    if (employee == null) throw SomeException();

    employee.ClockIn();

    EmployeeRepository.Save();
}
</code>```

This looks pretty straight-forward until we realize that the Employee's time card information is actually maintained as a list of transactions.  That means each time I call ClockIn or ClockOut, I am not directly changing the state of the Employee but, instead, I am adding a new entry into the Employee's TimeSheet.  The current state of the Employee (clocked in or not) is derived from the most recent entry in the TimeSheet.

So, if I go with the code shown above, my repository has to recognize that the persistable properties of the Employee have not changed but that a new entry was added into the Employee's TimeSheet and perform an insert into the data store.

On the other hand (and here's the ultimate question of the post), TimeSheet seems like it is an Aggregate Root as well as it has identity (the employee ID and period) and I could just as easily implement the same logic as TimeSheet.ClockIn(employeeId).

I find myself debating the merits of the two approaches and, as stated in the opening paragraph, wonder what criteria I should be evaluating to determine which approach is more suited for the problem.

答:
Aggregate roots should not contain each other (though they may contain IDs to others).

First, is TimeSheet really an aggregate root? The fact that it has identity makes it an entity, not necessarily an AR. Check out one of the rules:

```<code>Root Entities have global identity.  Entities inside the boundary have local
identity, unique only within the Aggregate.
</code>```

You define the TimeSheet's identity as employee ID & time period, which suggests that TimeSheet is a part of Employee with time period being the local identity. Since this is a Time Clock application, is the main purpose of Employee to be a container for TimeSheets?

Assuming you do have to ARs, ClockIn and ClockOut seem more like TimeSheet operations than Employee ones. Your service layer method could look something like this:

```<code>public void ClockIn(String employeeId)
{
    var timeSheet = TimeSheetRepository.FindByEmployeeAndTime(employeeId, DateTime.Now);
    timeSheet.ClockIn();
    TimeSheetRepository.Save();
}
</code>```

If you really need to track clocked-in state in both Employee and TimeSheet, then have a look at Domain Events (I don't believe they are in Evans' book, but there are numerous articles online). It would look something like: Employee.ClockIn() raises EmployeeClockedIn event, which an event handler picks up and in turn calls TimeSheet.LogEmployeeClockIn().

OwnerDisplayName: SonOfPirate

Body:
Aggregate roots should not contain each other (though they may contain IDs to others).

First, is TimeSheet really an aggregate root? The fact that it has identity makes it an entity, not necessarily an AR. Check out one of the rules:

Root Entities have global identity.  Entities inside the boundary have local
identity, unique only within the Aggregate.

You define the TimeSheet's identity as employee ID & time period, which suggests that TimeSheet is a part of Employee with time period being the local identity. Since this is a Time Clock application, is the main purpose of Employee to be a container for TimeSheets?

Assuming you do have to ARs, ClockIn and ClockOut seem more like TimeSheet operations than Employee ones. Your service layer method could look something like this:

public void ClockIn(String employeeId)
{
    var timeSheet = TimeSheetRepository.FindByEmployeeAndTime(employeeId, DateTime.Now);
    timeSheet.ClockIn();
    TimeSheetRepository.Save();
}

If you really need to track clocked-in state in both Employee and TimeSheet, then have a look at Domain Events (I don't believe they are in Evans' book, but there are numerous articles online). It would look something like: Employee.ClockIn() raises EmployeeClockedIn event, which an event handler picks up and in turn calls TimeSheet.LogEmployeeClockIn().


答:
I would be inclined to implement a service for time tracking:

```<code>public interface ITimeSheetTrackingService
{
   void TrackClockIn(Employee employee, Timesheet timesheet);

   void TrackClockOut(Employee employee, Timesheet timesheet);

}
</code>```

I don't think that it's time sheet's responsibility to clock in or clock out, neither it's employee's responsibility.

Title: When should an Aggregate Root contain another AR (and when should it not)

Body:
Let me begin by first apologizing for the length of the post, but I really wanted to convey as much detail up-front so I don't take your time going back and forth in comments.

I am designing an application following a DDD approach and am wondering what guidance I can follow to determine whether an Aggregate Root should contain another AR or if they should be left as separate, "free-standing" ARs.

Take the case of a simple Time Clock application that allows Employees to clock themselves in or out for the day.  The UI allows them to enter their employee ID and PIN which is then validated and the current state of the employee retrieved.  If the employee is currently clocked-in, the UI displays a "Clock Out" button; and, conversely, if they are not clocked-in, the button reads "Clock In".  The action taken by the button corresponds to the state of the employee as well.

The application is a web client that calls a back-end server exposed via a RESTful service interface.  My first pass at creating intuitive, readable URLs resulted in the following two endpoints:

```<code>http://myhost/employees/{id}/clockin
http://myhost/employees/{id}/clockout
</code>```

NOTE: These are used after the employee ID and PIN have been validated and a "token" representing the "user" is passed in a header. This is because there is a "manager-mode" that allows a manager or supervisor to clock-in or out another employee. But, for the sake of this discussion, I'm trying to keep it simple.

On the server, I have an ApplicationService that provides the API.  My initial idea for the ClockIn method is something like:

```<code>public void ClockIn(String id)
{
    var employee = EmployeeRepository.FindById(id);

    if (employee == null) throw SomeException();

    employee.ClockIn();

    EmployeeRepository.Save();
}
</code>```

This looks pretty straight-forward until we realize that the Employee's time card information is actually maintained as a list of transactions.  That means each time I call ClockIn or ClockOut, I am not directly changing the state of the Employee but, instead, I am adding a new entry into the Employee's TimeSheet.  The current state of the Employee (clocked in or not) is derived from the most recent entry in the TimeSheet.

So, if I go with the code shown above, my repository has to recognize that the persistable properties of the Employee have not changed but that a new entry was added into the Employee's TimeSheet and perform an insert into the data store.

On the other hand (and here's the ultimate question of the post), TimeSheet seems like it is an Aggregate Root as well as it has identity (the employee ID and period) and I could just as easily implement the same logic as TimeSheet.ClockIn(employeeId).

I find myself debating the merits of the two approaches and, as stated in the opening paragraph, wonder what criteria I should be evaluating to determine which approach is more suited for the problem.

Body:
I would be inclined to implement a service for time tracking:

public interface ITimeSheetTrackingService
{
   void TrackClockIn(Employee employee, Timesheet timesheet);

   void TrackClockOut(Employee employee, Timesheet timesheet);

}

I don't think that it's time sheet's responsibility to clock in or clock out, neither it's employee's responsibility.


答:
"Best" is relative.

Unfortunately, I can't remember the source.  The studies I have seen or were referenced indicate that consistent visual style is the key for a project.  Which particular house of style you worship at is less important than consistency.  See Atwood's article for some additional references, especially to Code Complete:  http://www.codinghorror.com/blog/2009/04/death-to-the-space-infidels.html

The premise is that if you're performing a code review, updating a new / foreign area, or bug hunting then the consistent presentation allows you, the developer, to more rapidly perform your task.  A consistent style minimizes the time spent retraining / adapting while moving around in the code tree.

Here's an article from Joel Spolsky with some additional, and I believe researched, references: http://www.joelonsoftware.com/articles/Wrong.html

Either Atwood or Spolsky will lead you down the route to Martin Fowler and Refactoring, where there are more studies / references.

This appears to be an article related to your question and "readability statistics", but after skimming it, I can't fully vouch for the quality of research.  It appears they borrowed the readability concept from regular writing and tried to apply it to code writing. http://www.comtor.org/wiki/images/4/4a/2009-Spring-Breese-A-499-PD.pdf

Title: What code format has been verified by case studies as most readable?

Body:
Are there any eye-tracking case studies, or similar research done to verify what code format is easiest to read, maintain and work with?

I always format my code the following way:

```<code>function thing()
{
    if(something)
    {
      // do something
    }
    else
    {
      // do something else
    }
}
</code>```

However, I never see this followed elsewhere. In most APIs or open-source projects, it's done like this.

```<code>function thing() {
    if(something) {
      // do something
    } else {
      // do something else
    }
}
</code>```

Can you provide an answer that is not based upon your personal preference, but is supported by research or some kind of fact?

Has there been any visual eye-scanning studies done to confirm which format is best?


问:
What is an Aguri tree?
Going through some old Hacker News items, I came across a post from a user that said

Aguri trees, which marry a bounded-size radix trie (like you'd use in a software routing table) to an LRU list, and automatically synthesize aggregates (like, 10.0.0.0/16 from 1,000 observations across all IPs) from the pattern of insertion. They're best known in traffic analysis, but we've used them on in runtime memory analysis as well.

~ tptacek

So I decided to look it up,

A quick Google Search leads me to a F1 driver.

A search on Wikipedia leads to a agricultural caste in India and some items from Japan

Stack Overflow hits 0 results https://stackoverflow.com/search?q=aguri site:stackoverflow.com/questions aguri

So I have finally linked it back to the user see he has a link on his blog

http://www.matasano.com/log/1009/aguri-coolest-data-structure-youve-never-heard-of/

But it's dead.

So, what is this Aguri data structure and if it is a real data structure, why is it not documented anywhere else?

答: Aguri is a traffic profiler that uses prefix trees. The complete article is on that page. In short there is no such data structure as an "Aguri Tree" unless you count the prefix trees used in that system to be their own unique subtype.</p>

Title: What is an Aguri tree?


问:
Estimate cost of project depends on [SLOC|COCOMO]?
Is it logical to estimate cost of project depends on source lines of code?

Like those calculated reports from tools such as

sloccount

ohloh estimating

*

How to convince [somebody|employer|client] to pay depends on those reports ?
The weird things come to scene when I see something like $83,862 based on my project.

Sometimes the developer [him|her]self would write more lines of code because of this estimating.

So if the count of the source lines isn't worthy, Why should be [sometimes|somehow] interesting part of development, Specially for employer, It does amaze them but why doesn't have any effect on pricing ?

Hey Employer I've developed this project that worth $1 million dollars, This source code counter program will prove it.

Maybe I don't know the real worth of my work, Should I public it for people and collect some comments about it or show it to some [experts|consultants] to find-out or just estimate myself upon my knowledge, And all of these solutions aren't right or at least logical.

And what happens to those codes I didn't wrote by myself, I mean sometimes we just copy a piece of code and [pasted|modified] into project.

And if estimating in this way is wrong, What is the purpose of these tools to generate such a report about source lines of code, Average hourly work and other facts.

Ohloh :

Estimated Cost

We calculate the estimated cost of the project using the Basic COCOMO
  model. For those familiar with the details, we are using coeffcients
  a=2.4 and b=105.

Estimate still seems way off?

Software cost estimation is tricky business even when all the
  variables are known (which we certainly don't have). One thing to
  remember is that COCOMO was created to model large institutional
  projects, which often don't compare well with distributed open-source
  projects. Beyond just development time, COCOMO is meant to include the
  design, specification drafting, reviewing and management overhead that
  goes along with producing quality software.

This model seems to be most accurate with mature, large projects.
  Young projects with little activity are typically overvalued.

I know quote from ohloh isn't just about SLOC

答:
Piece of code 1:

return this.Data.Products.Where(c => c.IsEnabled).GroupBy(c => c.Category).Select(c => new PricesPerCategory(category: c.Key, minimum: c.Min(d => d.Price), maximum: c.Max(d => d.Price)));
```

<p>Piece of code 2:</p>

<pre class="lang-cs prettyprint-override"><code>return this.Data.Products
    .Where(c => c.IsEnabled)
    .GroupBy(c => c.Category)
    .Select(c => new PricesPerCategory(category: c.Key, minimum: c.Min(d => d.Price), maximum: c.Max(d => d.Price)));
</code>```

Piece of code 3:

Func<Product, double> pricePredicate = c => c.Price;
Func<Product, bool> predicate = c => c.IsEnabled;
Func<Product, string> keySelector = c => c.Category;
Func<IGrouping<string, Product>, PricesPerCategory> finalSelector = c =>
    new PricesPerCategory(
        category: c.Key,
        minimum: c.Min(pricePredicate),
        maximum: c.Max(pricePredicate));

return this.Data.Products
    .Where(predicate)
    .GroupBy(keySelector)
    .Select(finalSelector);
```

Those three pieces of code do the same thing and compile very probably to the same IL code. As you may notice, the third piece of code is unreadable because excessive variables and lines of code were added just to grow the LOC while decreasing the code quality.

Why would somebody pay more for bad code in the third example, and pay less for the better code in the second one?

Body:
Piece of code 1:

return this.Data.Products.Where(c => c.IsEnabled).GroupBy(c => c.Category).Select(c => new PricesPerCategory(category: c.Key, minimum: c.Min(d => d.Price), maximum: c.Max(d => d.Price)));

Piece of code 2:

return this.Data.Products
    .Where(c => c.IsEnabled)
    .GroupBy(c => c.Category)
    .Select(c => new PricesPerCategory(category: c.Key, minimum: c.Min(d => d.Price), maximum: c.Max(d => d.Price)));

Piece of code 3:

Func<Product, double> pricePredicate = c => c.Price;
Func<Product, bool> predicate = c => c.IsEnabled;
Func<Product, string> keySelector = c => c.Category;
Func<IGrouping<string, Product>, PricesPerCategory> finalSelector = c =>
    new PricesPerCategory(
        category: c.Key,
        minimum: c.Min(pricePredicate),
        maximum: c.Max(pricePredicate));

return this.Data.Products
    .Where(predicate)
    .GroupBy(keySelector)
    .Select(finalSelector);

Those three pieces of code do the same thing and compile very probably to the same IL code. As you may notice, the third piece of code is unreadable because excessive variables and lines of code were added just to grow the LOC while decreasing the code quality.

Why would somebody pay more for bad code in the third example, and pay less for the better code in the second one?


问:
Backtracking with Killer Sudoku
I'm developing a Killer Sudoku solver for a school project. I've programmed 10 human strategies showing what they are doing in order to be the most educational possible.

It can solve hard Killer Sudokus right now but my teacher proposed that I use backtracking to solve every possible grid.

I've been trying for one week searching for general resources on backtracking or resources based on Sudoku... The fact is that with Killer Sudoku, you can't just say a cell has a solution without relying on zones and on what the previously written cells imply on zones and possibilities everywhere.

What I'd like to do is something which applies all my strategies everytime it suggests a number to be more efficient and return the only solution.

But to apply strategies, we need a copy of the grid right ? So I can clone my objects totally using some methods and I can apply my strategies using another method.

What would be the structure for this function ?

PS: I've tried several times to write some code and everytime the solution returned was incorrect. (The grid can easily be checked for validity)

It was something like this :

```<code>def bt(sudoku)
  if sudoku.valid? then
    true
  else
    sudoku2 = sudoku.clone
    sudoku2.first_cell_not_solved.possibilities.each do |p|
      sudoku2.first_cell_not_solved.solution = p
    end
    sudoku2.apply_all_strategies
    if sudoku.completed?
      return sudoku.valid?
    else
      bt(sudoku2)
    end
  end
end
</code>```

答:
Where you have sudoku2.first_cell_not_solved.set_first_possibility_as_solution, you actually need to be looping through all possibilities on the first cell not solved, then loop through all possibilities on the second cell not solved, etc.  Each time you see if choosing that possibility produces a solution by applying your strategies.  If it doesn't, you undo (i.e. backtrack) that possibility and choose the next one.  By only ever choosing the first possibility, your example code doesn't actually do any backtracking.

This kind of brute force algorithm has the potential to take a very, very long time.  The trick is choosing the right cell to go first.  For example, choosing a cell with only two possibilities will likely produce a result faster than choosing a cell that's wide open.  Also, you're likely to solve the same sub-puzzles many times, so some sort of memoization is usually very helpful.

Edit:  something like this (forgive any ruby mistakes, I don't know the language):

```<code>def bt(sudoku)
  if sudoku.completed? then
    return sudoku.valid?
  else
    sudoku.first_cell_not_solved.possibilities.each do |p|
      sudoku2 = sudoku.clone
      sudoku2.first_cell_not_solved.solution = p
      sudoku2.apply_all_strategies
      if bt(sudoku2)
        sudoku = sudoku2
        true
      end
    end
  end
  false
end
</code>```

Title: Backtracking with Killer Sudoku

Body:
Where you have sudoku2.first_cell_not_solved.set_first_possibility_as_solution, you actually need to be looping through all possibilities on the first cell not solved, then loop through all possibilities on the second cell not solved, etc.  Each time you see if choosing that possibility produces a solution by applying your strategies.  If it doesn't, you undo (i.e. backtrack) that possibility and choose the next one.  By only ever choosing the first possibility, your example code doesn't actually do any backtracking.

This kind of brute force algorithm has the potential to take a very, very long time.  The trick is choosing the right cell to go first.  For example, choosing a cell with only two possibilities will likely produce a result faster than choosing a cell that's wide open.  Also, you're likely to solve the same sub-puzzles many times, so some sort of memoization is usually very helpful.

Edit:  something like this (forgive any ruby mistakes, I don't know the language):

def bt(sudoku)
  if sudoku.completed? then
    return sudoku.valid?
  else
    sudoku.first_cell_not_solved.possibilities.each do |p|
      sudoku2 = sudoku.clone
      sudoku2.first_cell_not_solved.solution = p
      sudoku2.apply_all_strategies
      if bt(sudoku2)
        sudoku = sudoku2
        true
      end
    end
  end
  false
end


问:
In Java, why are nextInt() and nextDouble() instance methods of Random objects?
In Java, why are nextInt() and nextDouble() instance methods of Random objects?

I feel that these methods should be static methods of the Random class. What is the purpose of having to instantiate a Random object to generate random integers or double values?

答: The constructor for Random lets you input a seed value, so you'd want to be able to use that with your nextFoo methods.


问:
When programming: How much time is spend navigating/scrolling and how much typing?
When your programming you often have to go and look at other pieces of code for reference, search for something etc. I'm looking for some numbers on the ratio of time spend actually typing the code(coding) and the time spend going back and forth between other parts of the system, not even counting browsing the internet, reading documentation.

Ofcourse this depends on a large number of factors, probably also on your IDE, programming language etc. I just need some rough estimates, or researches on the subject.

Background:
I want to investigate how much network latency is tolerable for a programmer to work on virtual machines (if any).

答:
I want to investigate how much network latency is tolerable for a programmer to work on virtual machines (if any).

This is simple. I'm going to throw out the "scrolling/navigating" part of this question and go directly to the root here: typing vs. latency.

When I hit the key, I expect the character to appear immediately. Anything less than immediate is unacceptable. When it comes to typing, I expect results. I type something approaching 100 wpm. Latency negates that.

The biggest problem I have with latency when typing is this: if I misspell something, on a live computer I can backtrack and correct it at 100 wpm. So it's taken care of and corrected immediately. If I am typing with latency, then what happens is I misspell something and don't see it for a word or two. Now I have to stop, erase, retype, all slowly because of the latency. It just flat-out slows down the whole process of composition.

When it comes to typing latency, you just have to decide what you can reasonably live with.

ContentLicense: CC BY-SA 2.5


答:
Java's Random class uses an initial seed value and a linear congruential generator as a part of its internal state to generate a sequence of random numbers.  If the nextInt() and nextDouble() methods were static, they wouldn't have access to this internal storage.

From the docs:

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

Note that this also means that if two instances of Random are created with different seeds, they'll generate two different sequences.

Body:
In Java, why are nextInt() and nextDouble() instance methods of Random objects?

I feel that these methods should be static methods of the Random class. What is the purpose of having to instantiate a Random object to generate random integers or double values?


答:
because each Random object has it's own seed that you can set

this allows each thread to have it's own Random without having to worry about efficiency issues caused by synchronization

also Math.random() lets you get a random double in the [0,1) range

Title: In Java, why are nextInt() and nextDouble() instance methods of Random objects?


问:
Splitting an image into many pieces to improve perceived performance? Good or Bad?
Time to time, I have to work on a website that involves a huge background in size and resolution (1920 x 1080 in resolution, over 2mb in size). I've been using preloaders and it worked very well, except that users have to wait a little bit.

I noticed that google map splits a big image into many pieces. I researched about it and found out that it actually increases perceived performance.

Is this true?

答:
This definitely improves user perceptions.

Any time your users can see something churning on the page, they will be more inclined to wait for everything to load versus not showing them any progress and making them guess when everything will be done.

I think you are much better off loading pieces as they come available.


问:
What is the difference between an Array and a Stack?
According to Wikipedia, a stack:

is a last in, first out (LIFO) abstract data type and linear data structure.

While an array:

is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key.

As far as I understand, they are fairly similar. So, what are the main differences? If they are not the same, what can an array do that a stack can't and vice-versa?

答:
You can retrieve an item from any index of an A\array.

With a stack, you can retrieve an item in the middle of stack A, by using another stack: B.

You keep taking the top item out of A and putting it into B until you are at the desired item of A, then you put the items from B back on top of stack A.

So, for data that requires the ability to retrieve an arbitrary index, the stack is more difficult to work with.

In the situation where you want "last in, first out" behavior, a stack will give you less overhead than an array.


答:
Well, you can certainly implement a stack with an array.  The difference is in access.  In an array, you have a list of elements and you can access any of them at any time.  (Think of a bunch of wooden blocks all laid out in a row.)

But in a stack, there's no random-access operation; there are only Push, Peek and Pop, all of which deal exclusively with the element on the top of the stack.  (Think of the wooden blocks stacked up vertically now. You can't touch anything below the top of the tower or it'll fall over.)

Title: What is the difference between an Array and a Stack?

Body:
According to Wikipedia, a stack:

is a last in, first out (LIFO) abstract data type and linear data structure.

While an array:

is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key.

As far as I understand, they are fairly similar. So, what are the main differences? If they are not the same, what can an array do that a stack can't and vice-versa?


答:
I wouldn't go so far as to say they're "very similar."

An array is used to hold things that will later be accessed sequentially or through the index.  The data structure doesn't imply any sort of access method (FIFO, LIFO, FILO, etc...) but it can be used that way if you wanted.

A stack is way of track of things as they're generated.  An access method is implied / required depending upon the type of stack that's created.  A frame stack would be a LIFO example.  Disclaimer - I may be mixing my data structure taxonomy here and a stack may truly only allow LIFO.  It would be a different type of queue otherwise.

So I could use an array as a stack (although I wouldn't want to) but I can't use a stack as an array (unless I work really hard at it).


答: The data in an array can be accessed by a key or index. The data in a stack can be accessed when it is popped off of the top of the stack. This means that accessing data from an array is easy if you know its index. Access data from a stack means you have to keep popping elements until you find the one you were looking for, which means data access can take longer.</p>


问:
What is the canonical reference on probabilistic data structures?
I've heard of probabilistic data structures like Skip Lists and Bloom Filters being immensely useful and I'd like to learn more about them in general. Is there a canonical reference on the subject on the level of Cormen et al.?</p>

答:
The best list that I could find, that has probabilistic data structures is this Wikipedia page. The problem here is, the page also includes probabilistic algorithms. The list that I know of is:

Bloom Filter

Random Tree - This is a general term, and "umbrellas" many different structures.

Skip List

Treap

There are probably many more, but these are the ones that I have found or that I was aware of.


问:
Do Java, J2EE and Java Web get better with time? It still looks problematic to me after months
I'm a little new to Java Web Development. JSF, JSP, Servlets, Hibernate etc... I have really a good understanding of OOP and C++. I have years of PHP and MySQL web development experience. I also have experience with C# and ASP.NET and I'm a software engineering student.

I don't want to continue my career with PHP, since it is getting very popular, there are many people who use it and I can't really use my engineering knowledge fully with PHP. It is more basic. I need a more enterprise environment, Java EE is exactly like this.

But...

For these last weeks I was re-thinking about keeping up my progress with Java EE. I have these problems listed below, and I'd like to get your thoughts on those especially if you are an experienced Java EE developed. The most primitive question is, do they get better with getting used to Java with time, as a developer? Do you, if you are experienced in Java EE, still deal with those kinds of problems after years?

There's always a "version conflict" between jars needs to be solved.

You always get an error because of a missing or extra jar.

There are so many jar files... That is really overwhelming. I'm using Hibernate, JSF and CXF in Tomcat and I have 100+ jar files in WEB-INF/lib. The two problems above I listed increases with jars count.

Tomcat or Glassfish is not really enough for development. Especially Tomcat is worse. There are many problems. Let's say, Tomcat does not update wtpwebapps dir always. I sometimes copy-paste jars manually. Eclipse 80% of the time restarts Tomcat on saving .java files, and does not update in hot-replace mode, but sometimes do. (Yes using always in debug mode)

There are many implementations. That's fine but setting up one of them takes at least hours, or days. Like Web Services. Which implementation? I just got an error because the latest Axis2 doesn't support Dynamic Web Module 3.0.

Setting up the development environment takes hours. If I need to work on a different computer, I check out SVN repository and set up libraries in Build Path, server, and solve new dependency bugs which takes lots of time. I still have no idea how to deal with different paths of libraries on different computers (some paths are not relative like Axis2 project folder setting).

The logging system of Tomcat or Glassfish still look complicated to me after months. I get tired of checking Console tab of Eclipse if there's an error/exception. Even half of the exceptions don't clearly describe the problem.

There's no stability like Apache Web Server (or php binary in that sense) in Tomcat and Glassfish. You can very well easily crash the whole Web App Server with a tiny bug. (Even the app shouldn't get crashed. Just that request should be crashed.)

I've used PHP for years and no bugs affected my development or production. But with just 5-6 month with java I got a few bugs that slowed me down. Even Eclipse has critical bugs in its core features. (i.e. Android Emulator does not deploy my .apk file and I need to kill adb.exe everytime after I start the emulator. This is not exactly Java EE but a good example. There were other Java EE bugs I run across.)

There's always a support problem for new releases. (i. e. latest Eclipse does not support Hiberbate Tools.)

There are many configuration files everywhere.

Configuration files are really different. Even using just a logging system like log4j takes hours to understand its configuration and implementation into project system.

Those are just popped from my mind. There are of course other problems. Every language does but Java seems to me has more than others.

So, do they get better with time for me as a developer? 2-3 years later, if I continue with Java and J2EE, will I be get rid of most of those annoying things because of being more experienced?

答:
I don't want to continue my career with PHP, since it is getting very popular, there are many people who use it and I can't really use my engineering knowledge fully with php. It is more basic. I need a more enterprise environment, Java EE is exactly like this.

I really feel like you answered your own question here. You say that PHP is too basic, and J2EE is very complicated. Yet you also agree that you can't "use your engineering knowledge fully with PHP."

The tradeoff for using tools that allow you to do so many more things is that there is just going to be a lot more to learn, maintain, and master.

The J2EE platform is massive, and one could theoretically spend decades trying to learn about it. There are so many different Web containers, frameworks, methodologies, and libraries that it's impossible to know everything there is to know about it. This is where developing great, problem solving skills will really pay off.

With that said, this is something that will get easier with time as you gain more experience and knowledge of the platform and simultaneously improve your problem solving skills. You'll see similarities in one framework/server or another, and you'll enhance your problem solving abilities and learn better techniques for approaching the problems you face.

As for the maintenance aspects, like setting up Tomcat (or whatever the latest container is of the day), or setting up your development environment, you will get faster at this, but it will always take time and troubleshooting to get things working and setup the way you want to.

The tradeoff for being able to develop enterprise-level applications is that there will be more complexity, and this is why you see individual, small developers using PHP and why you don't typically see Java/J2EE used by freelance or individual developers.


答:
In response to your points:

Not for me. It probably depends on your project, and how its configured and how your workstation/dev tools are configured.

Sometimes, but it's usually very easily fixed.

100+ JARs for that setup? It's possible. I currently do most of my JavaEE development in RAD which handles all those 100's of JARs pretty easily, with one or two WS Runtimes specified in the build path.

Can't speak for this, most of my JavaEE has been on WebSphere. Which has its own problems, but they are all managable.

Days??

Hours?? Hmm I can't say I've ever had this problem. Maybe the development environments are poorly configured?

Again, I have much more experience with WebSphere and this is not a major problem.

Again, I have much more experience with WebSphere and this is not a major problem.

Many complex development tools have bugs. Maybe when you did PHP you just got lucky and didn't hit your tool's bugs? I used to do PHP in DreamWeaver and it was usually buggy as hell (worse than most versions of Eclipse or RAD). Maybe you should switch tools, to something like NetBeans or IntelliJ.

Hm I guess you could check the release notes before finding out the hard way, but yeah that can suck.

Yeah, there are. I guess if every component wants its own config file and there are many components then there will be many config files.

Maybe, but once you learn it, you've learnt it and you don't have to learn it again. I suppose if you only stick to the very basic features then this is a burden but when you need the advanced stuff, it's good to know it's out there.

It will probably get easier over time. On the other hand, it sounds like whatever you're working with is a lot nastier to work with than anything I ever worked with. So maybe the specific projects and tools and their respective setups are a major component of your headache. A badly configured development environment can make coding in any language pure hell. I've seen it on the .NET side too, but that was more a function of how the project was initially set up than with inherent problems with underlying technologies.

Title: Do Java, J2EE and Java Web get better with time? It still looks problematic to me after months

Body:
I'm a little new to Java Web Development. JSF, JSP, Servlets, Hibernate etc... I have really a good understanding of OOP and C++. I have years of PHP and MySQL web development experience. I also have experience with C# and ASP.NET and I'm a software engineering student.

I don't want to continue my career with PHP, since it is getting very popular, there are many people who use it and I can't really use my engineering knowledge fully with PHP. It is more basic. I need a more enterprise environment, Java EE is exactly like this.

But...

For these last weeks I was re-thinking about keeping up my progress with Java EE. I have these problems listed below, and I'd like to get your thoughts on those especially if you are an experienced Java EE developed. The most primitive question is, do they get better with getting used to Java with time, as a developer? Do you, if you are experienced in Java EE, still deal with those kinds of problems after years?

There's always a "version conflict" between jars needs to be solved.

You always get an error because of a missing or extra jar.

There are so many jar files... That is really overwhelming. I'm using Hibernate, JSF and CXF in Tomcat and I have 100+ jar files in WEB-INF/lib. The two problems above I listed increases with jars count.

Tomcat or Glassfish is not really enough for development. Especially Tomcat is worse. There are many problems. Let's say, Tomcat does not update wtpwebapps dir always. I sometimes copy-paste jars manually. Eclipse 80% of the time restarts Tomcat on saving .java files, and does not update in hot-replace mode, but sometimes do. (Yes using always in debug mode)

There are many implementations. That's fine but setting up one of them takes at least hours, or days. Like Web Services. Which implementation? I just got an error because the latest Axis2 doesn't support Dynamic Web Module 3.0.

Setting up the development environment takes hours. If I need to work on a different computer, I check out SVN repository and set up libraries in Build Path, server, and solve new dependency bugs which takes lots of time. I still have no idea how to deal with different paths of libraries on different computers (some paths are not relative like Axis2 project folder setting).

The logging system of Tomcat or Glassfish still look complicated to me after months. I get tired of checking Console tab of Eclipse if there's an error/exception. Even half of the exceptions don't clearly describe the problem.

There's no stability like Apache Web Server (or php binary in that sense) in Tomcat and Glassfish. You can very well easily crash the whole Web App Server with a tiny bug. (Even the app shouldn't get crashed. Just that request should be crashed.)

I've used PHP for years and no bugs affected my development or production. But with just 5-6 month with java I got a few bugs that slowed me down. Even Eclipse has critical bugs in its core features. (i.e. Android Emulator does not deploy my .apk file and I need to kill adb.exe everytime after I start the emulator. This is not exactly Java EE but a good example. There were other Java EE bugs I run across.)

There's always a support problem for new releases. (i. e. latest Eclipse does not support Hiberbate Tools.)

There are many configuration files everywhere.

Configuration files are really different. Even using just a logging system like log4j takes hours to understand its configuration and implementation into project system.

Those are just popped from my mind. There are of course other problems. Every language does but Java seems to me has more than others.

So, do they get better with time for me as a developer? 2-3 years later, if I continue with Java and J2EE, will I be get rid of most of those annoying things because of being more experienced?


问:
When comparing a string variable to a string literal with .equals(), is there a standard practice for the order of items?
There are benefits to each and I understand the differences, but what is considered best / standard practice? And why?

For example :

```<code>"myString".equals(myStringVar)
</code>```

Avoids a potential NPE and does not require a null check.  (Good thing?)

Cleaner to read since a null check is not required.

If null is not an expected value, your program could be breaking without being any the wiser.

However

```<code>myStringVar.equals("myString")
</code>```

Requires a null check if null is an expected value. (Good thing?)

Can clutter up compound conditionals with null checks.

Allows for NPE to let us know if something has broken.

Which variation is considered the standard to use for Java, and why?

答:
I suspect that this originates from a safety precaution used when programming in older C (or C++). In C, you could accidentally assign a value when you mean to test equality:

```<code>if (x = 3)
</code>```

This condition will always be true, since it's assignment x a value of 3, not testing that x is equal to 3. To avoid this subtle bugs, developers started reversing the condition:

```<code>if (3 = x)
</code>```

This contains the same "bug", but will generate a compiler error, so it's safer.

More modern languages don't have this problem, and they can easily warn you when you try to do these sorts of things. As such, it's no pretty much pure preference, so pick one, and use it consistently.

Body:
I suspect that this originates from a safety precaution used when programming in older C (or C++). In C, you could accidentally assign a value when you mean to test equality:

if (x = 3)

This condition will always be true, since it's assignment x a value of 3, not testing that x is equal to 3. To avoid this subtle bugs, developers started reversing the condition:

if (3 = x)

This contains the same "bug", but will generate a compiler error, so it's safer.

More modern languages don't have this problem, and they can easily warn you when you try to do these sorts of things. As such, it's no pretty much pure preference, so pick one, and use it consistently.


问:
How important is self-teaching in the programming field?
I'm 16. I started programming about a year ago when I was about to start high-school. I'm going for a career in programming, and I'm doing my best to learn as much as I can. When I first started, I learned the basics of C++ from a book and I started to learn things by myself from there on. Nowadays I'm much more experienced than I was a year ago. I knew I had to study by myself because high-school won't (likely) teach me anything valuable about programming, and I want to be prepared.

The question here is: how important is it to study programming by oneself?

答:
There is a good parable about it:

The annual world championship held in British Columbia. The finalists
  were Canadian, and Norwegian.

Their task was as follows. Each of them that a certain portion of the
  forest. The winner is the one who could knock down the largest number
  of trees from 8 am until four o'clock in the afternoon.

At eight o'clock whistle blew and two woodcutters took their
  positions. They cut down a tree behind a tree, while the Canadian had
  not heard that the Norwegian stop. Realizing that this was his chance,
  Canadian redoubled his efforts.

At nine o'clock in the Canadian heard that the Norwegian again went to
  work. And again, they worked almost simultaneously, when ten to ten
  Canadians have heard that the Norwegian stopped again. And again, the
  Canadian went to work, wanting to take advantage of the weakness of
  the enemy.

At ten o'clock in the Norwegian re-enter the work. Until ten minutes
  to eleven, he briefly not interrupted. With the growing sense of
  jubilation Canadian continued to work in the same rhythm, already
  feeling the smell of victory.

It lasted all day. Every hour of the Norwegian stayed for ten minutes,
  and the Canadian continued to work. When you hear about the end of the
  competition, at four o'clock in the afternoon, the Canadian was quite
  sure that the prize in his pocket.

You can imagine how he was surprised to learn that he lost.

How did that happen? - He asked the Norwegian. - Every hour, I heard you for ten minutes stops. Like, Damn you, you managed to cut more
  wood than I do? It is impossible.

In fact, everything is very simple - just said Norwegian. - Every hour, I stopped for ten minutes. And while you continue to chop wood, I was sharpening my ax.

So you should study all the time to keep your ax sharp.


答:
I think you're right in that it depends on the nullness semantics of the variable.  If you don't expect it to be null and don't have to check for and handle it then the first form is cleaner.

That said, rather than embed the string literal, a better option would probably be this:

```<code>private final String MY_STRING = "myString";
if(MY_STRING).equals(myStringVar);
</code>```

Especially if there is potential for using the string in more place than one.

Title: When comparing a string variable to a string literal with .equals(), is there a standard practice for the order of items?

Body:
There are benefits to each and I understand the differences, but what is considered best / standard practice? And why?

For example :

```<code>"myString".equals(myStringVar)
</code>```

Avoids a potential NPE and does not require a null check.  (Good thing?)

Cleaner to read since a null check is not required.

If null is not an expected value, your program could be breaking without being any the wiser.

However

```<code>myStringVar.equals("myString")
</code>```

Requires a null check if null is an expected value. (Good thing?)

Can clutter up compound conditionals with null checks.

Allows for NPE to let us know if something has broken.

Which variation is considered the standard to use for Java, and why?

Body:
I think you're right in that it depends on the nullness semantics of the variable.  If you don't expect it to be null and don't have to check for and handle it then the first form is cleaner.

That said, rather than embed the string literal, a better option would probably be this:

private final String MY_STRING = "myString";
if(MY_STRING).equals(myStringVar);

Especially if there is potential for using the string in more place than one.


答:
Standard and good practice would vary with a culture of an organisation you are working for

Our standard in .NET is myStringVar == "myString" simply because we have agreed on it, i.e. we believe it to be clean and concsice

Note: This does not apply to Java due to == comparing the references instead of the objects themselves. In Java you should be using myStringVar.equals("myString").


答:
Their responsibilities are different:

Stack must be able to pop elements onto the stack and push elements from the stack, hence why it normally has methods Pop() and Push()

Array's responsibility is to get/set element at a specified index


问:
What is "swarming"?
I've heard swarming mentioned in the context of Agile or Extreme Programming. It seems to be a complement to pairing.

What exactly is it? When should it be applied? How do you do it well?

答:
The idea is that everyone on your team works on the same story at the same time. Instead of everyone focusing on different tasks, everyone focuses on one task at a time until it's completed. Then they move on to the next thing, where they all work together on it.

This helps teams that struggle completing stories before the end of sprint. Often teams finish 80% of all the stories, but none are complete. This is less useful than completely finishing 80% of the stories, since unfinished stories have (effectively) no value to an end user. It's easier to get stories completed when everyone on the team is focusing on one story at a time. This is the motivation behind swarming.

There are some difficulties here. For instance, QA can't always test things before they are built (or even designed). In this case, you should establish a design together early on, and then QA can write (initially failing) tests against the design and not the actual implementation.

Title: What is "swarming"?


问:
Good ways to jump to a particular state in a yielding stateful function?
I'm working on some embedded code using C. Various pieces of functionality need non-blocking stateful functions, which are mostly implemented using a switch on various states. For example, a modem connection manager (pseudo-code):

```<code>void manage_connection(void) {
    static states state = IDLE;
    switch (state) {
        case IDLE:
            if (connection_requested()) state = BACKOFF;
            break;
        case BACKOFF:
            if (random_delay_timeout()) {
                do_connect();
                state = CONNECTED;
            }
            break;
        case CONNECTED:
            result = send_data();
            if (result == DATA_SENT) {
                state = IDLE;
            } else if (result == ERROR) {
                // Go straight to backoff state and connect ASAP
                state = BACKOFF;
            }
            break;
    }
}
</code>```

State machines are nasty at the best of times, so I've started to move to a different paradigm using coroutine-style functions, using a "yield" statement. Of course, C doesn't provide a "yield" statement, but I'm using protothreads to achieve this. Protothreads is great, and gives me exactly what I want to implement the above non-blocking state machine in a structured-programming style. The above function roughly translates to (pseudo-code):

```<code>void manage_connection(void) {
    WAIT_UNTIL(connection_requested()); // or, while(!condition) yield;
    WAIT_UNTIL(random_delay_timeout());
    do_connect();
    WAIT_UNTIL((result = send_data()));

    if (result == DATA_SENT) {
        // RESTART starts from top. It is part of the protothreads API.
        RESTART();
    } else if (result == ERROR) {
        // This is the part which doesn't translate so well.
        // Could use an ugly goto:
        goto backoff;
        // Or similar alternatives, none of which scale well:
        // - Set a flag to skip the states I don't want, and RESTART();
        // - Use while loops or other control logic to branch appropriately.
    }
}
</code>```

As you can see, the protothreads version is, on the whole, much clearer & simpler in terms of the flow of logic (once you learn how protothreads work, and look past some very minor boilerplate which I haven't included in the example).

But jumping to a particular state in a state machine is a common pattern that I'm come across, which the state machine version handles elegantly, but the procedural version does not. Of course, that's why the procedural version is less bug-prone and clearer -- because you can't jump all over the place on a whim (except for goto, which I'd like to avoid for the usual reasons).

However, when you have a good reason to want to jump, it adds significant bug-prone lack of clarity to what is otherwise a very straightforward function.

Obviously there are plenty ways to achieve the necessary functionality, but none of them scale well to more than a few states. Bear in mind this is the simplest possible example -- my real-world functions fill half a screen.

What are some ways to solve this problem in a way that doesn't muddy the otherwise-lucid flow of logic?

答:
First of all, thank your for let me find out protothread: very clever!  This also means, I'm everything but an expert at protothread.

I think I would write your state machine as follow:

```<code>void manage_connection(void) {
    for (;;) {
        WAIT_UNTIL(connection_requested());
        do {
            if (attempts++ >= MAX)
                RESTART();
            WAIT_UNTIL(random_delay_timeout());
            do_connect();
            WAIT_UNTIL(result = send_data());
        } while (result != DATA_SENT);
    }
}
</code>```

The whole point is that you need a conditional branch to deal with a non-linear case.  Plus, the connection attempts cannot be infinitive.

Body:
First of all, thank your for let me find out protothread: very clever!  This also means, I'm everything but an expert at protothread.

I think I would write your state machine as follow:

void manage_connection(void) {
    for (;;) {
        WAIT_UNTIL(connection_requested());
        do {
            if (attempts++ >= MAX)
                RESTART();
            WAIT_UNTIL(random_delay_timeout());
            do_connect();
            WAIT_UNTIL(result = send_data());
        } while (result != DATA_SENT);
    }
}

The whole point is that you need a conditional branch to deal with a non-linear case.  Plus, the connection attempts cannot be infinitive.


问:
Why does the add() method of a Linkedlist return true in Java?
Why does the add method of a Linkedlist return true in Java?

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#add(E)

Why not just make it a void method? I know it says "per the general contract of Collection.add", but why doesn't this contract/interface make add a void method?

答:
This is to allow referencing to LinkedList instances as List or Collection.

```<code>boolean addSomething(Collection c) {
    return c.add(null); // expects collection, with add returning boolean
}

void hackList(LinkedList list) {
    addSomething(list); // list is a Collection, OK to pass
}
</code>```

LinkedList is a List and Collection.

As for why a Collection would need to return boolean, this looks clearly explained in respective javadocs:

...Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.)...

Body:
This is to allow referencing to LinkedList instances as List or Collection.

boolean addSomething(Collection c) {
    return c.add(null); // expects collection, with add returning boolean
}

void hackList(LinkedList list) {
    addSomething(list); // list is a Collection, OK to pass
}

LinkedList is a List and Collection.

As for why a Collection would need to return boolean, this looks clearly explained in respective javadocs:

...Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.)...


问:
What are the roles of singletons, abstract classes and interfaces?
I am studying OOP in C++ and, even though I am aware of the definitions of these 3 concepts, I cannot really realize when or how to use it.

Let's use this class for the example:

```<code>class Person{
    private:
             string name;
             int age;
    public:
             Person(string p1, int p2){this->name=p1; this->age=p2;}
             ~Person(){}

             void set_name (string parameter){this->name=parameter;}
             void set_age (int parameter){this->age=parameter;}

             string get_name (){return this->name;}
             int get_age (){return this->age;}

             };
</code>```

1.Singleton

HOW does the restriction of the class to have only one object work?

CAN you design a class that would have ONLY 2 instances? Or maybe 3?

WHEN is using a singleton recommended/necessary? Is it good practice?

2.Abstract Class

As far as i know, if there's only one pure virtual function, the class becomes abstract.
So, adding

```<code>virtual void print ()=0;
</code>```

would do it, right?

WHY would you need a class whose object is not required?

3.Interface

If an interface is an abstract class in which all the methods are pure virtual functions, then

WHAT is the main difference between the 2 of them?

Thanks in advance!

答:
1. Singleton

You restrict the number of instances because the constructor will be private meaning only static methods can create instances of that class (there are other dirty tricks actually to accomplish that but let's not get carried away).

Creating a class that will have only 2 or 3 instances is perfectly feasible. You should be using singleton whenever you feel the necessity to have only one instance of that class in the entire system. That usually happens to classes that have a 'manager' behavior.

If you want to learn more about Singletons you can start in Wikipedia and particularly for C++ in this post.

There is definitely some good and bad things about this pattern but this discussion belongs somewhere else.

2. Abstract Classes

Yes, that's right. Only a single virtual method will mark the class as abstract.

You'll be using those kind of classes when you have a bigger class hierarchy in which the top classes should not really be instantiated.

Let's supposed you're defining a Mammal class and then inheriting it to Dog and Cat. If you think about it, there's no much sense to have a pure instance of a Mammal since you first need to know what kind of Mammal it really is.

Potentially there's a method called MakeSound() that will only make sense in the inherited classes but there's no common sound that all mammals can make (It's just an example not trying to make a case for mammal's sounds here).

So that means Mammal should be an abstract class since it will have some common behavior implemented to all mammals but it's not really supposed to be instantiated. That's the basic concept behind abstract classes but there's definitely more to it that you should learn.

3. Interfaces

There are no pure interfaces in C++ in the same sense that you have in Java or C#. The only way to create one is by having a pure abstract class which mimics most of the behavior you want from an interface.

Basically the behavior you're looking for is to define a contract where other objects can interact with without caring about the underlying implementation. When you make a class purely abstract it mean all implementation belongs somewhere else so the purpose of that class is only about the contract it defines. This is a very powerful concept in OO and you should definitely look more into it.

You can read about the interface specification for C# in MSDN to have a better idea:

http://msdn.microsoft.com/en-us/library/ms173156.aspx

C++ will provide the same kind of behavior by having a pure abstract class.


答:
Singleton is useful when you don't want multiple copies of a particular object, there must only be one instance of that class - it is used for objects that maintain global state, have to deal with non-reentrant code in some way etc.

A singleton that has a fixed number of 2 or more instances is a multiton, think of database connection pooling etc.

Interface specifies a well defined API that is helps model interaction between objects. In some cases, you could have a group of classes that do have some common functionality - if so, instead of duplicating it in implementations, you can add method definitions to the interface turning it into an abstract class.

You can even have an abstract class where all the methods are implemented, but you mark it as abstract to indicate it should not be used as-is without subclassing.

Note: Interface & abstract class aren't very different in the C++ world with multiple inheritance etc., but have different meanings in Java et al.

Title: What are the roles of singletons, abstract classes and interfaces?

Body:
I am studying OOP in C++ and, even though I am aware of the definitions of these 3 concepts, I cannot really realize when or how to use it.

Let's use this class for the example:

```<code>class Person{
    private:
             string name;
             int age;
    public:
             Person(string p1, int p2){this->name=p1; this->age=p2;}
             ~Person(){}

             void set_name (string parameter){this->name=parameter;}
             void set_age (int parameter){this->age=parameter;}

             string get_name (){return this->name;}
             int get_age (){return this->age;}

             };
</code>```

1.Singleton

HOW does the restriction of the class to have only one object work?

CAN you design a class that would have ONLY 2 instances? Or maybe 3?

WHEN is using a singleton recommended/necessary? Is it good practice?

2.Abstract Class

As far as i know, if there's only one pure virtual function, the class becomes abstract.
So, adding

```<code>virtual void print ()=0;
</code>```

would do it, right?

WHY would you need a class whose object is not required?

3.Interface

If an interface is an abstract class in which all the methods are pure virtual functions, then

WHAT is the main difference between the 2 of them?

Thanks in advance!


答:
WHEN is using a singleton recommended/necessary? Is it good practice?

Never. Worse than that, they're an absolute bitch to get rid of, so making this mistake once can haunt you for many, many years.

The difference between abstract classes and interfaces is absolutely nothing in C++. You generally have interfaces to specify some behaviour of the derived class, but without having to specify all of it. This makes your code more flexible, because you can swap out any class that meets the more limited specification. Run-time interfaces are used when you need a run-time abstraction.


答:
In addition to the excellent answer gnat gave, it can be useful to know that you just tried to add null to a list, and therefore did not change it.  While you could check for this separately, it's kinda nice to be able to say

```<code>if (myList.add(foo)) { doSomething(); }
</code>```

or perhaps

```<code>while (myList.add(buffer.readLine()));
</code>```

Title: Why does the add() method of a Linkedlist return true in Java?

Body:
Why does the add method of a Linkedlist return true in Java?

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#add(E)

Why not just make it a void method? I know it says "per the general contract of Collection.add", but why doesn't this contract/interface make add a void method?

Body:
In addition to the excellent answer gnat gave, it can be useful to know that you just tried to add null to a list, and therefore did not change it.  While you could check for this separately, it's kinda nice to be able to say

if (myList.add(foo)) { doSomething(); }

or perhaps

while (myList.add(buffer.readLine()));


答:
Cmd + F

Best friend I have. No more scrolling, no more browsing code to find it. Need to find a file quickly? find . | grep [filename]. Poof, there it is. Can even file name match with regex. Using TextMate? Cmd + T and Cmd + Opt + T are your friends.

Title: When programming: How much time is spend navigating/scrolling and how much typing?

Body:
When your programming you often have to go and look at other pieces of code for reference, search for something etc. I'm looking for some numbers on the ratio of time spend actually typing the code(coding) and the time spend going back and forth between other parts of the system, not even counting browsing the internet, reading documentation.

Ofcourse this depends on a large number of factors, probably also on your IDE, programming language etc. I just need some rough estimates, or researches on the subject.

Background:
I want to investigate how much network latency is tolerable for a programmer to work on virtual machines (if any).


问:
What is the Bible of Hashing?
Is there a Cormen-like reference on Hashes and Hashing? This particular structure has seen little attention in my CS education for some reason but I'd like to learn more as they seem to be everywhere. I know Cormen covers it but I'm looking for something more specialized and in-depth.</p>

答:
I really enjoyed the book File Organization and Processing. Despite it's name, it's just a book of data structures. The first half is about hashing and various collision resolution methods, and later on there is coverage of some dynamic hashing algorithms.

It's a little old but it's still useful. There are step-by-step examples for each algorithm and answers to the exercises.

Disclaimer: I'm biased because the author was one of my CS professors.

Title: What is the Bible of Hashing?


问:
Apply vs. Ok buttons
Often when configuring settings, applications have both an "Apply" and an "Ok" button. Should the "Ok" button always perform the "Apply" before closing the window out? Are there pros and cons to doing this?</p>

答:
Yes, the OK button should always "Apply". I don't see any cons, as there usually is a "abort/close window" button to revert the previous settings, in case you mis-configured something.

The optional "Apply" button should set the changes made in the current dialog without closing it. IMHO it is a convenience button, which is really useful in complex dialogs with many settings (e.g. Eclipse Preference Dialog).

Title: Apply vs. Ok buttons


答:
At this point, Ok, apply, and cancel are the equivalent of household names. So many other applications have adopted the standard that apply means just apply, ok means apply and close, and cancel means cancel and close that making an attempt to change this or "be witty" in your application is more likely to just confuse, frustrate, or cause your users to make mistakes. The psychological impact of mistakes makes your users feel bad, and they associate this bad feeling with your application, not their lack of knowledge on how it works.

As an example of this concept, one of OpenOffice's successes with Calc came about because they lowered the barriers to entry for Excel users. When I first started using Calc, I was surprised that many of the same shortcut keys worked the same in Calc, and this made it easier for me as a user to commit to using Calc.

Had OpenOffice decided to completely redo their idea of how the shortcut keys worked, OpenOffice may never have gained a successful following.

If you apply this same concept to your application, you would really want to ask yourself what you have to gain by changing something that is not only tried and tested, but that also eliminates a potential and unnecessary learning curve in your application.

Title: Apply vs. Ok buttons

Body: Often when configuring settings, applications have both an "Apply" and an "Ok" button. Should the "Ok" button always perform the "Apply" before closing the window out? Are there pros and cons to doing this?</p>


问:
Command line merge conflict tools
I sometimes prefer to work in a terminal. I use git, and sometimes have merge conflicts.  Are there any merge-conflict-resolution tools that work in a command-line only environment?</p>

答:
From the manpage of "git mergetool":

Use the merge resolution program specified by . Valid merge
  tools are: kdiff3, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff,
  ecmerge, diffuse, tortoisemerge, opendiff, p4merge and araxis.

Out of these, I know that emerge and vimdiff are command-line only. Although it is not listed, emacs' ediff can also be used as a mergetool. https://stackoverflow.com/questions/1817370/using-ediff-as-git-mergetool

I personally find that graphical tools such as meld makes things much easier.

Title: Command line merge conflict tools


答:
I personally do not like "OK" buttons.

I have seen too many "The application has messed up and all your input will be lost" messages followed by an "OK" button when it is clearly not OK.

The "OK" button is used/misused in so many different ways in so many applications that it is effectively meaningless. "Apply" and "Cancel" generally mean what they say.

Title: Apply vs. Ok buttons


问:
Interpreting gprof profiling output
I am practicing algorithm and data structures. Therefore, I keep profiling my programs. Here is an example output from gprof:

```<code>Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  ns/call  ns/call  name
 29.76      2.58     2.58                             _IO_vfscanf_internal
 14.30      3.82     1.24                             ____strtof_l_internal
 11.71      4.84     1.02                             memcpy
  7.84      5.52     0.68  8400000    80.95    80.95  insertorupdate
  5.94      6.03     0.52                             _int_malloc
  5.77      6.53     0.50                             round_and_return
  3.81      6.86     0.33                             _IO_sputbackc
  3.23      7.14     0.28                             strlen
  2.88      7.39     0.25                             __strcmp_ia32
  2.13      7.58     0.19                             __isoc99_scanf
  2.13      7.76     0.19                             fgets
  2.02      7.94     0.18                             _IO_getline_info
  1.27      8.05     0.11                             __mpn_lshift
  1.21      8.15     0.11                             __memchr_sse2_bsf
  0.87      8.23     0.08                             malloc
  ... rest ...
</code>```

But I found it hard to understand what this means. For example, my program takes a lot of time in standard functions, I guess it should be good, right? Because, if one of my functions were consuming most of the time, that could mean I was doing something wrong. But as I say, I am not sure if I am interpreting this correctly, so any suggesting or pointers reading this is welcome.

答:
If you're working with algorithms and trying to show big-O behavior, it's better to count basic operations, like comparisons or memory allocations.

What you're seeing in your gprof output is your program spends most of its time reading input.
And that's just unblocked CPU time.
It doesn't count I/O time, even though you are still waiting for it.
(And I/O is also CPU time, just with a different CPU.)
If it counted I/O time as well, you would see an even larger fraction in that code.

gprof estimates how much time each routine held the program counter.
It also counts how many times each routine was called from each other routine.
From that it tries to figure out how much time each routine was responsible for in the sense of either spending time, or causing time to be spent.
The way it calculates this is riddled with problems, as the original authors freely admitted, and it has basically stayed that way for 30 years.
It is venerable, but it is not going to tell you much that you can depend on.

Title: Interpreting gprof profiling output


答:
Swarming just refers to the fact that multiple people work together to complete a task or story. In my experience this isn't something you do often.

Typically, each member of my team works on a different task and/or different story. If someone is falling behind, or if there's a desire to finish a task or story early, other people will stop working on other tasks and "swarm" to complete the task, which means they all work together on a single task or story until it is completed.

We recently had a small number of stories that was some fairly boring, uninteresting work. I gave the team a small incentive (pizza) and deadline (end of the day) to finish the work, so they swarmed on the story and knocked out at least a couple days of work in one afternoon. They got the work done and out of the way early, then each team member went back to whatever they were working on. They got a free lunch, I got work done early that could have dragged on due to it's dull nature, and the team got ahead of their sprint. Win-win-win.

"Swarming" is nothing more than a fancy term for "hey, let us help you with that".

Title: What is "swarming"?

Body:
I've heard swarming mentioned in the context of Agile or Extreme Programming. It seems to be a complement to pairing.

What exactly is it? When should it be applied? How do you do it well?


问:
Backtracking with Killer Sudoku
I'm developing a Killer Sudoku solver for a school project. I've programmed 10 human strategies showing what they are doing in order to be the most educational possible.

It can solve hard Killer Sudokus right now but my teacher proposed that I use backtracking to solve every possible grid.

I've been trying for one week searching for general resources on backtracking or resources based on Sudoku... The fact is that with Killer Sudoku, you can't just say a cell has a solution without relying on zones and on what the previously written cells imply on zones and possibilities everywhere.

What I'd like to do is something which applies all my strategies everytime it suggests a number to be more efficient and return the only solution.

But to apply strategies, we need a copy of the grid right ? So I can clone my objects totally using some methods and I can apply my strategies using another method.

What would be the structure for this function ?

PS: I've tried several times to write some code and everytime the solution returned was incorrect. (The grid can easily be checked for validity)

It was something like this :

```<code>def bt(sudoku)
  if sudoku.valid? then
    true
  else
    sudoku2 = sudoku.clone
    sudoku2.first_cell_not_solved.possibilities.each do |p|
      sudoku2.first_cell_not_solved.solution = p
    end
    sudoku2.apply_all_strategies
    if sudoku.completed?
      return sudoku.valid?
    else
      bt(sudoku2)
    end
  end
end
</code>```

答:
It's actually easier to write an exhaustive backtracking program than it is to solve a specific Sudoku puzzle.  The algorithm is pretty simple.  You don't need to clone the grid.

```<code>value[i] = 0 for i in 0..totalCells-1;
int currentCell = 0;

while (currentCell != totalCells) {
  ++value[currentCell];
  if (value[currentCell] > 9) {
    value[currentCell] = 0; // erase
    --currentCell; // backtrack
    if (currentCell < 0) throw new UnsolvableSudokuException();
  } else if (!anyConstraintViolated) {
    ++currentCell; // advance to next cell
  }
}
</code>```

You might think this would run for a long time but even with a slower language like Perl this algorithm solves regular Sudoku in a couple of seconds.

Title: Backtracking with Killer Sudoku

Body:
It's actually easier to write an exhaustive backtracking program than it is to solve a specific Sudoku puzzle.  The algorithm is pretty simple.  You don't need to clone the grid.

value[i] = 0 for i in 0..totalCells-1;
int currentCell = 0;

while (currentCell != totalCells) {
  ++value[currentCell];
  if (value[currentCell] > 9) {
    value[currentCell] = 0; // erase
    --currentCell; // backtrack
    if (currentCell < 0) throw new UnsolvableSudokuException();
  } else if (!anyConstraintViolated) {
    ++currentCell; // advance to next cell
  }
}

You might think this would run for a long time but even with a slower language like Perl this algorithm solves regular Sudoku in a couple of seconds.


答:
If you stop to think about it, its all about the polymorphism. You want to be able to write a piece of code once that can do more then one think depending on what you pass it.

Say we have a function like the following Python code:

```<code>function foo(objs):
    for obj in objs:
        obj.printToScreen()

class HappyWidget:
    def printToScreen(self):
        print "I am a happy widget"

class SadWidget:
    def printToScreen(self):
        print "I am a sad widget"
</code>```

The good thing about this function is that it will be able to handle any list of objects, as long as those objects implement a "printToScreen" method. You can pass it a list of happy widgets, a list of sad widgets or even a list that has a mix of them and the foo function will still be able to correctly do its thing.

We refer to this type restriction of needing to have a set of methods implemented (in this case, printToScreen) as an interface and objects that implement all the methods are said to implement the interface.

If we were talking about a dynamic, duck-typed language like Python we would basicaly be over by now. However, C++'s static type system demands that we give a class to the objecs in our function and it will only be able to work with subclasses of that initial class.

```<code>void foo( Printable *objs[], int n){ //Please correctme if I messed up on the type signature
    for(int i=0; i<n; i++){
        objs[i]->printToScreen();
    }
}
</code>```

In our case, the only reason the Printable class exists is to give a place for the printToScreen method to exist. Since there is no shared implementation between the classes that implement the printToScreen method, it makes sense to make Printable into an abstract class that is only used as a way to group similar classes in a common hierarchy.

In C++ the absctract class and interface concepts are a little bit blurry. If you want to define them better, abstract classes are what you are thinking about, while interfaces usualy mean the more general, cross-language idea of the set of visible methods an object exposes. (Although some languages, like Java, use the interface term to refer to something more directly like an abstract base class)

Basically, concrete classes specify how objects are implemented, while abstract classes specify how they interface with the rest of the code. To make your functions more polymorphi, you should try to receive a pointer to the abstract superclass whenever it would make sense to do so.

As for Singletons, they really are quite useless, since they can often be replaced by just a group of static methods or plain old functions. However, sometimes you have some sort of restriction that forces you to use an object, even though you wouldnt really want to use one, so the singleton patter is appropriate.

BTW, some people might have commented that the word "interface" has a particular meaning in the Java language. I think its better to stick with the more general definition for now though.

Body:
If you stop to think about it, its all about the polymorphism. You want to be able to write a piece of code once that can do more then one think depending on what you pass it.

Say we have a function like the following Python code:

function foo(objs):
    for obj in objs:
        obj.printToScreen()

class HappyWidget:
    def printToScreen(self):
        print "I am a happy widget"

class SadWidget:
    def printToScreen(self):
        print "I am a sad widget"

The good thing about this function is that it will be able to handle any list of objects, as long as those objects implement a "printToScreen" method. You can pass it a list of happy widgets, a list of sad widgets or even a list that has a mix of them and the foo function will still be able to correctly do its thing.

We refer to this type restriction of needing to have a set of methods implemented (in this case, printToScreen) as an interface and objects that implement all the methods are said to implement the interface.

If we were talking about a dynamic, duck-typed language like Python we would basicaly be over by now. However, C++'s static type system demands that we give a class to the objecs in our function and it will only be able to work with subclasses of that initial class.

void foo( Printable *objs[], int n){ //Please correctme if I messed up on the type signature
    for(int i=0; i<n; i++){
        objs[i]->printToScreen();
    }
}

In our case, the only reason the Printable class exists is to give a place for the printToScreen method to exist. Since there is no shared implementation between the classes that implement the printToScreen method, it makes sense to make Printable into an abstract class that is only used as a way to group similar classes in a common hierarchy.

In C++ the absctract class and interface concepts are a little bit blurry. If you want to define them better, abstract classes are what you are thinking about, while interfaces usualy mean the more general, cross-language idea of the set of visible methods an object exposes. (Although some languages, like Java, use the interface term to refer to something more directly like an abstract base class)

Basically, concrete classes specify how objects are implemented, while abstract classes specify how they interface with the rest of the code. To make your functions more polymorphi, you should try to receive a pointer to the abstract superclass whenever it would make sense to do so.

As for Singletons, they really are quite useless, since they can often be replaced by just a group of static methods or plain old functions. However, sometimes you have some sort of restriction that forces you to use an object, even though you wouldnt really want to use one, so the singleton patter is appropriate.

BTW, some people might have commented that the word "interface" has a particular meaning in the Java language. I think its better to stick with the more general definition for now though.


问:
REST & Grails- A solution in search of a problem?
Over the past week, I've been struggling to adapt a Grails application to use the REST architecture.  Problem is, I've had nothing but trouble throughout.

For this application, the choice between using XML and JSON literally came down to a coin flip.  Neither format offered much over the other, so I went with XML.

Writing the URL redirects and the controller methods was relatively easy and got me interested. The problems came when actually doing stuff with the new controller functions.  Specifically, two major issues came to light

First, the list view of an object works with the regular CRUD method.  Adapting to REST required executing a query to get all objects, count them up and render the output as both HTML and XML using the withFormat method.

HTML view shows absolutely nothing in the way of listings, but the XML tree shows up when I comment out the HTML section in withFormat.  So I know that part's working.

Secondly, what to do when a premature end of XML file exception comes at you when its the machine creating the XML in the first place?

At this point, to me at least, REST seems like more of a solution in search of a problem.  It essentially co-opts the HTTP functions for its own use, when controller redirects seem to work fine.

Is it a scalability adaptation?

答:
REST is not a solution, it's a convention, and as such, it is subjective.

Which is more readable?

REST:

```<code>PUT /users/profile/1234
{userName:fooBar,...}
</code>```

Non REST:

```<code>POST /userController.go?action=updateUser&userId=1234&userName=fooBar...
</code>```

It's up to you to decide what you prefer

Body:
REST is not a solution, it's a convention, and as such, it is subjective.

Which is more readable?

REST:

PUT /users/profile/1234
{userName:fooBar,...}

Non REST:

POST /userController.go?action=updateUser&userId=1234&userName=fooBar...

It's up to you to decide what you prefer


问:
Alternatives to the singleton pattern
I have read different opinions about the singleton pattern.
Some maintain that it should be avoided at all costs and others
that it can be be useful in certain situations.

One situation in which I use singletons is when I need a factory
(let's say an object f of type F) to create objects of a certain class A.
The factory is created once using some configuration parameters and then
is used each time an object of type A is instantiated. So every part of
the code that wants to instantiate A fetches the singleton f and create
the new instance, e.g.

```<code>F& f                   = F::instance();
boost::shared_ptr<A> a = f.createA();
</code>```

So the general my scenario is that

I need only one instance of a class either for optimization reasons (I do not need multiple factory objects) or for sharing common state (e.g. the factory knows how many instances of A it can still create)

I need a way to have access to this instance f of F in different places of the code.

I am not interested in the discussion whether this pattern is good or bad,
but assuming I want to avoid using a singleton, what other pattern can I use?

The ideas I had were (1) to get the factory object from a registry or
(2) to create the factory at some point during program start up and then
pass the factory around as a parameter.

In solution (1), the registry itself is a singleton, so I have just shifted
the problem of not using a singleton from the factory to the registry.

In case (2) I need some initial source (object) from which the factory object
comes so I am afraid that I would again fall back to another singleton
(the object that provides my factory instance).
By following back this chain of singletons I can maybe reduce the problem
to one singleton (the whole application) by which all other singletons
are directly or indirectly managed.

Would this last option (using one initial singleton that creates all other
unique objects and injects all other singletons at the right
places) be an acceptable solution?
Is this the solution that is implicitly suggested when one advises not to
use singletons, or what are other solutions, e.g. in
the example illustrated above?

EDIT

Since I think the point of my question has been misunderstood by some,
here is some more information. As explained e.g. here, the word
singleton can indicate (a) a class with a single instance object and
(b) a design pattern used to create and access such an object.

To make things clearer let us use the term unique object for (a) and
singleton pattern for (b). So, I know what the singleton pattern
and dependency injection are (BTW, lately I've been using DI heavily
to remove instances of the singleton pattern from some code I am working on).

My point is that unless the whole object graph is instantiated from
a single object living on the stack of the main method, there will always be
the need to access some unique objects through the singleton pattern.

My question is whether having the complete object graph creation and
wiring depend on the main method (e.g. through some powerful DI framework
that does not use the pattern itself) is the only
singleton-pattern free solution.

答:
If your needs from the singleton can be boiled down to a single function, why not just use a simple factory function? Global functions (probably a static method of class F in your example) are inherently singletons, with uniqueness enforced by the compiler and linker.

```<code>class Factory
{
public:
    static Object* createObject(...);
};

Object* obj = Factory::createObject(...);
</code>```

Admittedly, this breaks down when the operation of the singleton cannot be reduced to a single function call, though perhaps a small set of related functions might get you by.

All that being said, items 1 and 2 in your question make it clear that you really just want one of something. Depending on your definition of the singleton pattern, you are either already using it or very close. I don't think you can have one of something without it being a singleton or at least very close to one. It's just too close to the meaning of singleton.

As you suggest, at some point you have to have one of something, so perhaps the problem is not having a single instance of something, but of taking steps to prevent (or at least discourage or minimize) abuse of it. Moving as much state out of the "singleton" and into parameters as possible is a good start. Narrowing the interface to the singleton also helps, as there are fewer opportunities for abuse that way. Sometimes you just have to suck it up and make the singleton very robust, like the heap or the filesystem.

Title: Alternatives to the singleton pattern

Body:
If your needs from the singleton can be boiled down to a single function, why not just use a simple factory function? Global functions (probably a static method of class F in your example) are inherently singletons, with uniqueness enforced by the compiler and linker.

class Factory
{
public:
    static Object* createObject(...);
};

Object* obj = Factory::createObject(...);

Admittedly, this breaks down when the operation of the singleton cannot be reduced to a single function call, though perhaps a small set of related functions might get you by.

All that being said, items 1 and 2 in your question make it clear that you really just want one of something. Depending on your definition of the singleton pattern, you are either already using it or very close. I don't think you can have one of something without it being a singleton or at least very close to one. It's just too close to the meaning of singleton.

As you suggest, at some point you have to have one of something, so perhaps the problem is not having a single instance of something, but of taking steps to prevent (or at least discourage or minimize) abuse of it. Moving as much state out of the "singleton" and into parameters as possible is a good start. Narrowing the interface to the singleton also helps, as there are fewer opportunities for abuse that way. Sometimes you just have to suck it up and make the singleton very robust, like the heap or the filesystem.