答:
For your Kindle, you should find a publisher who publishes in Mobi format. See the bottom of my post for some recommendations. I have a Kindle too, and the Mobi-format ebooks work really well on it.

I use Ibis Reader as my main ebook reader. It's a web-based reader, which means you can use it on your computer, mobile devices, etc. (I haven't yet tried it on my Kindle, but I mean to....)

I like three things in particular: navigation is easy (use left/right arrow keys, or tap the left/right margins), it has a "No Distractions" mode (no on-screen nav, just text), and you can bookmark pages to get back to (re Mark Trapp's answer). (You can always return to the nav if you want to jump to a specific section that you haven't got bookmarked, of course.)

It will also remember your last-read place, so that when you come back to the site, you will pick up where you left off, even if you're connecting from a different device.

Ibis Reader supports ePub books only, and does not support Mobi, PDF, etc. However, many tech ebook publishers, especially O'Reilly and Pragmatic (and an increasing number of Pearson titles, and soon Manning too), sell most (all?) of their catalogue in all three formats, so you're all set.

Title: eBook editions of programming books

Body:
(I'll get my justification for why this is on topic in early: programming books tend to have fairly specific formatting needs - code samples, tables, images and graphs - which are not common to all book types and are not necessarily well handled by eBook readers.  Similarly they're used in different ways - you often dip in and out rather than read cover to cover.)

I've just noticed that Don't Make Me Think by Steve Krug is available as an eBook edition for the Kindle (and presumably also for other readers) which set me thinking.

There are certain advantages to eBook readers for tech books - primarily that you can carry a massive library of what would be heavy physical books around very easily.  The downside is that certain eBook readers allegedly aren't particularly well equipped to cope with tables, code samples and so on and a book like Don't Make Me Think presumably makes extensive use of these sorts of things.

So, the question, what are your experiences of reading and using programming books on an eBook reader and would you recommend it? I'm specifically interested in the latest generation Kindle but happy to hear about all devices - might be useful to state which one you use in the answer.


问:
Micro-services architecture and reporting services?
as I understand it micro-services are autonomous and have complete control over their own data and therefor each micro-service has a dedicated database.

I was wondering what would be the approach to implement reporting in a micro-services architecture, if reports depend on data that exists in multiple databases where each database is governed by its own micro-service.

答:
Yes, micro-services should operate on their own datasets, but this doesn't have to mean individual databases, it can be schemas or even just a few tables in an existing DB. Just as long as you know who has ownership over what data, you should be good.

But reporting... typically this does not occur on the live databases, you would extract data from the main DBs to a reporting DB where you run all manner of slow and intensive queries. How you get the data extracted is up to you - either a dedicated SQL task, or you have a method on your services that exports data for import into the report DB.

ContentLicense: CC BY-SA 3.0


问:
FP and board game state
I wanted to implement the game of Tic Tac Toe using a functional language (in my case, Scala) but I'm unsure how to go about managing the board game state after each player makes their move.

I understand that FP avoids mutating global state, but how does this work in the case of a board game?

答:
State + move = new state

Both old state and new state are immutable. Move doesn't mutate board state, but creates a copy of the old state with move added.

Imagine an inefficient implementation where board state is just a linked list of moves taken and each new move just adds another head to the linked list. For instance if I am holding a reference to a specific head of linked list of 5 moves (representing board state), adding more moves doesn't change anything as far as that value is concerned, it still points of a list of 5 moves even if the whole list is now 9 moves long. Immutability.

Title: FP and board game state


问:
Qt's future in the light of Nokia-Microsoft partnership
In case you missed it, a lot has happened in the last two day that could potentially impact the Qt framework, for the worse. :-( It will impact the mobile sector in several and probably not currently acknowledged ways, for sure.

It started yesterday with Nokia's CEO Stephen Elop internal letter depicting Nokia sitting on a burning platform and the need for a big and aggressive shift in business.

A day later, at the Nokia World conference, Nokia announced the partnership with Microsoft, which at the moment resumes to Nokia adopting the Windows Phone 7 platform and development environment, dumping Symbian along the road and tagging Meego as R&D(a pretty dangerous keyword if you ask me), as for Maemo/N900 series I guess it's bye bye for good. I know what you're thinking but no, Qt is not going to be ported to the Window Phone platform. And I'm also scared about this. You can watch the Elop & Ballmer joint press release here.

Now after reading this huge thread on the Qt-interest mailing list I can't help but wonder, what is the future of Qt at Nokia, now that they aren't focused(at all?) on Qt anymore(remember the full focus switch on Qt as main development framework for all Nokia products(including Symbian, yes) back in October?).

I love Qt, in my opinion it is the only true cross-platform application development framework and one of the few to make C++ development a joy(to the extent possible) and good things has happened to the framework and considerable momentum while under Nokia, thus i am wondering, what are the chances that Qt might suffer a slow death at Nokia after this? Yes i know about KDE.org and the fact that Qt is easily spawnable, but I still feel uneasy.

It also must be horrible for all of the efforts either by Nokia employees or third parties that have gone into Symbian and all of the Ovi Store Symbian/Qt content and business and why not, Maemo/Meego. There are also massive layoffs planned, I suspect Symbian techs and Qt?

I'd love to hear your input on this? Is Qt future safe&proof?

LE: The question as been gradually revised, improved and better referenced, thus you might want to throw a quick re-read to see what you might have missed.

答: Digia bought Qt from Nokia in 2012. They are focused on the mobile market and QML, but Qt Widgets and the C++ API are still supported. Qt's future is safe&proof.</p>

ContentLicense: CC BY-SA 2.5


问:
how to find out if spelling mistakes in source code are a serious issue or not?
I find very troubling amount of spelling mistakes I see everyday in our codebase, from which I will reproduce a very short but representative example:

```<code>ArgumnetCount
Timeount
Gor message from queue
</code>```

Unfortunately this is in no way limited to one person. There is a lot of non-native English speakers in our team who contribute to that, however I can also pinpoint some of the worst spelling mistakes to our Software Architect who is American, born and raised.

These are also to be found even in emails, presentations, documents, whatever piece of written information we have in a software development company.

I'd like to know how to find out if it is a serious issue or not?

I've always met these spelling mistakes with concern, but my own, personal, official policy is that we are not paid to spell things right, we are paid to get things done, so inside the company I never really criticized anyone about it. But I have raised this issue with some of my close friends, and never settled it for good.

答:
I have a maxim: Tidy code does not necessarily mean a tidy mind, but the obverse is certainly true: untidy code, untidy mind.

A programmer who doesn't take the time to name variables correctly and spell comments correctly is almost certainly not taking the time to do anything else correctly. Whether the programmer is a native English speaker is not a real issue, since issues with his English can (and should) be addressed during peer review.

Yes, it is a serious issue for the product, for the team and for the individuals.

For the product: correction may introduce defects which are only caught by customers

For the team: the team spends time fixing sloppy coding rather than creating value

For the individuals: bad spelling makes you look stupid and lowers your professional standing among your peers.


问:
Black box or white box testing - which do you do first?
On a very small team, where the black box and white box testing is done by the same person, which should the tester do first?</p>

答:
Black box.

White box components are usually dependent on black box components, so I would want to test the black box first and then move on to the white box.


问:
Initialize object from SqlDataReader
As of now, we have two different styles of object intializations based on SQL row in our codebase:

```<code>public Config(SqlDataReader sdr) {
    for (int i = 0; i < sdr.FieldCount; i++) if (!sdr.IsDBNull(i)) {
        switch (sdr.GetName(i)) {
            case 'Id': Id = sdr.GetInt32(i); break;
            ...
        }
    }
}
</code>```

and

```<code>public User(SqlDataReader sdr)
{
    UserId = sdr.GetInt32(0);
    if (!sdr.IsDBNull(1)) Name = sdr.GetString(1);
    ...
}
</code>```

They are called like this:

```<code>while(sdr.Read()) users.Add(new User(sdr));
</code>```

C# coding guide says that style should be consistent, so one of them has to change to the other, if we don't find a reason to keep them different. So, before we implement the whole project with its 50+ models, we need a design guideline regarding this.

Both designs have their drawbacks, but I don't know how to make it better:

In the first, no one will notice until later in the code if required fields are dropped from the query.

The second one will fail whenever the fields in the query are reordered.

Which one should we prefer, or how could we improve them to address the drawbacks? Are they really drawbacks, in terms of code maintenance/reuse?

答:
Both options have drawbacks: the first depends on the "magic string" of the column name, the second depends on the "magic number" of the column index. A good suite of automated unittests could cover either usage and help a great deal in preventing breaking changes though...

I would personally favor the first for a number of reasons, but they are probably very personal. (Actually, I would prefer NOT to write this kind of code and use an OR/M but that does not make this question any less valid)

Searchable field names

Field names can be found using Find in Files. 'Id' is obviously very generic, but I imagine if you want to remove a column called 'OrderPaymentTerm' you could easily look for the usages in the code. Or even better, put the field names in constants that are part of the class that creates the query. That way, field names and usages are right beside each other.

Required field validation is easy

If you want to make sure all the fields are present in the query, simply keep a list of fields that you read from the SqlDataReader and throw an exception if a field is missing.

Column order should not matter

Nobody expects a change in the ordering of columns in a SELECT clause to be a breaking change. And if you use SELECT * FROM, you can't control the ordering of the columns anyway.

Removing a column is less painful

If you remove the sixth column in a ten-column SELECT, you have to update all the indexes in the second case. Painful, and prone to error.

Title: Initialize object from SqlDataReader


问:
Can tools.jar from OpenJDK can be installed in public repository
Is it legal to install tools.jar from OpenJDK in public maven repository? I found at least three topics on the Internet which conclusion was that such action is forbidden for jar provided by Oracle, but can't find anything about OpenJDK. Any help appreciated.</p>

答:
If you want an opinion that you can rely on, ask a lawyer.

OpenJDK is licensed under the GPL (v2) with some exceptions.  The GPL explicitly allows distribution of the software, including works (such as binaries) derived from the software.  The exceptions don't change this.

Historically, this was not true.  But it is now.

See point 1.


问:
Which is the convention in Rails to perform calculations and display the results?
So I'm working on a personal project on Rails to learn more about this framework, and I wanted to add a feature in which the user choose a particular record from the view, and after some calculations are made (which involves an array of 80 integers) I show the result... And because I find it looks ugly in the way I did I just wondered what was the convention to do this kind of things...

In detail what I do is show you a list of records to the user, the
user selects a record and a number, and then click the "Calculate exp" button...

Then in the controller I check if the parameters exist, if they exist then I define the array and do the calculations based on the input number, on the record attributes and the array (the array never changes and could be defined as a constant in fact) that I define in the controller, and at the end I assing the result to an instance variable.

Finally the result is shown on the same page, only if the instance variable that hold the result and is defined on the controller (after checking that the parameters exists) exists.

So my question is if I'm doing it the right way (is my first time trying to do something "serious" with rails and I don't know if I'm doing it right, especially by declaring an array of 80 elements in the controller, I don't like how it looks and I don't feel it's right.).

答:
I would say this is fine.  You are using view templates, interacting with a controller, that's all good.

You might want to consider having a model and using that for the static data.  Models will normally be database backed "Active Record" objects but do not have to be, they can also be used to hold the kind of data you have.


问:
How to merge two functions that do same things with different variables
I have these two Javascript functions that are equal except for the variables

```<code>onClickVoteUp: function (e) {
    var $target = $(e.target);
    var upvoted = this.model.get("upvoted");
    var downvoted = this.model.get("downvoted");
    this.$el.find(".active").removeClass("active");
    if(!upvoted){
        if(downvoted) {
            this.model.set("downvoted", false);
            this.model.upvote();
        }
        this.model.upvote();
        this.model.set("upvoted", true);
        $target.addClass("active");
    } else {
        this.model.set("upvoted", false);
        this.model.downvote();
    }
},
onClickVoteDown: function (e) {
    var $target = $(e.target);
    var upvoted = this.model.get("upvoted");
    var downvoted = this.model.get("downvoted");
    this.$el.find(".active").removeClass("active");
    if(!downvoted){
        if(upvoted){
            this.model.set("upvoted", false)
            this.model.downvote();
        }
        this.model.downvote();
        this.model.set("downvoted", true);
        $target.addClass("active");
    } else {
        this.model.set("downvoted", false);
        this.model.upvote();
    }
}
</code>```

They are events handlers and as you can see they only have different variable, but the algorithms are the same. How would you write only one function to optimize the code?

答:
You cannot write only one function.  You will still need to have a separate function for each event handler, so the best you can do is to have 3 functions whose total amount of code will be less than what you currently have because it will not contain duplicated code. It will not perform faster, but it will be smaller.

So, what you need to do is to extract the common functionality of those two event handlers into a separate, "common" function, and have each event handler call the common function passing it additional parameters telling it how you want it to work.  I am not going to show you code, because this is "Programmers SE", not "Stackoverflow", but I will give you the general direction of thinking:

You need to stop thinking about "upvoting" and "downvoting", and instead start thinking about simply "voting" in a direction which may be either "up" or "down".  This way, the direction can become a variable of your "common" function.

By looking at your code I see that there are a few things that depend on this direction, which you will have to parametrize based on the value of "direction".  One is whether to use the "upvoted" or "downvoted" string literal, and the other is whether to invoke model.upvote() or model.downvote().

From what I know it is possible to pass a method reference to a function in javascript, so that your handler can tell the common function which method of model to invoke, but it would really help if your model exposed a vote(direction) method instead of two separate upvote() and downvote() methods.

You might even need a fourth little helper function, which returns the opposite direction from the direction that you pass to it, so that if you pass it "up" it returns "down", and if you pass it "down" it returns "up".


答:
Whatever must be most correct.

Seriously, white-box testing (i.e. testing the internals of code) should ideally be done with unit tests by the developer who wrote the code.  Unit tests would be built up over time, and part of the build process so we don't waste the poor tester's time with code we know doesn't work as it should.  Unit testing becomes more important the smaller your team is--particularly because you don't have an army of testers to shake problems out.

Black-box testing (i.e. testing through the user/system interface) is typically what most testers do.

All testing needs to be prioritized on how critical a function is for the finished product.  If the mission is to provide a tool to do X and the product doesn't do X, that's a big problem.

Title: Black box or white box testing - which do you do first?

Body: On a very small team, where the black box and white box testing is done by the same person, which should the tester do first?</p>


问:
Is it bad practice to make methods public solely for the sake of unit testing?
I have a class with a public method. It has other methods that 'assist' with the purpose of the public method. The public method must be tested. However, I also want to unit test the private methods.

It would be impossible for my unit tests to call private methods and test them in isolation, so they must be public.

The problem here is that I'm left with code that, I feel, has been written with a lack of respect for OOP convention, purely for the sake of being able to unit test it.

Am I right in amending the access of methods purely for 'testability'? Or should I be rethinking and refactoring the structure as a whole to separate out the functionality of the private methods (despite the fact they don't do a lot at all and may, at times, resemble small helper methods)?

答:
Making the methods public - yes, that is bad practice. Making them internal - that depends.

Instead of making all methods to be tested public, and instead of redesigning your classes completely, sometimes the most pragmatic solution is to make the methods in stake "internal" and use the "InternalsVisibleTo" attribute to allow your unit tests access them. That may  not lead to the ideal design in the first place, but sometimes you just have to get things done, and testing "internal" code is often better than having no tests at all or introducing accidentally new bugs by refactoring those private methods out to separate classes without having any unit tests written before.

See also How to define implementation details?


问:
Portable Data in C# App
I have developed a C# front end app for management of an SQL Database for the purposes of document control.  The project this database is for has several consultants and a client spread in a variety of geographic locations.  Security concerns mean that probably finding an internet connected database will not be a good solution.  I am looking for a way to provide the ability for the client and other consultants to have access to the data, for browsing purposes more than anything, but am interested in perhaps being able to sync changes made by others back into the main database down the road.

The firm I am with is an Architecture firm and we use Revit for our modeling and production of drawings.  Revit is interesting as an application because the documents are used as relational databases.  So it occurred to me that perhaps I can have my application create a document that is really a relational database, and can provide an application to read and manipulate the data, and provide the data as a document, to the other players.  Then they won't need access to the actual SQL Server database, but can see the data as it was when the "data document" was created.

Then I considered serialization.  Basically, if I just write a serialized form of the data from my application to a document, and then provide a similar application that simply populates the model from the document rather than the database, it accomplishes the same thing.  Since I am using ObservableCollections, Linq, and MVVM practices, I can even reuse much of the code between the two applications.

So what are the advantages with the portable relational databases that I would lose with the serialized data?  And does anyone know how Revit manages to do this?  I don't think it is an SQLLite or NoSQL solution, as I don't see any of the databases associated with that installed on the Revit machines.

答:
I do not know Revit, but MS Access provides this functionality (treating documents as relational data) for more than 20 years. The main advantages over serialization are

external data: you can retrieve and manipulate data in portions, you do not have to load 1GB of data to change just one single character in a single record.

parallel access by different processes.

indexing capabilities (you can simulate this using in-memory dictionaries, but that might be getting more complex than indexing provided by a database)

meta data: every relational DB, even lightweight ones, allow you to define a database schema, and query it also. In case of MS Access, for example, you can use the Access front end application and inspect the DB schema, define datatypes, add a description to each field, add a graphical schema, and so on.

depending one the db system, you get some goodies like views or constraints.

I think most of these points are also valid for SQLite.

Title: Portable Data in C# App


问:
Is it good Python style to write a function that has no effect other than potentially raise exceptions?
Sometimes I find myself writing Python code that looks like this:

```<code>def check_stuff(param):
    if condition1(param):
        return "condition1" # These might be enum values, etc., instead of strings
    if condition2(param):
        return "condition2"

def func(param):
    cs = check_stuff(param)
    if "condition1" == cs:
        raise Exception1(param)
    if "condition2" == cs:
        raise Exception2(param)
    #...
</code>```

Here, the return value of check_stuff is only used to decide what exception to raise. Let's imagine that this is true of every time I call check_stuff, probably because I only call it once. Would it be better style to just raise the exceptions in check_stuff itself?

```<code>def check_stuff2(param):
    if condition1(param):
        raise Exception1(param)
    if condition2(param):
        raise Exception2(param)

def func2(param):
    check_stuff(param)
    #...
</code>```

答:
No, it would be worse

functions should tell what they do. With a good naming, your check_stuff function indicates what it does. It should therefore be named e.g. checkConditionsValid depending on what it actually does. I suppose your function func also returns something or has some side effect in case that the conditions are. If not, that would be a design flaw, not the check_stuff function.

Use dependency injection. Instead of heaving check_stuff rely on some global variable, pass the conditions to it as arguments. It not only makes your code easier to reason about it also makes it more readable.


答:
Maybe

It can work to externalize validation logic as long as it is not externally visible and is used to enforce preconditions.

Say you have an object that operates on a database connection, and most of its functions require that the connection be set up and initialized. Rather than checking the connection and conditionally throwing an exception in each function, have one function that checks the connection which is called by each method that uses the connection before it is used. This realizes DRY and helps ensure consistency.

For this to work well, the validation method and the state it checks should be private to the object. This prevents other objects (including subclasses) from causing it to violate preconditions.

Title: Is it good Python style to write a function that has no effect other than potentially raise exceptions?

Body:
Sometimes I find myself writing Python code that looks like this:

```<code>def check_stuff(param):
    if condition1(param):
        return "condition1" # These might be enum values, etc., instead of strings
    if condition2(param):
        return "condition2"

def func(param):
    cs = check_stuff(param)
    if "condition1" == cs:
        raise Exception1(param)
    if "condition2" == cs:
        raise Exception2(param)
    #...
</code>```

Here, the return value of check_stuff is only used to decide what exception to raise. Let's imagine that this is true of every time I call check_stuff, probably because I only call it once. Would it be better style to just raise the exceptions in check_stuff itself?

```<code>def check_stuff2(param):
    if condition1(param):
        raise Exception1(param)
    if condition2(param):
        raise Exception2(param)

def func2(param):
    check_stuff(param)
    #...
</code>```


答:
Yes, a function that just raises an exception is OK.

You can easily have functions like ensureWellFormed(email_address) or http_request.ensureUserLoggedIn() that raise well-documented exceptions. This de-clutters code, and many high-profile projects, e.g. Django, do use this style here and there.

If you use this approach, make sure your exception objects carry enough context data to understand and report what happened in an exception handler. 'User has no access to the URL requested' is nigh useless; 'User joerandom has no access to URL /foo/bar' is quite useful.

No, a parameterless function working with global state is a bad idea.
Your example code shows functions that check global state. Referring to global state implicitly is usually a very bad idea. It creates hard-to-detect dependencies. If you happen to alter global state, especially implicitly, it creates weirdest, hard-to-detect bugs. Code that refers to global state is hard to test and hard to refactor, too. The global-state approach may appear easier now, but in a slightly longer term it will bite painfully. Note how in my examples above either a parameter is passed to a function for checking, or an object instance is used (which is also passed to a method as the self parameter).


问:
Is it worth even checking to see if Guid.NewGuid() is Guid.Empty?
In one of the projects I'm working on the following pattern is seen on a fairly regular basis:

```<code>var guid = Guid.NewGuid().ToString();
while (guid == Guid.Empty.ToString())
{
    guid = Guid.NewGuid().ToString();
}
</code>```

While I understand that a a GUID is not guaranteed to be unique and as per the MSDN documentation a generated GUID may be zero, is this a practical consideration actually worth sending cycles testing for both in the computational sense and in terms of developer time thinking about it?

答:
Look at the source code of Guid.NewGuid method:

```<code>public static Guid NewGuid() {
    Contract.Ensures(Contract.Result<Guid>() != Guid.Empty);
    ...
}
</code>```

See the code contract? The Guid.NewGuid method never gives an empty GUID.

Body:
Look at the source code of Guid.NewGuid method:

public static Guid NewGuid() {
    Contract.Ensures(Contract.Result<Guid>() != Guid.Empty);
    ...
}

See the code contract? The Guid.NewGuid method never gives an empty GUID.


问:
Algorithm or domain for finding cheapest subgraphs that connect vertex pairs
I am currently working on a project inspired by the Ticket to Ride board game.  This board game is played on an undirected graph where each vertex represents a city and each edge represents a claimable train line connecting two cities.  Players get points by claiming an edge for themselves, scoring points based upon how many cars the route requires to claim.  There are also tickets that give bonus points if the player is able to claim a path that connects the two cities.  Each player has only 45 cars, so this is a resource allocation problem.

I am trying to write a program that helps agents (humans or AIs) plan which routes to take based upon which tickets that agent needs to complete, which routes the agent has already claimed, and which routes are unavailable due to other players having claimed them.  I need an algorithm that finds a set of subgraph(s) such that each ticket has its city in the same subgraph while trying to optimize some criteria (minimum car usage, maximum points per car, etc.).  I do not care whether the algorithm gets all the cities in one subgraph, or whether it strings them all out in a line without branching (which would help toward getting the Longest Route bonus); I want something that enables the agent to complete the tickets quickly so he can start working on new ones.

The problem is that I do not have enough familiarity with graph theory to know the name for this type of problem.  I have tried searches with text that describes what I am trying to do with no luck.  I have also looked in my old textbooks (Introduction to Algorithms and Algorithms in C: Part 5 - Graph Algorithms) to try to find a graph problem domain that seems to relate to my issue; the closest seems to be network flow, but that does not seem to be close enough.

I have tried solving this problem on my own.  I wrote an A* that scored each set of subgraphs based upon the estimated minimum distance to a node, but it did not work (as I would have discovered if I had read the Wikipedia article on A* first).  I wrote an NSGA-II implementation to try to solve the problem stochastically, but it oddly seems to do worse the closer the initial set of owned edges is to connecting the tickets.  In fact, the NSGA-II implementation "freaks out" and finds very strange routes to connect subgraphs when only one route that earlier calls to the algorithm recommended.

Could someone either tell me the name of this domain so I can start doing research, point me to an algorithm, or propose an algorithm that I could try?

答: It sounds like a combinatorial optimization problem. I would start by reading about branch and bound, and other techniques used in that type of problem. Your representation of a point in the problem space (the current combination) may have an effect on efficiency. If you can create a compact representation, you can compare points, and avoid redundant branch traversals in the tree of combinations. Your cost function is also very important: that is, how good a particular combination (branch) is so far, compared to others.</p>


答:
You first do white testing thinking as a coder/developer to make sure things will work fine.
Then you do black box testing usually trying to think as if you were the end user, without thinking on the internal structure of the program. Sometimes you need to think like a coder/developer even if you are doing a black testing because you might be testing an internal module that was written by another person and you dont have access to the code.</p>


问:
PHPUnit > Best approach to mock container objects? (e.g. $item->id)
I'm using PHPUnit test doubles to mock models, libraries etc. But when I want to return an array perhaps of container objects, how best to do so. Here is what I'm currently doing:

```<code>/**
* This is just a mock of the response from http client
*/
class Container {
    public $values;

    public function __construct($values) {
        $this->values = $values;
    }

    public function __get($name) {
        return (isset($values[$name])) ? $values[$name] : null;
    }

    public function __set($name, $value) {
        $values[$name] = $value;
    }
}
</code>```

.. then in my test* methods I may do something like:

```<code>$userMock = new Container(array('id' => 2, 'name'=>'Tom'));
$this->mock
    ->method('find') // called within BaseController
    ->with(2)
    ->willReturn( $userMock );
</code>```

So I don't know if I can use PHPUnit tets doubles or Mockery to create such classes, can I? It seems simpler to just do this way, is this a good approach though?

答:
Generally, you don't need to mock value objects (and your container objects seems like value objects) and your approach is right.

If you need to write assertions to the properties, I would consider it a code smell. Still, PHP Unit allows you to mock magic methods, so you can assert the __set calls for example, or you can just assert the end value of the property (assuming you need to assert that the properties are correctly set, if you need to assert that they are read, that's a test smell; as you should verify the end result of the code that uses them, and not it's exact implementation, e.g. don't verify where it got value from, but verify what it did with that value)


问:
Why does 'zip' ignore the dangling tail of the collection?
C#, Scala, Haskell, Lisp and Python have the same zip behaviour: if one collection is longer, the tail is silently ignored.

It could be an exception thrown as well, but I didn't heard of any language using this approach.

This puzzles me. Does anyone know the reason why zip is designed that way? I guess for new languages, it is done because other languages do it this way. But what was the root reason?

I am asking here factual, historic-based question, not if somebody likes it, or if it is a good or bad approach.

Update: If I was asked what to do, I would say -- throw an exception, pretty similarly to indexing an array (despite "old" languages did all kind of magic, how to handle out of bounds index, UB, expand array, etc).

答:
Because there's no obvious way to complete the tail. Any choice on how to do it would result in a non-obvious tail.

The trick is to explicitly lengthen your shortest list to match the length of the longest with values you expect.

If zip did that for you, you couldn't know what values it was filling in intuitively. Did it cycle the list? Did it repeat a mempty value? What is a mempty value for your type?

There's no implication in what zip does which one could use to intuit the way the tail would be lengthened, so the only reasonable thing to do is work with the values available rather than making some up your consumer may not expect.

Also remember you're referring to a very specific well known function with specific well known semantics. But that doesn't mean you can't make a similar but slightly different function. Just because there's a common function that does x, doesn't mean you can't decide for your given purpose you want to do x and y.

Though remember the reason this and many other common FP style functions are common, is because they're simple and generalized so you can tweak your code to use them and get the behaviour you want. For instance, in C# you could just

```<code>IEnumerable<Tuple<T, U>> ZipDefaults(IEnumerable<T> first, IEnumerable<U> second)
{
    return first.Count() < second.Count()
        ? first.Concat(Enumerable.Repeat(default(T), second.Count() - first.Count())).Zip(second)
        : first.Zip(second.Concat(Enumerable.Repeat(default(U), first.Count() - second.count())))
}
</code>```

Or other simple things. FP approaches make modifications so easy because you can reuse pieces as well as having implementations be so small as above that creating your own modified versions of things is exceedingly simple.

Body:
Because there's no obvious way to complete the tail. Any choice on how to do it would result in a non-obvious tail.

The trick is to explicitly lengthen your shortest list to match the length of the longest with values you expect.

If zip did that for you, you couldn't know what values it was filling in intuitively. Did it cycle the list? Did it repeat a mempty value? What is a mempty value for your type?

There's no implication in what zip does which one could use to intuit the way the tail would be lengthened, so the only reasonable thing to do is work with the values available rather than making some up your consumer may not expect.

Also remember you're referring to a very specific well known function with specific well known semantics. But that doesn't mean you can't make a similar but slightly different function. Just because there's a common function that does x, doesn't mean you can't decide for your given purpose you want to do x and y.

Though remember the reason this and many other common FP style functions are common, is because they're simple and generalized so you can tweak your code to use them and get the behaviour you want. For instance, in C# you could just

IEnumerable<Tuple<T, U>> ZipDefaults(IEnumerable<T> first, IEnumerable<U> second)
{
    return first.Count() < second.Count()
        ? first.Concat(Enumerable.Repeat(default(T), second.Count() - first.Count())).Zip(second)
        : first.Zip(second.Concat(Enumerable.Repeat(default(U), first.Count() - second.count())))
}

Or other simple things. FP approaches make modifications so easy because you can reuse pieces as well as having implementations be so small as above that creating your own modified versions of things is exceedingly simple.


答:
This calculation is Business Logic and should go in the Domain Layer of your application, i.e. your models.

The controller is the wrong place for this logic because it should be pretty dumb. It knows what to do (calculate a value) but not why it happens or the nitty gritty details of how it happens (the algorithm for the calculation).

A view model should just massage the domain model into something more palatable to the view, but it too should be devoid of business logic. The algorithm of the calculation should go in the model.

The screenshot of code you posted is too small to read, but it appears you have a Hero model. I would move the array of values into the Hero class and expose a public method that does the calculation and returns the result.

Title: Which is the convention in Rails to perform calculations and display the results?

Body:
So I'm working on a personal project on Rails to learn more about this framework, and I wanted to add a feature in which the user choose a particular record from the view, and after some calculations are made (which involves an array of 80 integers) I show the result... And because I find it looks ugly in the way I did I just wondered what was the convention to do this kind of things...

In detail what I do is show you a list of records to the user, the
user selects a record and a number, and then click the "Calculate exp" button...

Then in the controller I check if the parameters exist, if they exist then I define the array and do the calculations based on the input number, on the record attributes and the array (the array never changes and could be defined as a constant in fact) that I define in the controller, and at the end I assing the result to an instance variable.

Finally the result is shown on the same page, only if the instance variable that hold the result and is defined on the controller (after checking that the parameters exists) exists.

So my question is if I'm doing it the right way (is my first time trying to do something "serious" with rails and I don't know if I'm doing it right, especially by declaring an array of 80 elements in the controller, I don't like how it looks and I don't feel it's right.).


答:
What you are attempting to do is nontrivial.

You effectively have a graph and are trying to optimize a series of connections based on relatively complicated rules and constraints.

Could someone either tell me the name of this domain so I can start doing research, point me to an algorithm, or propose an algorithm that I could try?

A more formal description of your problem is a constrained optimization problem. There are a variety of methods in literature which deal with such problems, such as combinatorial problems.

Depending on how you have implemented your constraints you can then use a variety of methods. It looks like  your constraints are relatively straightforward to list heuristically.

You may find success in modifying your problem to be a traveling salesman problem as there are a lot of methods to deal with these.

I am unfamiliar enough with Ticket to Ride to know how the "points" for a route are calculated. If it is possible to determine a value per edge, this is ideal. You ideally want to convert this into a problem which can be addressed directly with existing methodology. You do NOT want to try to invent your own optimization algorithm to deal with this.

Title: Algorithm or domain for finding cheapest subgraphs that connect vertex pairs

Body:
I am currently working on a project inspired by the Ticket to Ride board game.  This board game is played on an undirected graph where each vertex represents a city and each edge represents a claimable train line connecting two cities.  Players get points by claiming an edge for themselves, scoring points based upon how many cars the route requires to claim.  There are also tickets that give bonus points if the player is able to claim a path that connects the two cities.  Each player has only 45 cars, so this is a resource allocation problem.

I am trying to write a program that helps agents (humans or AIs) plan which routes to take based upon which tickets that agent needs to complete, which routes the agent has already claimed, and which routes are unavailable due to other players having claimed them.  I need an algorithm that finds a set of subgraph(s) such that each ticket has its city in the same subgraph while trying to optimize some criteria (minimum car usage, maximum points per car, etc.).  I do not care whether the algorithm gets all the cities in one subgraph, or whether it strings them all out in a line without branching (which would help toward getting the Longest Route bonus); I want something that enables the agent to complete the tickets quickly so he can start working on new ones.

The problem is that I do not have enough familiarity with graph theory to know the name for this type of problem.  I have tried searches with text that describes what I am trying to do with no luck.  I have also looked in my old textbooks (Introduction to Algorithms and Algorithms in C: Part 5 - Graph Algorithms) to try to find a graph problem domain that seems to relate to my issue; the closest seems to be network flow, but that does not seem to be close enough.

I have tried solving this problem on my own.  I wrote an A* that scored each set of subgraphs based upon the estimated minimum distance to a node, but it did not work (as I would have discovered if I had read the Wikipedia article on A* first).  I wrote an NSGA-II implementation to try to solve the problem stochastically, but it oddly seems to do worse the closer the initial set of owned edges is to connecting the tickets.  In fact, the NSGA-II implementation "freaks out" and finds very strange routes to connect subgraphs when only one route that earlier calls to the algorithm recommended.

Could someone either tell me the name of this domain so I can start doing research, point me to an algorithm, or propose an algorithm that I could try?


问:
REST and foreign key constraints
I have a rather complex database schema using foreign key constraints. This database schema will be accessed with REST services.

Should REST or the database be responsible for referential integrity? Is it bad practice to have foreign keys constraints in the database when the entities are updated / deleted via REST?

答:
Should REST or the database be responsible for referential integrity?

Both:

DB should have proper constraints.

API should have validation rules which reflect those constraints (e.g. "role_id cannot be null on user object"), check those, and provide meaningful error messages when they are violated.

Is it bad practice to have foreign keys constraints in the database when the entities are updated / deleted via REST?

No, it is a requirement if you want to keep your data consistent.

OwnerDisplayName: phpPhil

Title: REST and foreign key constraints


答:
This is what a conventional rails controller would look like:

```<code>class HeroesController < ApplicationController
  before_filter :authenticate_user!
  before_filter :user_only

  def index
    @heroes = current_user.heroes.find_by_level(params[:level])
  end
end
</code>```

Controllers should map to resources, and your controller is returning a list of heroes. Hence, HeroesController#index. All the finding stuff goes in the model.

Body:
This is what a conventional rails controller would look like:

class HeroesController < ApplicationController
  before_filter :authenticate_user!
  before_filter :user_only

  def index
    @heroes = current_user.heroes.find_by_level(params[:level])
  end
end

Controllers should map to resources, and your controller is returning a list of heroes. Hence, HeroesController#index. All the finding stuff goes in the model.


问:
Event action abstraction and trigger control
I am thinking of abstracting Event action in order to make further alteration/implementation/maintenance easy since the project I am currently working on has volatile requirement. So I thought of the following concept.
I created an implementation of IEventAction which ex. handles closing of planning in my application, I made IEventAction extends IEventAction so I can manage all EventAction using a generic collection; and using a factory, I will get the appropriate event by passing the keypress key to the factory to resolve the correct event as shown in the code below.

```<code>interface IEventAction {

}

interface IEventAction<T> : IEvent {
    void Fire(T factor);
    bool CheckCondition(T factor); //check the condition to fire the event
}

class PlanningClose : IEventAction<string> {
    GroupBox _gpb;
    public PlanningClose(GroupBox gpb){
        this._gpb = gpb;
    }

    public void Fire(string factor) {
        this._gpb.SendToBack(); //hide planning groupeBox
    }

    public bool CheckCondition(string factor){
        return factor == "*"; //"*" is keyboard key for close.
    }
}

class frmMain : Form {
    //logic here
    void registerActions() {
        ActionsFactory.Register(new PlanningClose(this._gpbPlanning));
    }
    //logic here
    void frmMain_KeyPress(object sender, KeyPressEventArgs e){
        //during resolve the factory checks if the event is suited be executing
        //CheckCondition(T factor) and return it if appropriate
        IEventAction evt = ActionsFactory.Resolve<string>(e.keychar);
        evt.Fire(e.KeyChar);
    }
    //logic here
}
</code>```

The problem here is that I am managing a lot of key presses in frmMain_KeyPress where I am using the same key several times for different purpose, the problem here is I cant figure out a proper way to handle this problem and keep Action as abstract as possible.
I thought about registering named action and resolving them by name also, but I have never used this technique.

```<code>//register
ActionsFactory.Register("close_planning", new PlanningClose(this._gpbPlanning);
//call
ActionsFactory.Resolve<string>("close_planning", e.KeyChar);
</code>```

Does anyone have a better way of implementing this problem.
Thank you.

答: It sounds like you want to resolve event actions based on more than just the e.KeyChar. I have seen this problem solved by passing in a second argument to the Resolve function which could be named something like KeyPressContext. Basically you would want to supply an extra object with metadata about the context in which the key was pressed and use that information to determine how to resolve the action.


问:
Is Current CoffeeScript Module Pattern Valid?
I have a Node.js web application that's written in CoffeeScript, which has a set of "services".  These various services are currently exposed as a CoffeeScript class, which does a few things that I like.

For one, I get a method that gets ran once as the instance of the service is started.  On some services this allows me to fetch authentication tokens, create connections, etc. that are requirements for said services.  Using CS classes also allows me to have properties that can be referenced in the specific methods exposed to the class instance (status, helper methods, etc.)

Originally when I took over the application services were exposed similar to this:

```<code>class SchedulerService
  constructor: (@msgBus, connStr) ->
    # Some logic setting up service.
  somePublicMethod: (cb) ->
    cb()

module.exports = SchedulerService
</code>```

More recently, I've taken up the habit of not exposing the class itself, but an instance of the class.

```<code># Some code that grabs msgBus connection, dbConnStr

class SchedulerService
  constructor: (@msgBus, connStr) ->
    # Some logic setting up service.
  somePublicMethod: (cb) ->
    cb()

module.exports = new SchedulerService(msgBus, dbConnStr)
</code>```

If you look at the docs these modules will be cached, allowing for these services to be required and have initialization be done once per service.

Are there any downsides to this sort of module pattern?  One thing I'd have to worry about is having the module cache invalidated, but it seems like that wouldn't likely happen under normal circumstances.

Another worry is boilerplate code to grab these common values, but I feel like that's solvable by a module whose only job is to supply these sort of arguments.

Any other things that I'm missing here?  Seems like a viable service pattern with CoffeeScript.

答:
I can think of a few reasons to expose the class and not the singleton instance.

Testability of the service

Reusability of the class

Life cycle management of service instances

If you are purposefully hiding the class constructor, how can you ever write unit tests that exercise only its code and none of its dependencies (its constructor arguments). You have just removed the ability to mock out it's depencies and test the class in isolation.

If the class is not meant to be part of a public API, reusability isn't much of an issue as you can always change the code later. However, structuring your code for reusability upfront costs very little and has the potential to save you a lot of work down the road if your singleton pattern doesn't work for some class of problems.

My third point is less common, but should you ever want services instances to be created and managed in the context of something like a database connection it becomes more important. Managing the resource creation/cleanup life cycle becomes a lot easier when you can encapsulate the concept in its own little box.


问:
Helping testers who don't have specialized domain knowledge
I am a team lead on a project that develops specialized engineering software. My developers generally have advanced degrees and the domain knowledge needed to work with the software we develop, but my testers don't have the necessary background knowledge. I don't have much flexibility in determining the composition of my team, so I can't hire new testers with an engineering background. What steps can I take to help my test team understand the software better -- or alternatively, how can I make it easier for them to do "black box" testing for which they won't need that knowledge?</p>

答:
Your developers are going to have to write very detailed and explicit testing instructions until the testers learn the domain and the app to the point where they can write their own. Make testing training videos from screen recordings just like they would for user training.

You may find some interesting bugs getting discovered because your testers don't think like engineers or programmers.

If this isn't feasible, someone in your firm needs to address the current business testing model and make room for more qualified people.


问:
How does branch prediction work, if you still have to check for the conditions?
I was reading the popular answer about Branch Prediction from https://stackoverflow.com/q/11227809/555690, and there is something confusing me:

If you guessed right, it continues on.

If you guessed wrong, the captain will stop, back up, and yell at you to flip the switch. Then it can restart down the other path.

If you guess right every time, the train will never have to stop.

If you guess wrong too often, the train will spend a lot of time stopping, backing up, and restarting.

But this is what I don't get: to know whether your guess was right or wrong, you have to make a condition check anyway. So how does branch prediction even work, if either way you are still doing the same conditional check?

What I am trying to say is, isn't branch prediction exactly the same as having no branch prediction at all because you are doing the same conditional checks anyway? (obviously I'm wrong, but I don't get it)

答:
Of course the condition is checked every single time. You cannot avoid this.

Branch prediction and many other tricks that modern CPUs do are all about achieving as much processing as possible in parallel. One of the main features that accomplishes things in parallel is the CPU pipeline. When the pipeline is full, you get the most benefits. When the pipeline is not full, performance suffers.

Usually, a condition is immediately followed by a conditional branch instruction, which will either branch or not branch, depending on the result of the condition. This means that there are two different streams of instructions that the CPU might need to follow.

Unfortunately, immediately after loading the condition instruction and the branch instruction, the CPU does not know yet what the condition will evaluate to, but it still has to keep loading stuff into the pipeline. So it picks one of the two sets of instructions based on a guess ("prediction") as to what the condition will evaluate to.

Later on, the CPU finds out whether its guess was right or wrong.

If the guess turns out to be right, then the branch went to the correct place, and the right instructions were loaded into the pipeline, so all is good.

If it turns out that the guess was wrong, then all the instructions that were loaded into the pipeline after the conditional branch instruction were wrong, they need to be discarded, and fetching of instructions must commence again from the right place.

Amendment

In response to StarWeaver's comment, to give an idea of what the CPU has to do in order to execute a single instruction:

Consider something as simple as MOV AX,[SI+10] which we humans naïvely think of as "load AX with the word at SI plus 10". Roughly, the CPU has to:

emit the contents of PC (the "program counter register") to the address bus;

read the instruction opcode from the data bus;

increment PC;

decode the opcode to discover that it is supposed to be followed by an operand;

emit the contents of PC to the address bus;

read the operand (in this case 10) from the data bus;

increment PC;

feed the operand and SI to the adder;

emit the result of the adder to the address bus;

read AX from the data bus.

This is a whopping 10 steps. Some of these steps will be optimized away even in non-pipelined CPUs, for example the CPU will almost always increment PC in parallel with the next step, which is an easy thing to do because the PC is a very, very special register which is never used for any other job, so there is no possibility of contention between different parts of the CPU for access to this particular register.  But still, we are left with 8 steps for such a simple instruction, and note that I am already assuming some degree of sophistication on behalf of the CPU, for example I am assuming that there will be no need for a whole extra step for the adder to actually carry out the addition before the result can be read from it, and I am assuming that the output of the adder can be sent directly to the address bus without having to be stored in some intermediate internal addressing register.

Now, consider that there exist more complicated addressing modes, like MOV AX, [DX+SI*4+10], and even far more complicated instructions, like MUL AX, operand which actually perform loops inside the CPU to calculate their result.

So, my point here is that the "atomic level" metaphor is far from suitable for the CPU instruction level.  It might be suitable for the pipeline step level, if you don't want to go too far down to the actual logic gate level.

ContentLicense: CC BY-SA 4.0


答:
If your test team does not have the necessary background knowledge, they are not going to be able to test your product adequately.

(This is a special case of a more general problem: If a team member does not have the necessary background knowledge, he is not going to be able to do his job adequately.)

You're going to have to figure out how to explain to your management and your HR people that your test team members need this background knowledge to do their jobs.  This will probably have the highly-undesirable (from management's perspective) side-effect of costing money, in the form of (a) requiring the company to spend more money on their salaries, to be able to hire people with the requisite knowledge, or (b) requiring the company to spend money teaching/training them (and then quite possibly having to pay them more to retain them, now that they have the knowledge).

You would not ever, for example, ask a non-pilot to take a new airplane up for first flight test.  He needs that knowledge.  You MIGHT ask a non-pilot to try to test a new piece of avionics equipment, but you'd be smart to stick him in a simulator or send him up with an instructor so he gets some idea of what the pilot is up against in the Real World.  (Pilots HATE complicated avionics.  I didn't really understand why until I flew a sim scenario, and learned firsthand.  They have their hands full with the airplane and the mission, and anything that adds workload is THE ENEMY.)

Having your developers write the test procedures is not the answer.  Even if you want to argue that the developers are most familiar with the product, and most able to do it, you also need to test the paths that the developers AREN'T familiar with.  Example: Certain functions on a certain airplane are required to be done in a very specific order.  A certain operational pilot, during a VERY high-profile certification test, deviated from the procedure, and demonstrated a previously-unknown MAJOR issue, that caused the certification test to fail instantly -- and with very good reason.  The airplane REALLY should not have done what it did.  (I'm being deliberately vague here.  I have my reasons.)  A good test engineer, having been told "Do it like this", is GOING to deviate, to see what happens if he doesn't "do it like this".  That's what test engineers do.

Note: When asked why the pilot deviated from the procedure, the lead answered by asking "Do you know 'pilot'?".  Wry smiles all around the room.

Title: Helping testers who don't have specialized domain knowledge

Body: I am a team lead on a project that develops specialized engineering software. My developers generally have advanced degrees and the domain knowledge needed to work with the software we develop, but my testers don't have the necessary background knowledge. I don't have much flexibility in determining the composition of my team, so I can't hire new testers with an engineering background. What steps can I take to help my test team understand the software better -- or alternatively, how can I make it easier for them to do "black box" testing for which they won't need that knowledge?</p>


答:
From my understanding, branch prediction is most useful when the condition you need to check requires the outcome of something which is expensive or still in progress, and you would otherwise be twiddling your thumbs waiting for the value to evaluate the condition.

With things like out-of-order execution, you can use branch prediction to start filling in empty spots in the pipeline that the CPU would otherwise not be able to use. In a situation where there aren't, for some reason, any idle cycles in the pipeline, then yes, there isn't a gain in branch prediction.

But the key here is, the CPU is starting the work for one of the predicted branches because it can't evaluate the condition itself yet.

Title: How does branch prediction work, if you still have to check for the conditions?

Body:
I was reading the popular answer about Branch Prediction from https://stackoverflow.com/q/11227809/555690, and there is something confusing me:

If you guessed right, it continues on.

If you guessed wrong, the captain will stop, back up, and yell at you to flip the switch. Then it can restart down the other path.

If you guess right every time, the train will never have to stop.

If you guess wrong too often, the train will spend a lot of time stopping, backing up, and restarting.

But this is what I don't get: to know whether your guess was right or wrong, you have to make a condition check anyway. So how does branch prediction even work, if either way you are still doing the same conditional check?

What I am trying to say is, isn't branch prediction exactly the same as having no branch prediction at all because you are doing the same conditional checks anyway? (obviously I'm wrong, but I don't get it)


问:
Child Object depends on member of Parent Object
I am wrestling with this OOP design issue.  Take these base classes, for example:

```<code>class Database
{
    public string ConnectionString { get; set; }
    public Table MyTable { get; set; }
}

class Table
{
    public string Name { get; set; }
}
</code>```

This example is oversimplified to just concentrate on the question at hand.

If I wanted to add logic that would get the Table row count, you would think that naturally belongs in Table class:

```<code>class Table
{
    public string Name { get; set; }

    public int GetRowCount() { ... }
}
</code>```

The problem is, in order to get the row count, a database connection would need to happen.  Not a big deal, but the Table class has no way to retrieve the Database.ConnectionString property in order to actually connect to get the row count of the particular table.

I see a few options here, and none of them really seem like great approaches.

Keep logic out of child objects

In this case, the GetRowCount() logic would have to live in the parent object.  Something like this:

```<code>class Database
{
    public string ConnectionString { get; set; }
    public Table MyTable { get; set; }

    public int GetRowCount(Table table) { ... }
}

class Table
{
    public string Name { get; set; }
}
</code>```

The Table class is now "dumb" to the logic of the row count, which isn't altogether a bad thing, but now there is no way to have a member in the Table class to store or retrieve data that is directly related to the Table class.

Have a reference to the Parent Object in the Child object

This I like even less than the above approach.  In this case, it would resemble something like this:

```<code>class Database
{
    public string ConnectionString { get; set; }
    public Table MyTable { get; set; }
}

class Table
{
    public string Name { get; set; }
    public Database Parent { get; set; }

    public int GetRowCount() { ... }
}
</code>```

Sure, Table.GetRowCount() can make a reference to Table.Parent.ConnectionString, but this just seems like unnecessary recursion and... sloppy.

Explicity pass the required data around

I don't like this either, but if the Table.GetRowCount() implementation required that the connection string is passed to it, this logic could live in the Table class, but now there is a lack of DRY as well as a leak of Database data into the Table implementation:

```<code>class Database
{
    public string ConnectionString { get; set; }
    public Table MyTable { get; set; }
}

class Table
{
    public string Name { get; set; }

    public int GetRowCount(string connectionString) { ... }
}
</code>```

Not to mention that this could lead to challenging logic bugs, I would imagine.

How is this typically done, and what's the best approach here?  I want the row count logic to live where it naturally belongs, with the Table class.  But that logic and data depends on a member (the connection string) that naturally lives in the Database class.

答:
Pass a reference to the ConnectionString (or better yet, the actual Connection) to the Table's constructor.

Since the Table is already inside the Database (and doesn't really belong anywhere else), the Database can simply give it the magic string during construction, and then the Table always has what it needs to execute the row count logic. Since your Connection(String) is mutable, you can't get away with a copy, but giving the Table a reference to that one connection is much better than giving it a reference to the whole Database object or forcing the Database to contain all the real code.


答:
Pass an already established connection to Table's constructor (as opossed to the other answer suggestion of passing the connection string).

That's the approach I've used for years. Objects that access the database don't open or close database connections. A connection is made by some other component, usually the main class, and passed to the constructors of the classes that need access to the database.

A further benefit of that approach is that you decouple the code using the conecction from the code creating it. For example, there could be  several versions of the database driver, or there could be a connection pool, and the children classes whould work all the same.

Title: Child Object depends on member of Parent Object

Body:
I am wrestling with this OOP design issue.  Take these base classes, for example:

```<code>class Database
{
    public string ConnectionString { get; set; }
    public Table MyTable { get; set; }
}

class Table
{
    public string Name { get; set; }
}
</code>```

This example is oversimplified to just concentrate on the question at hand.

If I wanted to add logic that would get the Table row count, you would think that naturally belongs in Table class:

```<code>class Table
{
    public string Name { get; set; }

    public int GetRowCount() { ... }
}
</code>```

The problem is, in order to get the row count, a database connection would need to happen.  Not a big deal, but the Table class has no way to retrieve the Database.ConnectionString property in order to actually connect to get the row count of the particular table.

I see a few options here, and none of them really seem like great approaches.

Keep logic out of child objects

In this case, the GetRowCount() logic would have to live in the parent object.  Something like this:

```<code>class Database
{
    public string ConnectionString { get; set; }
    public Table MyTable { get; set; }

    public int GetRowCount(Table table) { ... }
}

class Table
{
    public string Name { get; set; }
}
</code>```

The Table class is now "dumb" to the logic of the row count, which isn't altogether a bad thing, but now there is no way to have a member in the Table class to store or retrieve data that is directly related to the Table class.

Have a reference to the Parent Object in the Child object

This I like even less than the above approach.  In this case, it would resemble something like this:

```<code>class Database
{
    public string ConnectionString { get; set; }
    public Table MyTable { get; set; }
}

class Table
{
    public string Name { get; set; }
    public Database Parent { get; set; }

    public int GetRowCount() { ... }
}
</code>```

Sure, Table.GetRowCount() can make a reference to Table.Parent.ConnectionString, but this just seems like unnecessary recursion and... sloppy.

Explicity pass the required data around

I don't like this either, but if the Table.GetRowCount() implementation required that the connection string is passed to it, this logic could live in the Table class, but now there is a lack of DRY as well as a leak of Database data into the Table implementation:

```<code>class Database
{
    public string ConnectionString { get; set; }
    public Table MyTable { get; set; }
}

class Table
{
    public string Name { get; set; }

    public int GetRowCount(string connectionString) { ... }
}
</code>```

Not to mention that this could lead to challenging logic bugs, I would imagine.

How is this typically done, and what's the best approach here?  I want the row count logic to live where it naturally belongs, with the Table class.  But that logic and data depends on a member (the connection string) that naturally lives in the Database class.


问:
Nested REST urls and parent id, which is better design?
Okay, we have two resources: Album and Song. Here is API:

```<code>GET,POST /albums
GET,POST /albums/:albumId
GET,POST /albums/:albumId/songs
GET,POST /albums/:albumId/songs/:songId
</code>```

We know that we hate some song, it is called Susy, for example. Where we should put search action?

Another question. Okay, now it is a it more real. We open album 1 and load all songs. We create JS objects, each holds song data and has few methods like so: remove, update.

Song object has ID, name and stuff, but has no clue about which parent it belongs to, because we retrieve list of songs by query and it will be not that good to return parent ids with each so. Am I wrong?

So, I see few solutions, but I'm not sure really.

Make parent id optional - as get-parameter. This approach I use currently, but I feel it is ugly one.

```<code>List,Create /songs?album=albumId
Update,Delete /songs/:songId
Get /songs/?name=susy # also, solution for first question
</code>```

Hybrid. It is now that handy since we need album id to perform OPTIONS query to get meta-data.

```<code>List,Create /album/:albumId/songs
Update,Delete /songs/:songId
POST /songs/search # also, solution for first question
</code>```

Return full url with each resource instance. API is same, but we will get songs like this:

```<code>id: 5
name: 'Elegy'
url: /albums/2/songs/5
</code>```

I heard this approach is called HATEOAS.

So... To provide parent ID

```<code>id: 5
name: 'Elegy'
albumId: 2
</code>```

Which is better? Or maybe I'm dumb? Throw some advices, guys!

答:
Where we should put search action?

In GET /search/:text. This will return a JSON array containing the matches, every match containing the album it belongs to. This makes sense, because the client may be interested not in the track itself, but the entire album (imagine that you are searching for a song which, you believe, was in the same album as the one you remember the name).

it will be not that good to return parent ids with each so. Am I wrong?

Individual tracks can contain the album. This will ensure that the track representation is uniform if you can get a track either through an album or through search (no album here).

Which is better?

As previously stated, including the album makes sense. While the third point (with the relative URI) can be interesting in some cases (you don't have to think about the way the URI should be formed), it has a drawback of not providing explicitly the album. The fourth point corrects this. If you see the benefit of having the relative URI in the response, you can combine the point 3 and 4.

Or maybe I'm dumb?

Choosing good URIs is not an easy task, especially since there is no single right answer. If you develop the client at the same time as the API, it may help you to visualize better how the API could be used. This being said, other people may then prefer other usages you weren't thinking about when developing the API.

An aspect which may be problematic is how you organize data internally, i.e. the usage of a hierarchy. From your comment, you are wondering what should contain a response to GET /artist/1/album/10/song/3/comment/23, which shows a very tree-oriented vision. This can lead to a few issues when extending the system later. For instance:

What if a song doesn't have an album?

What if an album has several artists?

What if you want to add a feature which makes it possible to comment albums?

What if there should be comments of comments?

etc.

This is essentially the problem I explained in my blog: a tree representation has too many limitations to be effectively used in many cases.

What happens if you destroy the hierarchy? Let's see.

GET /albums/:albumId returns a JSON containing the meta information about the album (such as the year when it was published or the URI of the JPEG showing the album cover) and an array of tracks. For example:

GET /albums/151
```

<pre class="lang-js prettyprint-override"><code>{
    "id": 151,
    "gid": "dbd3cec7-b927-423f-894b-742c4c7b54ce",
    "name": "Yellow Submarine",
    "year": 1969,
    "genre": "Psychedelic rock",
    "artists": ["John Lennon", "Paul McCartney", ...],
    "tracks": [
        {
            "id": 90224,
            "title": "Yellow Submarine",
            "length": "2:40"
        },
        {
            "id": 83192,
            "title": "Only a Northern Song",
            "length": "3:24"
        }
        ...
    ]
}
</code>```

Why do I include, for instance, the length of each track? Because I imagine that the client showing an album may be interested by listing the tracks by title, but also show the length of each track—most clients do. On the other hand, I may not show the composer(s) or the artist(s) for every track, because I decide that this information is not necessary at this level. Obviously, your choices may be different.

GET /tracks/:trackId returns the information about a specific track. Since there is no hierarchy any longer, you don't need to guess the album or the artist: the only thing you really have to know is the identifier of the track itself.

Or maybe even not? What if you can specify it by name with GET /tracks/:trackName?

GET /tracks/Only%20a%20Northern%20Song
```

<pre class="lang-js prettyprint-override"><code>{
    "id": 83192,
    "gid": "8d9c4311-9d7b-40a4-8aeb-4fe96247fe2b",
    "title": "Only a Northern Song",
    "writers": ["George Harrison"],
    "artists": ["John Lennon", "Paul McCartney", "Ringo Starr"],
    "length": "3:24",
    "record-date": 1967,
    "albums": [151, 164],
    "soundtrack": {
        "uri": "http://audio.example.com/tracks/static/83192.mp3",
        "alias": "Beatles - Only a Northern Song.mp3",
        "length-bytes": 3524667,
        "allow-streaming": true,
        "allow-download": false
    }
}
</code>```

Now look closer at albums; what do you see? Right, not one, but two albums. If you have an hierarchy, you can't do that (unless you duplicate the record).

GET /comments/:objectGid. You may have spotted the ugly GUIDs in the responses. Those GUIDs make it possible to identify the entity across the database in order to perform tasks which can be applied to albums, or artists, or tracks. Such as commenting.

GET /comments/8d9c4311-9d7b-40a4-8aeb-4fe96247fe2b
```

<pre class="lang-js prettyprint-override"><code>[
    {
        "author": {
            "id": 509931,
            "display-name": "Arseni Mourzenko"
        },
        "text": "What a great song! (And I'm proud of the usefulness of my comment)",
        "concerned-object": "/tracks/83192"
    }
]
</code>```

The comment references the concerned object, making it possible to go to it when accessing the comment outside its context (for instance when moderating the latest comments through GET /comments/latest).

Note that this doesn't mean that you should avoid any form of hierarchy in your API. There are cases where it makes sense. As a rule of thumb:

If the resource makes no sense outside the context of its parent resource, use hierarchy.

If the resource can live (1) alone or (2) in a context of parent resources of different types or (3) have multiple parents, the hierarchy should not be used.

For instance, lines of a file make no sense outside the context of a file, so:

```<code>GET /file/:fileId
</code>```

and:

```<code>GET /file/:fileId/line/:lineIndex
</code>```

are fine.

Body:
Where we should put search action?

In GET /search/:text. This will return a JSON array containing the matches, every match containing the album it belongs to. This makes sense, because the client may be interested not in the track itself, but the entire album (imagine that you are searching for a song which, you believe, was in the same album as the one you remember the name).

it will be not that good to return parent ids with each so. Am I wrong?

Individual tracks can contain the album. This will ensure that the track representation is uniform if you can get a track either through an album or through search (no album here).

Which is better?

As previously stated, including the album makes sense. While the third point (with the relative URI) can be interesting in some cases (you don't have to think about the way the URI should be formed), it has a drawback of not providing explicitly the album. The fourth point corrects this. If you see the benefit of having the relative URI in the response, you can combine the point 3 and 4.

Or maybe I'm dumb?

Choosing good URIs is not an easy task, especially since there is no single right answer. If you develop the client at the same time as the API, it may help you to visualize better how the API could be used. This being said, other people may then prefer other usages you weren't thinking about when developing the API.

An aspect which may be problematic is how you organize data internally, i.e. the usage of a hierarchy. From your comment, you are wondering what should contain a response to GET /artist/1/album/10/song/3/comment/23, which shows a very tree-oriented vision. This can lead to a few issues when extending the system later. For instance:

What if a song doesn't have an album?

What if an album has several artists?

What if you want to add a feature which makes it possible to comment albums?

What if there should be comments of comments?

etc.

This is essentially the problem I explained in my blog: a tree representation has too many limitations to be effectively used in many cases.

What happens if you destroy the hierarchy? Let's see.

GET /albums/:albumId returns a JSON containing the meta information about the album (such as the year when it was published or the URI of the JPEG showing the album cover) and an array of tracks. For example:

GET /albums/151

{
    "id": 151,
    "gid": "dbd3cec7-b927-423f-894b-742c4c7b54ce",
    "name": "Yellow Submarine",
    "year": 1969,
    "genre": "Psychedelic rock",
    "artists": ["John Lennon", "Paul McCartney", ...],
    "tracks": [
        {
            "id": 90224,
            "title": "Yellow Submarine",
            "length": "2:40"
        },
        {
            "id": 83192,
            "title": "Only a Northern Song",
            "length": "3:24"
        }
        ...
    ]
}

Why do I include, for instance, the length of each track? Because I imagine that the client showing an album may be interested by listing the tracks by title, but also show the length of each track—most clients do. On the other hand, I may not show the composer(s) or the artist(s) for every track, because I decide that this information is not necessary at this level. Obviously, your choices may be different.

GET /tracks/:trackId returns the information about a specific track. Since there is no hierarchy any longer, you don't need to guess the album or the artist: the only thing you really have to know is the identifier of the track itself.

Or maybe even not? What if you can specify it by name with GET /tracks/:trackName?

GET /tracks/Only%20a%20Northern%20Song

{
    "id": 83192,
    "gid": "8d9c4311-9d7b-40a4-8aeb-4fe96247fe2b",
    "title": "Only a Northern Song",
    "writers": ["George Harrison"],
    "artists": ["John Lennon", "Paul McCartney", "Ringo Starr"],
    "length": "3:24",
    "record-date": 1967,
    "albums": [151, 164],
    "soundtrack": {
        "uri": "http://audio.example.com/tracks/static/83192.mp3",
        "alias": "Beatles - Only a Northern Song.mp3",
        "length-bytes": 3524667,
        "allow-streaming": true,
        "allow-download": false
    }
}

Now look closer at albums; what do you see? Right, not one, but two albums. If you have an hierarchy, you can't do that (unless you duplicate the record).

GET /comments/:objectGid. You may have spotted the ugly GUIDs in the responses. Those GUIDs make it possible to identify the entity across the database in order to perform tasks which can be applied to albums, or artists, or tracks. Such as commenting.

GET /comments/8d9c4311-9d7b-40a4-8aeb-4fe96247fe2b

[
    {
        "author": {
            "id": 509931,
            "display-name": "Arseni Mourzenko"
        },
        "text": "What a great song! (And I'm proud of the usefulness of my comment)",
        "concerned-object": "/tracks/83192"
    }
]

The comment references the concerned object, making it possible to go to it when accessing the comment outside its context (for instance when moderating the latest comments through GET /comments/latest).

Note that this doesn't mean that you should avoid any form of hierarchy in your API. There are cases where it makes sense. As a rule of thumb:

If the resource makes no sense outside the context of its parent resource, use hierarchy.

If the resource can live (1) alone or (2) in a context of parent resources of different types or (3) have multiple parents, the hierarchy should not be used.

For instance, lines of a file make no sense outside the context of a file, so:

GET /file/:fileId

and:

GET /file/:fileId/line/:lineIndex

are fine.


答:
Think of it like a road trip without GPS.  You come to an intersection, and think you need to turn, but aren't completely sure.  So you take the turn, but ask your passenger to check the map.  Maybe you're three miles down the road by the time you finish arguing about where you are.  If you were right, you're three miles farther than you would have been if you had stopped and argued before turning.  If you were wrong, you have to turn around.

CPU pipelines work the same way.  By the time they can check the condition, they're already a ways down the road.  The difference is, they don't have to drive the three miles back, they just lose the head start.  That means there's no harm in trying.


答:
It is perfectly fine for a child object to have a reference to its parent.  There is no unnecessary recursion and no sloppiness.  Naturally, that would be a construction-time parameter, and it would be stored in a readonly member, so there would be no set.

Then, the table could obtain the connection string from the database object, if it really needed to.

However, I would recommend that you don't do what you are trying to do.  It is none of the table's business to obtain a connection string and establish a connection in order to get a count.  The fact that a connection string is involved is an implementation detail.  The entire concept of connection strings is a hack which is best encapsulated in the smallest amount of code which is absolutely necessary to get the job done.

So, either always work with a separate connection object which has already been created (presumably using a connection string) or, better yet, make your database be the connection object, fully encapsulating the fact that its establishment involved a useful hack known as a connection string.


问:
Why use a bool over more domain specific abstractions
Booleans are often used to model domain specific dichotomies. The most common example I can think of is the success or failure of an operation. It seems to me that a boolean must be interpreted in the context in which it is used as opposed to something more specific to the domain of the function. What is the advantage to returning a boolean from a function over returning something like a enumeration of named values?

Assume the programming language we are using succinctly deals with both booleans and enumerations so readability is not an issue.

答:
What is the advantage to returning a boolean from a function over returning something like a enumeration of named values?

It let's programmers be lazy. Sometimes that is a virtue. Things like this, it is not.

The main advantage is that at the call-site, using a bool is often more readable:

```<code>if(foo.IsBar){ ... }
</code>```

Rather than:

```<code>if(foo.Bar == enum.Good){ ... }
</code>```

The enum will be marginally more readable in Bar than IsBar, but that code is only in one spot. The property/function will be called in more spots, so we favor making that code more readable.

And then there's the fact that everything else already uses bools. If you need to take the result and pass it into existing code, the enum needs adapted to some truthy value, further hurting readability.

Again, this is in general. Usually booleans + good name can be made more readable. Sometimes enums will be more readable. Use the right one for the problem at hand.

Body:
What is the advantage to returning a boolean from a function over returning something like a enumeration of named values?

It let's programmers be lazy. Sometimes that is a virtue. Things like this, it is not.

The main advantage is that at the call-site, using a bool is often more readable:

if(foo.IsBar){ ... }

Rather than:

if(foo.Bar == enum.Good){ ... }

The enum will be marginally more readable in Bar than IsBar, but that code is only in one spot. The property/function will be called in more spots, so we favor making that code more readable.

And then there's the fact that everything else already uses bools. If you need to take the result and pass it into existing code, the enum needs adapted to some truthy value, further hurting readability.

Again, this is in general. Usually booleans + good name can be made more readable. Sometimes enums will be more readable. Use the right one for the problem at hand.


答:
It's almost always what you want, and when it isn't, you can do the fill yourself.

The main issue is with lazy semantics you don't know the length when you first start the zip, so you can't just throw an exception at the start.  You would need to first return all the common elements, then throw an exception, which wouldn't be very useful.

It's also a style issue.  Imperative programmers are accustomed to manually checking boundary conditions all over the place.  Functional programmers prefer constructs that can't fail by design.  Exceptions are extremely rare.  If there's a way for a function to return a reasonable default, functional programmers will take it.  Composability is king.

Title: Why does 'zip' ignore the dangling tail of the collection?

Body:
C#, Scala, Haskell, Lisp and Python have the same zip behaviour: if one collection is longer, the tail is silently ignored.

It could be an exception thrown as well, but I didn't heard of any language using this approach.

This puzzles me. Does anyone know the reason why zip is designed that way? I guess for new languages, it is done because other languages do it this way. But what was the root reason?

I am asking here factual, historic-based question, not if somebody likes it, or if it is a good or bad approach.

Update: If I was asked what to do, I would say -- throw an exception, pretty similarly to indexing an array (despite "old" languages did all kind of magic, how to handle out of bounds index, UB, expand array, etc).


答:
Sometimes you just need to know whether an operation succeeded or not.

The most straightforward example that I can think of is the TryParse metaphor in the .NET Framework.  TryParse exists for a number of reasons:

You can control the lifetime of the variable you're putting the parse result into,

Exceptions are too expensive to be throwing if you're in the middle of a long loop, and

A success flag allows an appropriate value to be substituted for a failed parse (like zero, perhaps).

TryParse looks like this:

```<code>bool result SomeNumericType.TryParse(string text, out SomeNumericType value)
</code>```

Let's say you're trying to parse some numeric columns in a large text file as quickly as possible, but one of the columns contains a text character.  If you use a Parse method that throws exceptions, you've just crippled your parser.

On the other hand, if you do something like this:

```<code>public double ParseColumn(string text)
{
    double number= 0;
    if (double.TryParse(text), out number)
        return number;
    else
    {
        // optionally analyze text for the reasons why, log the problem, or whatever
        return 0;
    }
}
</code>```

Then you've avoided having to trap the dreaded exception, an operation that is typically three orders of magnitude slower than returning an error code or success result, and you've lowered the overhead as much as humanly possible for the general case (a successful parse operation).

Title: Why use a bool over more domain specific abstractions

Body:
Booleans are often used to model domain specific dichotomies. The most common example I can think of is the success or failure of an operation. It seems to me that a boolean must be interpreted in the context in which it is used as opposed to something more specific to the domain of the function. What is the advantage to returning a boolean from a function over returning something like a enumeration of named values?

Assume the programming language we are using succinctly deals with both booleans and enumerations so readability is not an issue.

Body:
Sometimes you just need to know whether an operation succeeded or not.

The most straightforward example that I can think of is the TryParse metaphor in the .NET Framework.  TryParse exists for a number of reasons:

You can control the lifetime of the variable you're putting the parse result into,

Exceptions are too expensive to be throwing if you're in the middle of a long loop, and

A success flag allows an appropriate value to be substituted for a failed parse (like zero, perhaps).

TryParse looks like this:

bool result SomeNumericType.TryParse(string text, out SomeNumericType value)

Let's say you're trying to parse some numeric columns in a large text file as quickly as possible, but one of the columns contains a text character.  If you use a Parse method that throws exceptions, you've just crippled your parser.

On the other hand, if you do something like this:

public double ParseColumn(string text)
{
    double number= 0;
    if (double.TryParse(text), out number)
        return number;
    else
    {
        // optionally analyze text for the reasons why, log the problem, or whatever
        return 0;
    }
}

Then you've avoided having to trap the dreaded exception, an operation that is typically three orders of magnitude slower than returning an error code or success result, and you've lowered the overhead as much as humanly possible for the general case (a successful parse operation).


答:
A very large reason for this is probably support: many languages and libraries are designed to support booleans or generic, dichotomous values over more-specific variants so that they have the widest applicability.

For example: if supports booleans. If we wanted if to be able to support any dichotomy (ignoring equality comparisons on the values) then it'd probably have to be parameterized (if<OpReuslt,Success>(...)) or have to test using some sort of Dichotomy type class / interface which we'd have to implement for everything we wanted to be testable (in which case it'd still be using something common to everything, like a boolean). Both of these seem a PITA.

In Haskell, F#, etc, there is the algebraic data type Either (Choice in F#) for representing one of two possible values. There are many libraries which use these constructs to interface with the rest of a program. If each tried to use its own abstraction then they'd all have to support the abstractions of the others or you'd have to have some sort of conversion layer.

There's also the fact that boolean values are often used in some sort of algebraic computation and if something else were used they'd have to be converted to some common type before these computations could take place, so why not use booleans to begin with?


答:
Any data type can be thought of as able to hold the answer to a question. What is two plus two? The integer four. What is pi? The floating point with a certain bit pattern. Is the sky blue? A yes/no, true/false answer.

These are primitives, meaning data elements are reusable across a broad spectrum of uses and generally are simple, often fitting into a single CPU register. Does each function that calculates an integer need its own enum or custom data structure? No. Does each function that returns a yes/no response need the same? No.

Sometimes a function needs to return a discrete number of responses. If there are more than two responses, use an enum. If there are two valid responses and they are not yes/no or true/false, use an enum (e.g. red/green, weekend/weekday, billable/nonbillable). If the responses are true or false, use a boolean. That is why it exists.


问:
Clarify the Open/Closed Principle
As I have had it explained, the open/closed principle states that once written code should not be modified (aside from bug fixes). But if my business rules change shouldn't I modify the code implementing those changes? I suspect I'm not understanding something about how the principle because it doesn't make sense to me.</p>

答:
The answer by Kate Gregory is very good, but consider a different situation where a new requirement can be satisfied by a relatively small change in the existing Invoice class. For example, lets say a new field must be added to the Invoice PDF. According to OCP, we should still create a new subclass, even if the new field could be added in the existing implementation by changing a few lines of code.

In my understanding, OCP reflects the reality of the 80's and early 90's, where projects often did not even use version control, much less had automated regression tests or the benefit of sophisticated refactoring tools. OCP was an attempt to avoid the risk of breaking code that  had been manually tested and put into production. Today, we have better ways to manage the risk of breaking working software (namely, version control systems, TDD and automated testing, and refactoring tools).

Title: Clarify the Open/Closed Principle


答:
Your testers do not need to think like a developer - for black-box testing they need to think like a user of your software, and they should have additional knowledge about how to test software in general.  So assumed your testers are smart enough to learn those things in a reasonable amount of time, train testers the same way you train your users, and make them learn testing basics. For the first part, if you are developing a professional product, I guess you already have a standard procedure. For the letter, there are books, courses, and lots of other material available at the web.

And if the usage of your software needs a fully skilled engineer, you will need your testers to have equal skills, at least some basic skills from that field. For example, when you develop a CAD software, you need people trained in technical drawing, if they are users or if they are testers. Probably your testers don't have to be as good as your users in the domain, but some knowledge of the domain will be essential. But maybe you could see this also as a chance to improve your software in a way to lower the entry skill level?


问:
What is the best "bucket-fill" algorithm?
I'm pretty new to image processing, and I am currently working on a paint-like application that will feature a bucket-fill.  However, I have no idea what the best algorithm for a bucket-fill is.

I implemented an example I found from this site, however, it ran into infinite loop problems when a user tried to bucket-fill an area that had already been bucket-filled with the same color.

I'm currently working around that problem by filling left, right, up and then down; however, I made it so that once a pixel has been filled in to the left, it cannot fill to the right, which means shapes such as:

will not be filled properly if the bucket tool is used at the red dot.

Therefore, I am hoping someone knows of an algorithm or a link to one that will resolve all these issues.

Additional Information: This will be implemented using Javascript as the paint tool. It will be used online utilizing the Canvas element.

答:
I'm currently doing the same thing. However, when I ran into the issue you point out, I opted for simply ending the function if the tool was clicked over an area of the same color you're trying to paint (this also seems to be the behavior of ms-paint).

The queued method should be extremely intuitive for anyone with some programming experience.

If painting the area surrounding a spot of the same color as your paint is a concern, one  you could:

check for background color.

search for the edge of the same-colored spot you clicked at.

queue the surrounding points to the spot.

proceed with normal execution using this (in this case) white-dot filled queue.

If you wish you can take a look at my (quite embarrasing) code
here.

It's far from being fast but it works fine...