答:
The recommendation in "Don't Mock What You Don't Own" is to wrap a third party component into an object of your own. You've already done that. Whatever object has the getDailyHits() method is already a wrapper around TableGateway. And it's a good wrapper since it describes its contract not in nasty low level terms from the ZF2 world, but in terms that make sense in your own system (getDailyHits, start, end).

All you need to do is give it an interface and change the way you test :

Test the concrete wrapper object (let's call it ZF2DAO, for Data Access Object) in an integration test against a real TableGateway if you can. Just test happy paths. These tests are not here to bust corner cases, just to verify that everyhting is set up porperly. You can move them to a separate test suite if they are too slow.

When testing objects that collaborate with the DAO, mock it. You do own this one.

Title: How to reconcile "not mocking what you don't own" with "expectations" in unit tests?

Body:
I'm putting together a set of models for use in a Zend Framework 2 application. So, each model has a table class which acts as the interface between the model and database for querying. Using the ZF2 TableGateway means that even a fairly simple query, like getting the number of hits from a page log between two dates, ends up with some complex calls:

public function getDailyHits($start, $end)
{
    $select = $this->tableGateway->getSql()->select();

    $select->columns(array(
            "date" => new Expression("DATE_FORMAT(timestamp, '%Y-%m-%d')"),
            "hits" => new Expression("COUNT(timestamp)"),
        ));

    $select->where->between("timestamp", $start, $end);

    $select->group("date");

    $results = $this->tableGateway->selectWith($select);

    $dailyHits = array();
    foreach ($results as $result) {
        $dailyHits[$result->date] = $result->hits;
    }

    return $dailyHits;
}
```

<p>When it came to developing the unit test, I wrote up a bunch of expectations:</p>

<pre class="lang-php prettyprint-override"><code>public function testGetDailySearches()
{
    // Setup
    $result = new \stdClass();
    $result->date = "2015-01-01";
    $result->searches = 42;

    $resultSet = array($result);

    $sql = $this->getMockBuilder("Zend\Db\Sql\Sql")
        ->disableOriginalConstructor()
        ->getMock();

    $select = $this->getMockBuilder("Zend\Db\Sql\Select")
        ->disableOriginalConstructor()
        ->getMock();

    $where = $this->getMockBuilder("Zend\Db\Sql\Where")
        ->disableOriginalConstructor()
        ->getMock();

    $tableGateway = $this->getMockBuilder("Zend\Db\TableGateway\TableGateway")
        ->disableOriginalConstructor()
        ->getMock();

    $searchLogTable = $this->getMockBuilder("Usage\Model\Table\SearchLog")
        ->setConstructorArgs(array($tableGateway))
        ->setMethods(null)
        ->getMock();

    // Expectations
    $tableGateway->expects($this->once())
        ->method("getSql")
        ->will($this->returnValue($sql));

    $tableGateway->expects($this->once())
        ->method("selectWith")
        ->with($this->equalTo($select))
        ->will($this->returnValue($resultSet));

    $sql->expects($this->once())
        ->method("select")
        ->will($this->returnValue($select));

    $select->expects($this->once())
        ->method("columns")
        ->will($this->returnValue($select)); // TODO: need to assert parameters

    $select->expects($this->once())
        ->method("__get")
        ->with($this->equalTo("where"))
        ->will($this->returnValue($where));

    $where->expects($this->once())
        ->method("between")
        ->with(
            $this->equalTo("time"),
            $this->equalTo("2015-10-01 00:00:00"),
            $this->equalTo("2015-10-07 23:59:59")
        )
        ->will($this->returnValue($select));

    $select->expects($this->once())
        ->method("group")
        ->with($this->equalTo("date"));

    // Assertions
    $this->assertEquals(
        array("2015-01-01" => 42),
        $searchLogTable->getDailySearches("2015-10-01 00:00:00", "2015-10-07 23:59:59")
    );
}
</code>```

I had a go at using Prophecy to reduce the verbosity in these tests, but got tripped up on them magic __get method needed to read the $where property from the Select object.

After reading through a couple of threads on the Prophecy site, I uncovered a link to That's Not Yours. It makes a lot of sense. It also would reduce a lot of boilerplate in some tests if I just subclass TableGateway (or even maybe just mock it) so that all the Zend\Db behaviour is retained.

But, then what happens to my expectations? Is this a case of overengineered testing? Should I have these expectations, or should I rely on testing a mostly black box of a method?

If I did remove those expectations, and relied on a mocked result from the subclassed/mocked selectWith, I could write a passing test which didn't specify any of the select criteria, and would fail to function as required in the real world.


问:
Why is Math.Sqrt() a static function?
In a discussion about static and instance methods, I always think, that Sqrt() should be a instance method of number types instead of a static method. Why is that? It obviously works on a value.

```<code> // looks wrong to me
 var y = Math.Sqrt(x);
 // looks better to me
 var y = x.Sqrt();
</code>```

Value types obviously can have instance methods, as in many languages, there is an instance method ToString().

To answer some questions from the comments: Why should 1.Sqrt() not be legal? 1.ToString() is.

Some languages do not allow to have methods on value types, but some languages can. I am talking about these, including Java, ECMAScript, C# and Python (with __str__(self)defined). The same applies to other functions like ceil(), floor() etc.

答:
I would be motivated by the fact that there's a ton of special-purpose math functions, and rather than populate every math type with all (or a random subset) of those functions you put them in a utility class. Otherwise, you'd either pollute your auto-completion tooltip, or you'd force people to always look in two places. (Is sin important enough to be a member of Double, or is it in the Math class along with inbreds like htan and exp1p?)

Another practical reason is that it turns out there may be different ways to implement numerical methods, with different performance and precision trade-offs. Java has Math, and it also has StrictMath.

ContentLicense: CC BY-SA 3.0

Title: Why is Math.Sqrt() a static function?


问:
Merging Sorted Lists (with no comparison function)
I have a few lists of items (which will likely but not necessarily have common elements). The lists are known to be sorted, but don't have a comparison function (they were manually put into the system in sorted order). I'd like to combine these lists into one list containing all the elements that is in a reasonable order given the existing ones.

Obviously there are edge cases and decisions to be made - I'm not too worried about the specifics, but rather I'd like a general approach to tackle the problem. Obviously if the two lists have nothing in common, there isn't much to be done besides appending one to the other, but that won't happen much.

As an example:

```<code>l1 = ['Task A', 'Task B', 'Task C', 'Task D']
l2 = ['Task B', 'Task B2', 'Task D', 'Task G']
l3 = ['Task A', 'Task C', 'Task E', 'Task D']
result = ['Task A', 'Task B', 'Task B2', 'Task C', 'Task E', 'Task D', 'Task G']
</code>```

Again, I realize there is no perfect solution, and the output is not mission critical, I just want it to be reasonably nicely ordered in most cases. Any help would be appreciated.

答:
If you have literally no comparison function, then the only sane option is to pick the same order each time:

```<code>one = [1,2,3]
two = [4,5,6]
three = [7,8,9]

merge(one, two, three) == [1,4,7,2,5,8,3,6,9]
</code>```

If there is some order, and the items can be compared for equality, but you can't encode the ordering explicitly, you can track how many times you've seen them in certain orders and use that to generate heuristics.

You can build up a history to base guesses on by storing all visits

I think these data types and algebra (expressed in pseudo-scala) would serve this purpose well.

```<code>// How many times a given item has been seen
type ItemCount = Map[Item, Int]

// NB ItemHistory forms a commutative monoid with zero as empty maps and mappend adding the counts together
case class ItemHistory(itemsSeenBefore: ItemCount, itemsSeenAfter: ItemCount)

// Fold over a list of input items and generate history for each one, storing the count of all items seen before and after
List[Item] => Map[Item, ItemHistory]

// Update your counts with more data
(Map[Item, ItemHistory], List[Item) => Map[Item, ItemHistory]

// Generate an ordering between two items, with a % accuracy.
// Whichever has been seen more often before or after defines the ordering.
// The accuracy is determined by taking the ratio of times that ordering was correct vs the entire history.
(Item, ItemHistory) => (Item, ItemHistory) => (Ordering, Float)

// Apply some cutoff for filtering out inaccurate orderings
(Ordering, Float) => Ordering
</code>```

If you implement a class with methods along those lines, you can use it to generate heuristics. Because the ItemHistory is a monoid, you can easily train it offline with the data you have today, persist the ItemHistories in whatever way is convenient, and then continually update them with new training data as it comes in.

Body:
If you have literally no comparison function, then the only sane option is to pick the same order each time:

one = [1,2,3]
two = [4,5,6]
three = [7,8,9]

merge(one, two, three) == [1,4,7,2,5,8,3,6,9]

If there is some order, and the items can be compared for equality, but you can't encode the ordering explicitly, you can track how many times you've seen them in certain orders and use that to generate heuristics.

You can build up a history to base guesses on by storing all visits

I think these data types and algebra (expressed in pseudo-scala) would serve this purpose well.

// How many times a given item has been seen
type ItemCount = Map[Item, Int]

// NB ItemHistory forms a commutative monoid with zero as empty maps and mappend adding the counts together
case class ItemHistory(itemsSeenBefore: ItemCount, itemsSeenAfter: ItemCount)

// Fold over a list of input items and generate history for each one, storing the count of all items seen before and after
List[Item] => Map[Item, ItemHistory]

// Update your counts with more data
(Map[Item, ItemHistory], List[Item) => Map[Item, ItemHistory]

// Generate an ordering between two items, with a % accuracy.
// Whichever has been seen more often before or after defines the ordering.
// The accuracy is determined by taking the ratio of times that ordering was correct vs the entire history.
(Item, ItemHistory) => (Item, ItemHistory) => (Ordering, Float)

// Apply some cutoff for filtering out inaccurate orderings
(Ordering, Float) => Ordering

If you implement a class with methods along those lines, you can use it to generate heuristics. Because the ItemHistory is a monoid, you can easily train it offline with the data you have today, persist the ItemHistories in whatever way is convenient, and then continually update them with new training data as it comes in.


问:
Where to put common business logic in DDD with MVC
Providing I have the following scenario: I have a Web application where users can deposit money to their accounts (wire transfer). When a user deposits money to their account, they should click the "Refresh my balance" button to refresh their balance.

The business logic behind the "Refresh my balance" is the following:

Refresh balance, for example by calling a bank's webservice.

If there is new money, subtract a % from it as a fee.

The thing is that I would not like to allow refreshing balance without proceeding new deposit fees.

I have two services:

```<code>class AccountService
{
    //The following calls the bank webservice to get the new balance and updates the account entity
    public function refreshBalance(Account account);
}

class FeeService
{
    //The following checks if there are deposits, and if there are it subtract a fee
    public function proceedNewFees(Account account);
}
</code>```

My MVC controller action is the following right now:

```<code>public function refreshBalanceAction()
{
    $account = $this->accountService->getAuthenticatedAccount();
    $this->accountService->refreshBalance($account);
    $this->accountService->proceedNewFees($account);
}
</code>```

As you can see, in the controller I have some business logic.
I would like to move it to the Domain layer. Where is the best place to put this business logic from the controller? Create a new CommonLogicService? Implement it in the AccountModel (and if so, how to refer to the AccountService instance being in the AccountModel? DI?)?

答: The way you describe it, I would put the code to update the balance in a separate UpdateBalanceService-class. Then create a new class 'RefreshBalanceService' that contains both the UpdateBalanceService and a ProcessNewFeesService. The UpdateBalanceService-class would then call both services and perform the necessary actions. It is then a matter of implementing your refresh-code so that it uses the UpdateBalanceService class to do its work, which will in turn delegate to the subservices to perform its tasks.</p>


问:
The eponymous class of java
Any Java code will always have a class which has the same name as that of the file. The whole designed program resides inside this class. However, in C++ we don't have this provision. What is the rationale behind this approach where the whole code resides inside a class? What extra advantage does this provide? Can we create objects of this class and call the main function of this class as many times as we wish?</p>

答:
Question 1:

What is the rationale behind this approach where the whole code resides inside a class? What extra advantage does this provide?

I'll link to the same link that gnat provided as a possible duplicate because I think it gives some useful information.  The takeaway being that having each public class inhabit its own file allows for faster compilation.

In addition, one of the practical benefits of the Java way of doing things is that we can actually have multiple main functions.  In fact, all of your classes could have a main function.  You still typically only have one main function in a given project, but I've seen alternative main functions used to:

Drive unit/integration/regression tests

Create a version of the program with a limited feature set(could be useful when setting up a 'demo'?)

Question 2:

Can we create objects of this class and call the main function of this class as many times as we wish?

Technically, yes you can.  Lets say we have:

```<code>public class Foo
{
    public static void main(String[] args) {}
}
</code>```

We can then create objects of type Foo.  We can further call main from that object:

```<code>Foo obj = new Foo();
obj.main(null);
</code>```

However, you don't typically do this in Java.  main is a static function, meaning you don't need an object in order to call it.  It would be just as valid to call Foo.main(null);.  In the above obj.main(null);, the obj object is essentially ignored.  The Java compiler, by default, should give you a warning against doing this that looks like this:

The static method main(String[]) from the type Foo should be accessed in a static way.

Which again, is just telling you to drop the object and to use the class to call the static method.

However, to answer your question: you can call the static main function as many times as you'd like, just like any other static method.  Just remember that you're not calling the object's static main method, you're calling the class's static main method - because objects don't have static methods, classes have static methods.

Title: The eponymous class of java

Body:
Question 1:

What is the rationale behind this approach where the whole code resides inside a class? What extra advantage does this provide?

I'll link to the same link that gnat provided as a possible duplicate because I think it gives some useful information.  The takeaway being that having each public class inhabit its own file allows for faster compilation.

In addition, one of the practical benefits of the Java way of doing things is that we can actually have multiple main functions.  In fact, all of your classes could have a main function.  You still typically only have one main function in a given project, but I've seen alternative main functions used to:

Drive unit/integration/regression tests

Create a version of the program with a limited feature set(could be useful when setting up a 'demo'?)

Question 2:

Can we create objects of this class and call the main function of this class as many times as we wish?

Technically, yes you can.  Lets say we have:

public class Foo
{
    public static void main(String[] args) {}
}

We can then create objects of type Foo.  We can further call main from that object:

Foo obj = new Foo();
obj.main(null);

However, you don't typically do this in Java.  main is a static function, meaning you don't need an object in order to call it.  It would be just as valid to call Foo.main(null);.  In the above obj.main(null);, the obj object is essentially ignored.  The Java compiler, by default, should give you a warning against doing this that looks like this:

The static method main(String[]) from the type Foo should be accessed in a static way.

Which again, is just telling you to drop the object and to use the class to call the static method.

However, to answer your question: you can call the static main function as many times as you'd like, just like any other static method.  Just remember that you're not calling the object's static main method, you're calling the class's static main method - because objects don't have static methods, classes have static methods.


问:
Who should read Exception.Message if at all?
When designing exceptions should I write messages that a user or a developer should understand? Who should actually be the reader of exception messages?

I find exception messages aren't useful at all and I always have a hard time writing them. By convention the type of the exception should already tell us why something didn't work and custom properties might add even more information like file names, indexes, keys etc. so why repeating it in the message itself? An autogenerated message could also do and all what it had to contain is the name of the exception with a list of additional properties. This would be exactly as useful as a handwritten text.

Wouldn't it be better to not write messages at all but instead have special exception renderers that takes care of creating meaningful messages maybe in different languages rather then hardcoding them in code?

I've been asked whether either of those questions provide an answer to my question:

How to write a good exception message

Why do many exception messages not contain useful details?

I've read them both and I wasn't happy with their answers. They talk about users in general and focus on the content of the message itself rather then on the addressee and it turns out there can be at least two of them: the end-user and the developer. I never know which one I should speak to when writing exception messages.

I even think that the famous message doesn't have any real value at all as it just repeats the name of the exception type in different words so why bother writing them at all? I can perfectly generate them automatically.

To me exception message lacks a differentiation of its readers. A perfect exception would need to provide at least two versions of the message: one for the end-user and one for the developer. Calling it just a message is too generic. A developer message should be then written in English but the end-user's message might need to be translated into other languages. It is not possible to achieve all this with only one message so an exception would need to provide some identifier to the end-user message that as I just said, might be available in different languages.

When I read all the other linked questions I get the impression that an exception message is indeed intended to be read by an end-user and not a developer... a single message is like to have a cake and eat it too.

答:
The answer to this depends entirely on the exception.

The most important question to ask is "who can fix the problem?"  If the exception is caused by a file system error while you're opening a file, it may make sense to give that message to the end user.  The message may contain more information about how to fix the error.  I can think of one definitive case in my work where I had a plugin system that loaded DLLs.  If a user made a typo on the command line to load the wrong plugin, the underlying system error message actually contained useful information to allow them to correct the problem.

Most of the time, however, an uncaught exception can't be fixed by the user.  Most of them involve making changes in the code.  In these cases, the consumer of the message is clearly a developer.

The case of caught exceptions is more complicated because you have an opportunity to properly process the exception and throw a more friendly one.  One scripting language I wrote threw exceptions whose message was very clearly intended for a developer.  However, as the stack unwound, I added user-readable stack traces from within the scripting language.  My users very rarely could grok the message, but they could look at the stack trace in their script and figure out what happened 95% of the time.  For the remaining 5%, when they called me, we had not only a stack trace, but a developer-ready message to help me figure out what was wrong.

In all, I treat the Exception message as an unknown content.  Someone further upstream, who knew more about the implementations, has handed my software an exception.  Sometimes I have a hunch that unknown content will be useful to an end user, sometimes it's not.


问:
Should I add a layer to keep object always valid and immutable?
I am developing COM. A factory need to be initialized first by providing a ID. I can not pass arguments to IFactory instance via CoCreateInstance. So IFactory may need add a init method to be called then. (as approach 2)

I don't want to require client to call init explicitly (they may forget). So that I add a layer named IEntryPoint. This ensures GetFactory will return a verified IFactory without called init first. Then the IFactory instance will not have the state denoted it is valid or invalid. All its methods can be const. (as approach 1)

Is it over encapsulated if IEntryPoint only has GetFactory method?

Approach 1:
IEntryPoint::GetFactory ensures IFactory instance is valid if S_OK is returned.

```<code>interface IEntryPoint
{
    HRESULT GetFactory(size_t id, IFactory** ppFactory) const;
};

interface IFactory
{
    HRESULT GetInstance(size_t id, IInstance** ppInstance) const;
};

interface IInstance
{
    HRESULT Getter1() const;
    HRESULT Getter2() const;
    HRESULT Getter3() const;
};
</code>```

vs

Approach 2:
IFactory instance requires client to call init first.

```<code>interface IFactory
{
    HRESULT Init(size_t id);
    HRESULT GetInstance(size_t id, IInstance** ppInstance) const;
};

interface IInstance
{
    HRESULT Getter1() const;
    HRESULT Getter2() const;
    HRESULT Getter3() const;
};
</code>```

答:
Both solutions seem acceptable to me.

Your first solution is essentially a "factory factory", which might be perceived as unnecessary abstraction, but you are right that it firmly imposes the required workflow upon the user. This is a "pit of success" approach, where the obvious thing to do and the right thing to do are the same.

You are right that your second solution gives the client an opportunity to write a bug, an opportunity they will take!  But we can also assume that people writing COM clients are pretty smart and familiar with coclasses that need initialization.  I have written stateful COM objects with complex workflow requirements (multiple kinds of initialization and shutdown); the key to getting clients to write the code correctly was to be brutal about detecting client bugs and returning really, really harsh HRESULTS. My personal favourite was E_UNEXPECTED, which gave the error message "Catastrophic failure".

If you decide to go with your second option you should write code that detects invalid workflows -- calling Init() zero times, calling Init() two times, and so on -- and makes the factory object completely unusable any time that the contract is violated. Do not be lenient; that breeds bugs and undefined behaviour. If you have a workflow requirement then make that workflow as simple as possible, clearly document it, and force your clients to debug their code when they get it wrong.

A third pattern that I like is to modify your Init method so that instead of taking the ID it needs, instead it takes an object of type IFactoryClient that has a method GetFactoryId that returns an ID.  The caller is then required to supply a valid implementation of this interface. The factory then decides when to call the client to fetch its ID when it needs to. This technique is added overhead for the client, but it gives you a nice extension point for the future. Future versions of the factory can QueryInterface or QueryService the client to start a conversation between the client and the service about the level of services they expect from each other.


答:
This is a well-defined problem with a deterministic solution.  You can think of each list as forming part of a directed acyclic graph:

Then, constructing a merged order is simply a matter of using one of the well-known algorithms to find a topological sorting.  The more similarities you have between the lists, the fewer valid topological sorts you will have.  If there are no elements in common, the topological sort will work for that case as well.  It will list all possible ways to combine the three lists.  You just have to pick the one that suits you best aesthetically.

Title: Merging Sorted Lists (with no comparison function)

Body:
I have a few lists of items (which will likely but not necessarily have common elements). The lists are known to be sorted, but don't have a comparison function (they were manually put into the system in sorted order). I'd like to combine these lists into one list containing all the elements that is in a reasonable order given the existing ones.

Obviously there are edge cases and decisions to be made - I'm not too worried about the specifics, but rather I'd like a general approach to tackle the problem. Obviously if the two lists have nothing in common, there isn't much to be done besides appending one to the other, but that won't happen much.

As an example:

```<code>l1 = ['Task A', 'Task B', 'Task C', 'Task D']
l2 = ['Task B', 'Task B2', 'Task D', 'Task G']
l3 = ['Task A', 'Task C', 'Task E', 'Task D']
result = ['Task A', 'Task B', 'Task B2', 'Task C', 'Task E', 'Task D', 'Task G']
</code>```

Again, I realize there is no perfect solution, and the output is not mission critical, I just want it to be reasonably nicely ordered in most cases. Any help would be appreciated.


问:
Are (database) integration tests bad?
Some people maintain that integration tests are all kinds of bad and wrong - everything must be unit-tested, which means you have to mock dependencies; an option which, for various reasons, I'm not always fond of.

I find that, in some cases, a unit-test simply doesn't prove anything.

Let's take the following (trivial, naive) repository implementation (in PHP) as an example:

class ProductRepository
{
    private $db;

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

    public function findByKeyword($keyword) {
        // this might have a query builder, keyword processing, etc. - this is
        // a totally naive example just to illustrate the DB dependency, mkay?

        return $this->db->fetch("SELECT * FROM products p"
            . " WHERE p.name LIKE :keyword", ['keyword' => $keyword]);
    }
}
```

Let's say I want to prove in a test that this repository can actually find products matching various given keywords.

Short of integration testing with a real connection object, how can I know that this is actually generating real queries - and that those queries actually do what I think they do?

If I have to mock the connection object in a unit-test, I can only prove things like "it generates the expected query" - but that doesn't mean it's actually going to work... that is, maybe it's generating the query I expected, but maybe that query doesn't do what I think it does.

In other words, I feel like a test that makes assertions about the generated query, is essentially without value, because it's testing how the findByKeyword() method was implemented, but that doesn't prove that it actually works.

This problem isn't limited to repositories or database integration - it seems to apply in a lot of cases, where making assertions about the use of a mock (test-double) only proves how things are implemented, not whether they're going to actually work.

How do you deal with situations like these?

Are integration tests really "bad" in a case like this?

I get the point that it's better to test one thing, and I also understand why integration testing leads to myriad code-paths, all of which cannot be tested - but in the case of a service (such as a repository) whose only purpose is to interact with another component, how can you really test anything without integration testing?

答:
You are right to think of such a unit test as incomplete. The incompleteness is in the database interface being mocked. Such naive mock's expectation or assertions are incomplete.

To make it complete, you'd have to spare enough time and resources to write or integrate a SQL rules engine that would guarantee that SQL statement being emitted by subject under test, would result in expected operations.

However, the often forgotten and somewhat expensive alternative/companion to mocking is "virtualization".

Can you spin up a temporary, in-memory but "real" DB instance for testing a single function ? yes ? there, you have a better test, the one that does check actual data saved and retrieved.

Now, one might say, you turned a unit test into an integration test. There are varying views about where to draws the line to classify between unit tests and integration tests. IMHO, "unit" is an arbitrary definition and should fit your needs.

Title: Are (database) integration tests bad?


问:
Why do some prominent web sites use alphanumeric strings for resource IDs instead of numbers?
For example, the video IDs that YouTube uses are not a simple number, but instead a case-sensitive, alphanumeric string (like dQw4w9WgXcQ). Why do some websites, such as YouTube and Dailymotion use an alphanumeric string for these IDs instead of using a plain number?

An obvious answer might be because the resulting IDs are then shorter (encoding them in, for instance, Base-64 instead of Base-10), but what I find interesting is that other websites such as Vimeo do not use this technique.

Is there another good reason?

答:
Is there another good reason?

Sure. There are probably many good reasons, though they may not be the reasons motivating YouTube, DailyMotion, etc:

The underlying resource isn't identified with a numeric key.

A non-numeric identifier makes casual discovery harder. That is, you can't casually browse to another resource by incrementing the key.

The alphanumeric string may represent more than a simple key. Who knows what's in there?


答:
In addition to the answer of D Stanley you have to think about polymorphism. Methods like Math.Sqrt should always return the same value to the same input. Making the method static is a good way to make this point clear, since static methods are not overrideable.

You mentioned the ToString()-method. Here you may want to override this method, so the (sub)class is represented in an other way as String as its parent class. So you make it an instance Method.

Title: Why is Math.Sqrt() a static function?

Body:
In a discussion about static and instance methods, I always think, that Sqrt() should be a instance method of number types instead of a static method. Why is that? It obviously works on a value.

```<code> // looks wrong to me
 var y = Math.Sqrt(x);
 // looks better to me
 var y = x.Sqrt();
</code>```

Value types obviously can have instance methods, as in many languages, there is an instance method ToString().

To answer some questions from the comments: Why should 1.Sqrt() not be legal? 1.ToString() is.

Some languages do not allow to have methods on value types, but some languages can. I am talking about these, including Java, ECMAScript, C# and Python (with __str__(self)defined). The same applies to other functions like ceil(), floor() etc.


问:
Why no developer API in C++ for Google or Yahoo mail?
I was trying to do some C++ coding that can send files from my laptop to my webmail account. It took me about 10 minutes to realize that there is no easy way to do this. Look into these links:

GMAIL: http://code.google.com/apis/gmail/oauth/code.html

YAHOO: http://developer.yahoo.com/mail/

I am trying to understand why PHP or Python or Java support exist but no C++. No flame wars, I love all programming languages and their creators equally but I am curious to understand the logic behind such implementation choices.

答:
Why no developer API in C++ for Google or Yahoo mail?

Why no developer API in Haskell, Erlang or Brainfuck for Google or Yahoo mail? Because nobody cared enough or needed it so far. Luckily, this is all just HTTP, XML and JSON, so you can build API bindings for any language/platform you want.

ContentLicense: CC BY-SA 2.5


答:
First, see the CAP Theorem. It's similar to the old aphorism of "Fast, Good, Cheap: Pick 2."

In theoretical computer science, the CAP theorem, also known as Brewer's theorem, states that it is impossible for a distributed computer system to simultaneously provide all three of the following guarantees:

Consistency (all nodes see the same data at the same time)

Availability (a guarantee that every request receives a response about whether it succeeded or failed)

Partition tolerance (the system continues to operate despite arbitrary partitioning due to network failures)

Integers

Maintaining a serialized number requires consistency... one place that is the keeper of numbers. In large systems this can become a bottleneck, a single point of failure, or both. In distributed systems, it is common to start relaxing this constraint (Consistency) in favor of the other two.

There are strategies to maintain serialized numeric identities in distributed systems, like the HI-LO algorithm or its derivatives, but it is still very possible to skip large swaths of numbers in case of node failures.

UUIDs

Another common method is to use a UUID, a randomly generated identifer (which is twice the size of Int64), which has a pretty high (but not 100%) chance of being unique from any other generated UUID. It's basically just a very large random number. This is nice for client operations, because the client can generate it with a pretty good chance of uniqueness, and subsequently use it to identify or track things. But collisions (same ID being generated) are possible (especially if the client has a terrible RNG) and still must be dealt with.

My suspicion is that the youtube identifers are some shorter variation of a uuid which is then converted to a variation of base64 without punctuation. Because punctuation kills the ability to be used in links. Hence, it's a very large number (either random or serialized) that has been converted to text so that it is shorter.

Strings

One identifier format that is fairly popular is "entity-#" or "system-entity-#" if you have a number of inter-operating systems. The # is generated either consistently by the owning system (still distributed in the sense that there are multiple systems, microservices, whatever) or with a HI-LO variation. And for display purposes, it's fairly trivial to strip off the prefix and just use the number portion.

Choosing

The above is obviously not a complete list, and in the end they are all just binary numbers on disk. The reasons to use one or the other are the architectural trade-offs that are most favorable to your system. UUIDs have the most convenient architectural properties for distributed systems, but are bad with the human factor (user can remember and type 102875, but not B9FE6378-E76C-40D5-883B-72FE376952A4, a UUID I just made).

If there is any ambiguity in what is being identified, neither UUIDs or numbers are particularly useful but strings are great there. At least serialized numbers can give you an idea of scale which can hint at what is being referenced.

There are, of course, security concerns with a string identifier like I mentioned, because it can give would-be attackers insight into your system.

I have even seen a blog post shunning numeric identifiers because of the impression it gives when a user is given low numbered resources (e.g. Account #5)... Not that I think this has merit. After all, you can always start your number sequence at 6-digits if user-confidence is a valid business concern. Edit: Trend analysis could be a security issue with incrementing IDs.

Title: Why do some prominent web sites use alphanumeric strings for resource IDs instead of numbers?

Body:
For example, the video IDs that YouTube uses are not a simple number, but instead a case-sensitive, alphanumeric string (like dQw4w9WgXcQ). Why do some websites, such as YouTube and Dailymotion use an alphanumeric string for these IDs instead of using a plain number?

An obvious answer might be because the resulting IDs are then shorter (encoding them in, for instance, Base-64 instead of Base-10), but what I find interesting is that other websites such as Vimeo do not use this technique.

Is there another good reason?

ContentLicense: CC BY-SA 4.0


答:
Unlike String.substring, Number.sqrt is not really an attribute of the number but rather a new result based on your number. I do think passing your number to a squaring function is more intuitive.

Moreover, the Math object contains other static members and it makes more sense to bunch them together and use them in a uniform manner.

Title: Why is Math.Sqrt() a static function?


问:
Reducing the arity of functions
I have discovered that reducing the arity of functions in my code to zero or one improves their non-functional characteristics significantly, such as  testability, maintainability and their composability.

This must have been identified elsewhere - does this approach have a name?

答:
Yes, an arity of one is a property of a mathematical functions. The case arity=0 is really arity=1 with the parameter of void or unit. And 1 input is not the only property, but perhaps lends itself to some of the others (e.g. no side effects). Maybe your functions tend to conform to the definition of Mathematical functions?

Here is a good article on mathematical functions (the basis for functional programming) with their benefits and drawbacks in the context of programming. Here is an excerpt.

As you can see from the diagrams, there is always exactly one input and one output for a mathematical function. This is true for functional programming languages as well, although it may not be obvious when you first use them.

For people scratching their heads right now, in practice in functional programming, you don't really code only single-parameter functions and nothing else. Through math trickery, you can show that an N-parameter function can be changed into N single-parameter functions with currying. (So, the compiler does that for you.)

Maintainability probably has more to do with following DRY and SRP, since your functions are broken down into individual operations.

Composability is one of the primary strengths of math functions. I won't take time to go into all that f(g(x)) stuff here. And I'm probably not as good at explaining it as others, so here's another link on that subject.

Testability is also really high with math functions since they lack side effects which have to be accounted for. By definition they also give repeatable results.

Title: Reducing the arity of functions


问:
Should we include the NuGet PACKAGE folder in version control?
In a C# or VB.NET project, should we include the PACKAGE folder (NuGet package folder that is created in the root of my project that contains the nupkg files and other content) to our source control repository (Git for instance)?</p>

答:
It depends.

Check out Bart van Ingen Schenau's answer to determine if it's possible to ignore the packages folder at all.

Basically: yes, NuGet is designed so that you can ignore the packages folder and NuGet will pull everything from the Internet if it's missing.

But should you ignore it? I say: it depends.

IMO it's a question of "can we continue working in case the package repository is not available" (be it temporarily or permanently)

For my personal OSS projects, I have the packages folder ignored in all of them.

When nuget.org is offline, I'll just wait and continue another day.

But it's something different at work.

Sure, you probably still have the packages locally on some machine, but is saving some space worth the hassle when your builds are breaking because your build server can't reach nuget.org?

We decided that space is cheap and we don't want the hassle, that's why we're committing the packages folder to source control.


问:
Does syntax really matter in a programming language?
One of my professors says "the syntax is the UI of a programming language", languages like Ruby have great readability and it's growing, but we see a lot of programmers productive with C\C++, so as programmers does it really matter that the syntax should be acceptable?

I would love to know your opinion on that.

Disclaimer: I'm not trying to start an argument. I thought this is a good topic of discussion.

Update: This turns out to be a good topic. I'm glad you are all participating in it.

答:
I think what really matters is API access, and availability of low-level functionality (like memory control and locking) when needed. Most other languages come with these features included. Problem is, when you need additional functionality you often have to use a language like C to implement it. And it is cumbersome interfacing C with the language you are using.

For everything except web development (and math) I've found that C/C++ is still THE language of an operating system and an application. It's what is supported most of the time for true multi-threaded, preforming, cross-platform application development. And the syntax of C is okay. Just very simple and relatively verbose. Amazing Syntax doesn't really matter that much. Power and API availability does We all need to interface with other people's code (which is most of the time written in C or its derivitives).


答:
Well, in Java there is a wrapper for every basic type.

And basic types are not class-types, and have no member-functions.

So, you have the following choices:

Collect all those helper-functions into a pro-forma-class like Math.

Make it a static function on the corresponding wrapper.

Make it a member-function on the corresponding wrapper.

Change the rules of Java.

Let's rule option 4 out, because... Java is Java, and adherents profess to like it that way.

Now, we can also rule out option 3 because while allocating objects is fairly cheap, it isn't free, and doing that over and over again does add up.

Two down, one still to kill: Option 2 is also a bad idea, because it means every function must be implemented for every type, one cannot rely on widening conversion to fill the gaps, or the inconsistencies will really hurt.

And taking a look at java.lang.Math, there are lots of gaps, especially for types smaller than int respective double.

So, in the end the clear victor is option one, collecting them all in one place in a utility-function-class.

Returning to option 4, something in that direction actually happened much later: You can ask the compiler to consider all the static members of any class you want when resolving names for quite a long time now. import static someclass.*;

As an aside, other languages don't have that problem, either because they have no prejudice against free functions (optionally using namespaces) or far fewer small types.

Title: Why is Math.Sqrt() a static function?


问:
Purpose of assertion messages
Some languages and libraries can associate assertion messages with assertions. Such assertion messages are included in error messages when the assertion does not hold. Examples are Java, Class::Contract, ContractLib and to some extent Eiffel itself (labels).

If I haven't overlooked something, assertion messages can either (1) describe the assertion or (2) describe the situation when the assertion does not hold:

```<code>// describes the assertion
assert !socketChannel.isBlocking() :
    "the socket must not be blocking to be selectable";

// describes the situation when the assertion does not hold
assert !socketChannel.isBlocking() :
    "the socket is blocking and thus not selectable";
</code>```

Both types of assertion messages could be replaced by comments.

Oracle's documentation leaves the semantics to the programmer and states that the purpose of assertion messages is to help the programmer. So it presents the choice as a personal preference. However, I would like to be more objective about this choice. My current thinking is this as follows:
Ideally, the assertion is self-explanatory and needs no description. If it does, it is better to describe it in a comment than in an assertion message as the description refers to code. Users should never see assertion errors (uncaught exception in general) and therefore the assertion message does not need to describe what went wrong.

Is there an additional explanation of which type of assertion messages is better or why both types are unnecessary (other than personal preference)?

答:
You seem to be dividing the people that may encounter the errors thrown from the assertion into two categories:

You, which should be able to understand what went wrong from the auto-generated message, and which will start debugging from the definition

End users, which should have never encountered the assertion in the first place, and which will mail the assertion text to you / open a ticket in your bug tracker / stop using your product and switch to the competitor / sue you for causing them to lose valuable commercial data

This may or may not be true for your own project, but in most reasonably sized projects other categories of people exist:

Other programmers that use your library

Your teammates, working on other parts of the project

Contributors to open source projects, limiting their modifications to specific parts of the project

You yourself, two months after the last time you've hacked around that area of the project

These people are fundamentally different from the original two categories:

Unlike you, they are not familiar with the part of the code where the assert resides. Looking at unfamiliar code written by other peoples is rarely a very enjoyable pastime - even if that code is well designed and documented.

Unlike your end users, they don't have the privilege of not having to understand the assertions. They are developers, and it's perfectly normal for developers to use functions/classes/modules wrong and trigger assertions there.

So, these people will see the assertions and will need to understand them(because it might be their code that did something wrong), but they won't be as comfortable as you going to the actual assert statement, looking at it's surrounding, and understanding what was going on. If you were already going to write a comment describing what (you believe) went wrong when that assertion is triggered, why not put it in the assertion's error message and make these coders' lives easier?

Title: Purpose of assertion messages


问:
Difference between Software Engineering and IT?
I see mostly everyone distinguishes between being a Software Engineer and being in IT on the jobs sections of their site. What are the definitions of each, and the distinction between them?</p>

答:
IT (Information Technology) is a catch-all for the industry at present, any job that is primarily to do with the operation of computers or developing for them is within the "IT industry/sector".

However, within the UK at least, job descriptions and adverts tend to reserve "IT" within a job title, as administration, procurement and technical support for company computing resources.  Everything from sysadmin work, to frontline technical support, or hardware repair and procurement/policy for internal IT.

Software Engineering specifically means developing software, analysis, design, programming - creating new software, or maintaining/altering existing software.  This is very different to a technical role.  The skill set is quite different, technical support guys are not necessarily programmers and (contrary to a lot of non-IT peoples' belief structures) software engineers are not necessarily any good at technical support.  Though Software Engineers are within the "IT sector", which confuses the matter slightly in the job market.

OwnerDisplayName: Jungle Hunter


答:
Regarding what the message associated should describe, you should stick with the assertive form which express what is expected. This is not only a preference: if you try explaining what went wrong, you'll have to negate your logic in your string and it might in fact become false, or ambiguous.
Just explain what was supposed to happen.

But this is not enough.

You should provide more context and make your assumptions even more explicit by telling us why the assertion is supposed to hold.
In no specific language:

```<code>assert (sensor >= threshold) :
  "Sensor is assumed to be above threshold at this point
   because we are in a tightly optimized function (well,
   that's what Greg always claims) and the caller is
   responsible for doing sanity checks (see check-sensor
   function)."
</code>```

(though the passive-aggressive remark, while useful, should probably be removed)

If you want to prevent users from seing assertions and/or exceptions, why stop at the string? comment the whole expression!
More seriously, you should handle your exceptions whenever you can provide  a useful feedback and possibly alternate paths. Sometimes your code is simply wrong despite your effort and your system will let internal error message bubble up to the highest-level of the code. But this is still fine, you can catch and log them before they reach the screen.

Title: Purpose of assertion messages

Body:
Some languages and libraries can associate assertion messages with assertions. Such assertion messages are included in error messages when the assertion does not hold. Examples are Java, Class::Contract, ContractLib and to some extent Eiffel itself (labels).

If I haven't overlooked something, assertion messages can either (1) describe the assertion or (2) describe the situation when the assertion does not hold:

```<code>// describes the assertion
assert !socketChannel.isBlocking() :
    "the socket must not be blocking to be selectable";

// describes the situation when the assertion does not hold
assert !socketChannel.isBlocking() :
    "the socket is blocking and thus not selectable";
</code>```

Both types of assertion messages could be replaced by comments.

Oracle's documentation leaves the semantics to the programmer and states that the purpose of assertion messages is to help the programmer. So it presents the choice as a personal preference. However, I would like to be more objective about this choice. My current thinking is this as follows:
Ideally, the assertion is self-explanatory and needs no description. If it does, it is better to describe it in a comment than in an assertion message as the description refers to code. Users should never see assertion errors (uncaught exception in general) and therefore the assertion message does not need to describe what went wrong.

Is there an additional explanation of which type of assertion messages is better or why both types are unnecessary (other than personal preference)?

Body:
Regarding what the message associated should describe, you should stick with the assertive form which express what is expected. This is not only a preference: if you try explaining what went wrong, you'll have to negate your logic in your string and it might in fact become false, or ambiguous.
Just explain what was supposed to happen.

But this is not enough.

You should provide more context and make your assumptions even more explicit by telling us why the assertion is supposed to hold.
In no specific language:

assert (sensor >= threshold) :
  "Sensor is assumed to be above threshold at this point
   because we are in a tightly optimized function (well,
   that's what Greg always claims) and the caller is
   responsible for doing sanity checks (see check-sensor
   function)."

(though the passive-aggressive remark, while useful, should probably be removed)

If you want to prevent users from seing assertions and/or exceptions, why stop at the string? comment the whole expression!
More seriously, you should handle your exceptions whenever you can provide  a useful feedback and possibly alternate paths. Sometimes your code is simply wrong despite your effort and your system will let internal error message bubble up to the highest-level of the code. But this is still fine, you can catch and log them before they reach the screen.


答: Another thing to consider is that programming languages with nicer syntax are easier to parse, thus making the compiler easier to write, faster, and less prone to bugs.  </p>

Title: Does syntax really matter in a programming language?

Body:
One of my professors says "the syntax is the UI of a programming language", languages like Ruby have great readability and it's growing, but we see a lot of programmers productive with C\C++, so as programmers does it really matter that the syntax should be acceptable?

I would love to know your opinion on that.

Disclaimer: I'm not trying to start an argument. I thought this is a good topic of discussion.

Update: This turns out to be a good topic. I'm glad you are all participating in it.


问:
How to debug javascript in browsers that don't have a console interface?
It's unbelievable but my company is still building web app on IE 6. Although the online dashboard for IE 6 is limited in functionality, I've found extremely difficult to debug anything on it. It's probably the most challenging task in my career, and I'm considering to leave the job because it takes way too much time to do anything.

On Chrome, I could simply add a breakpoint in a JavaScript source, but this is not possible on IE 6. Nothing on IE 6 seems make sense, for example, the CSS simply don't work. There is no web console.

How did the programmers 10-15 years ago managed to debug anything? Currently, I'll have to show an alert box to debug a loop, so I'd have to close off the alert box for each iteration of the loop. 100 alert boxes for a loop with 100 iterations...

答:
Actually, lets go a bit further:

There are two kinds of browsers - ones that provide a console interface with a log method, and ones that don't.

Right before you do any other javascript, have the following code (assuming you have jQuery - adapt if you use something else):

```<code>if (!window.console) {
   var consoleElement = $("<div>");
   consoleElement.addClass("console"); // use CSS to position and style this element for testing

   $("body").append(consoleElement);

   console = {
       log: function(message) {
           var messageElement = $("<span>");
           messageElement.addClass("console")
               .text(message);

           $("#console").append(messageElement);
       }
   };
}
</code>```

A more complete approach can be found at https://stackoverflow.com/a/13817235/184124

Body:
Actually, lets go a bit further:

There are two kinds of browsers - ones that provide a console interface with a log method, and ones that don't.

Right before you do any other javascript, have the following code (assuming you have jQuery - adapt if you use something else):

if (!window.console) {
   var consoleElement = $("<div>");
   consoleElement.addClass("console"); // use CSS to position and style this element for testing

   $("body").append(consoleElement);

   console = {
       log: function(message) {
           var messageElement = $("<span>");
           messageElement.addClass("console")
               .text(message);

           $("#console").append(messageElement);
       }
   };
}

A more complete approach can be found at https://stackoverflow.com/a/13817235/184124


答: Have you tried downloading the Internet Explorer Developer Toolbar? It will help you debug and troubleshoot your webpages on IE6 or other versions: http://www.microsoft.com/en-us/download/details.aspx?id=18359

Title: How to debug javascript in browsers that don't have a console interface?

Body:
It's unbelievable but my company is still building web app on IE 6. Although the online dashboard for IE 6 is limited in functionality, I've found extremely difficult to debug anything on it. It's probably the most challenging task in my career, and I'm considering to leave the job because it takes way too much time to do anything.

On Chrome, I could simply add a breakpoint in a JavaScript source, but this is not possible on IE 6. Nothing on IE 6 seems make sense, for example, the CSS simply don't work. There is no web console.

How did the programmers 10-15 years ago managed to debug anything? Currently, I'll have to show an alert box to debug a loop, so I'd have to close off the alert box for each iteration of the loop. 100 alert boxes for a loop with 100 iterations...


问:
Why throw a 'must implement this function' exception rather than making the function abstract?
In the Android support libraries here the destroyItem and instantiateItem functions throw an exception if they aren't overriden:

```<code>175        throw new UnsupportedOperationException(
176                "Required method instantiateItem was not overridden");
</code>```

Why wouldn't the developers just make the functions abstract? Wouldn't that be the more correct way of ensuring the functions are overridden, from an OOP perspective?

答:
The makers if of the adapter most likely do not want to force the developers extending the class to implement said methods unless you really need them.

You can extend the class without the need to use the mentioned methods, if they were declared abstract, you would have to write code you would never use, or throw the exception yourself.

Go ahead and check YAGNI.


答:
Use Internet Explorer 11 and have it emulate Internet Explorer 5.

F12 -> Emulation -> Document Mode

Internet Explorer will then behave like Internet Explorer 5/6, but will offer you all the modern debugging tools.

Regarding your question

How did the programmers 10-15 years ago managed to debug anything?

Javascript applications used to be far simpler back then, so javascript debugging capabilities didn't need to be complex either. There wasn't that much you could do with Javascript anyway. Lots of features we take for granted now didn't exist back then. More complex applications were usually implemented purely server-sided or with plugins like Adobe Macromedia Flash.

Because CSS was so poor and inconsistent back then, lots of people abused tables nested in tables nested in tables to create layouts. Although frowned upon today, this was the most reliable and convenient way to get elements to where you wanted them to be.


问:
How to start using DDD in designing a "library" application
I want to design an online book reader. The first step is describing all the use cases which I have listed below:

I should be able to search a book by title.

I should be able to borrow a book.

I should be able to bookmark a borrowed book.

The system should allow one user per book at a time.

The system should allow to add a new book.

The system should allow to delete an existing book.

That said, I know now I need some Service Objects which would operate on Entities / Value Objects to get the thing done. I am deferring the database design / decision for now as its not considered a good practice. For the similar reasons Delivery mechanisms too is deferred.

After some reading I came to the conclusion that I would need the following:

Services (Algorithms without any states, depends on entities / values)

SearchBook (Takes a title and gives the result back)

BorrowService (Checks if a book can be borrowed)

Member service (Enroll/Unroll members in a library)

Entities (real world mutable objects with unique ID)

Library

Book (ISBN number as a UID)

User (Email as UID, it can be author or reader)

Associations

An author can have many books under his name, a user can only borrow one book at a time. A library can hold many books at a time, it can have many members too.

Notes

For simplicity there will be only single library / store.

No two users can read the same book at a time.

Questions

I am not able to find any value object till now or I am not able to recognize / find it?

I have followed Clean Architecture for some time and helped to build a toy project before. What is the difference between this and DDD?

Am I on the right track?

答:
I am not able to find any value object till now or I am not able to recognize / find it?

Value objects may be difficult to find in some domains, although in your case I would probably make ISBN a value object since it has formally defined structure and there is some business logic connected with it. Sometimes it is a design decision whether to represent something as a value object or an entity or just a field of an entity.

I have followed Clean Architecture for some time and helped to build a toy project before. What is the difference between this and DDD?

These are two completely different things.

Clean Architecture is an Architectural Pattern which defines the structure of a whole program.

DDD is a method for modelling Domain Logic and separating it from the rest of the program.

They are orthogonal to each other (both may be applied in the same program).

Am I on the right track?

Yes, you are on the right track with modelling. The best source of knowledge on DDD is the book by Eric Evans (author of the method).

Make sure that methods of entities and value objects contain only domain logic (state changes and constraints). All platform-specific code should be elsewhere (presentation, persistence, logging, threading, etc). Entities should have domain methods that are named after business operations. These methods should be called from services (only one call/entity/operation in most cases).


问:
Object oriented design - Designing business rules
I have trouble designing classes that reflect different business behaviors/rules. An example to explain my case:

```<code>- a tour has a departure
- a departure may be a guaranteed departure
if a departure is guaranteed:
    - a guaranteed departure may have a date that, starting from that date:
    * departure cannot be cancelled by tour agency for any reason
    * before that date in can be cancelled
    * but it may not have a date indicator, which means departure can't be cancelled
else:
   - departure can be cancelled anytime by agency for any reason
</code>```

What's the correct way to design classes in such scenarios?

A simple boolean field (cancellable) and simple Date field (cancellableBefore)  in Departure class

when cancellable == true and cancellableBefore == null => always cancellable

when cancellable == true and cancellableBefore != null => cancellable if now < cancellableBefore

...

and so on...

or is there a more OO answer to this?

答:
To make this more OO, create three classes that represent your departure and isolate the logic to determine if it can be canceled there. The classes inherit from a common interface IDeparture with a method canBeCanceledOn that takes a datetime indicating the point in time when a cancellation is attempted.

Next, create three classes for your departures. RegularDeparture can be cancelled at any time and will always return true for the canBeCanceledOn. FixedDeparture would be a fixed departure that cannot be canceled and always return false for canBeCanceledOn. CancellableUntilSetDateDeparture would use logic to determine if the date up to which the departure can be canceled is before the provided cancellation attempt date.

This way you have classes that are responsible for one thing only (represent a type of departure) and you can add additional departure types as needed and 'plug' them into Tours.


问:
Readme.txt vs. README.txt
I have just forked a project in Github, made my changes etc. This got me wondering: I see mostly README.txt in opensource projects and the file I edited was Readme.txt. Is this some sort of standartisation or should I have left it as is?</p>

答:
Traditionally the file was called README in uppercase because command-line environments that use alphabetical ordering would then put the file at the top. This makes them easily visible in big directories.

It's most likely a holdover from the Unix/Linux world where you would download sources and then build your software. Having files like README and INSTALL at the top of your 'list directory contents' view makes it easier to see that they are there, instead of having to browse the entire contents from a command-line interface. The same basic principle works for github as well (and actually works in GUI interfaces too, come to think of it, so it might still hold merit)

By no way a hard rule, but very likely something that everybody is doing as a habit because other projects are doing it. Unless there is some explicit reason NOT to, you should probably use all caps just because you'll see it being used that way in lots of other projects. It's also the default naming Github uses when you create a new repository.

Title: Readme.txt vs. README.txt


答: README is usually written in upper case. In this way the ls Unix command placed the file near the beginning of the directory listing (upper-case letters comes before lower-case letters in ASCII ordering).

Title: Readme.txt vs. README.txt

Body: I have just forked a project in Github, made my changes etc. This got me wondering: I see mostly README.txt in opensource projects and the file I edited was Readme.txt. Is this some sort of standartisation or should I have left it as is?</p>


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I work in Japan.

I'd say 40-60% of code I see uses English variable/method/class names. Sometimes Japanese and English is intermixed. Comments and commit messages are almost always in Japanese.

Consequently you see a lot of code written in poor English, and it's quite bad because it hurts readability a lot. Unfortunately, code done in Japanese isn't much better, either since Japanese written in Alphabet (in particular, lack of Kanji) is tough to read.

Sometimes engineers do use 2 byte character (Kanji/Hiragana etc.) method/variable/class names (it's legal in e.g. Java) but this frequently causes great pain because of character encodings (build blows up etc.) and is usually frowned upon.

There is a lot more emphasis on English for Japanese Engineers in the Japanese job market, so I'm hoping that this situation improves soon (I code entirely in English and I believe all Japanese engineers should, too)..


问:
Why is Math.Sqrt() a static function?
In a discussion about static and instance methods, I always think, that Sqrt() should be a instance method of number types instead of a static method. Why is that? It obviously works on a value.

```<code> // looks wrong to me
 var y = Math.Sqrt(x);
 // looks better to me
 var y = x.Sqrt();
</code>```

Value types obviously can have instance methods, as in many languages, there is an instance method ToString().

To answer some questions from the comments: Why should 1.Sqrt() not be legal? 1.ToString() is.

Some languages do not allow to have methods on value types, but some languages can. I am talking about these, including Java, ECMAScript, C# and Python (with __str__(self)defined). The same applies to other functions like ceil(), floor() etc.

答:
One point that I don't see mentioned explicitly (although amon alludes to it) is that square root can be thought of as a "derived" operation: if the implementation doesn't provide it for us, we can write our own.

Since the question is tagged with language-design, we might consider some language-agnostic description. Although many languages have different philosophies, it is very common across paradigms to use encapsulation to preserve invariants; i.e. to avoid having a value which doesn't behave as its type would suggest.

For example, if we have some implementation of integers using machine words, we probably want to encapsulate the representation somehow (e.g. to prevent bit shifts from changing the sign), but at the same time we still need access to those bits to implement operations like addition.

Some languages may implement this with classes and private methods:

```<code>class Int {
    public Int add(Int x) {
      // Do something with the bits
    }
    private List<Boolean> getBits() {
      // ...
    }
}
</code>```

Some with module systems:

```<code>signature INT = sig
  type int
  val add : int -> int -> int
end

structure Word : INT = struct
  datatype int  = (* ... *)
  fun add x y   = (* Do something with the bits *)
  fun getBits x = (* ... *)
end
</code>```

Some with lexical scope:

```<code>(defun getAdder ()
   (let ((getBits (lambda (x) ; ...
         (add     (lambda (x y) ; Do something with the bits
     'add))
</code>```

And so on. However, none of these mechanisms are needed for implementing square root: it can be implemented using the public interface of a numeric type, and hence it doesn't need access to the encapsulated implementation details.

Hence the location of square root comes down to the philosophy/tastes of the language, and of the library designer. Some may choose to put it "inside" the numeric values (e.g. make it an instance method), some may choose to put it at the same level as the primitive operations (this might mean an instance method, or it might mean living outside the numeric values, but inside the same module/class/namespace, e.g. as a standalone function or static method), some might choose to put it in a collection of "helper" functions, some might choose to delegate it to third-party libraries.

Title: Why is Math.Sqrt() a static function?

Body:
One point that I don't see mentioned explicitly (although amon alludes to it) is that square root can be thought of as a "derived" operation: if the implementation doesn't provide it for us, we can write our own.

Since the question is tagged with language-design, we might consider some language-agnostic description. Although many languages have different philosophies, it is very common across paradigms to use encapsulation to preserve invariants; i.e. to avoid having a value which doesn't behave as its type would suggest.

For example, if we have some implementation of integers using machine words, we probably want to encapsulate the representation somehow (e.g. to prevent bit shifts from changing the sign), but at the same time we still need access to those bits to implement operations like addition.

Some languages may implement this with classes and private methods:

class Int {
    public Int add(Int x) {
      // Do something with the bits
    }
    private List<Boolean> getBits() {
      // ...
    }
}

Some with module systems:

signature INT = sig
  type int
  val add : int -> int -> int
end

structure Word : INT = struct
  datatype int  = (* ... *)
  fun add x y   = (* Do something with the bits *)
  fun getBits x = (* ... *)
end

Some with lexical scope:

(defun getAdder ()
   (let ((getBits (lambda (x) ; ...
         (add     (lambda (x y) ; Do something with the bits
     'add))

And so on. However, none of these mechanisms are needed for implementing square root: it can be implemented using the public interface of a numeric type, and hence it doesn't need access to the encapsulated implementation details.

Hence the location of square root comes down to the philosophy/tastes of the language, and of the library designer. Some may choose to put it "inside" the numeric values (e.g. make it an instance method), some may choose to put it at the same level as the primitive operations (this might mean an instance method, or it might mean living outside the numeric values, but inside the same module/class/namespace, e.g. as a standalone function or static method), some might choose to put it in a collection of "helper" functions, some might choose to delegate it to third-party libraries.


答:
You have correctly observed that there is a curious symmetry at play here.

Whether I say sqrt(n) or n.sqrt() does not really matter, they both express the same thing and which one you prefer is more a matter of personal taste than anything else.

That is also why there is a strong argument from certain language designers to make the two syntaxes interchangeable. The D programming language already allows this under a feature called Uniform Function Call Syntax. A similar feature has also been proposed for standardization in C++. As Mark Amery points out in the comments, Python allows this too.

This is not without problems. Introducing a fundamental syntax change like this has wide-ranging consequences for existing code and is of course also a topic of controversial discussions among developers who have been trained for decades to think of the the two syntaxes as describing different things.

I guess only time will tell whether the unification of the two is feasible in the long run, but it is definitely an interesting consideration.

Title: Why is Math.Sqrt() a static function?


答:
In Java and C# ToString is a method of object, the root of the class hierarchy, so every object will  implement the ToString method. For an Integertype it's just natural that the implementation of ToString would work this way.

So you reasoning is wrong. The reason value types implement ToString is not that some people were like: hey let's have a ToString method for Value types.
It's because ToString is already there and it's "the most natural" thing to output.

Title: Why is Math.Sqrt() a static function?


答:
All-uppercase letters stand out and make the file easily visible which makes sense because it is probably the first thing a new user would want to look at.  (Or, at least, should have looked at…) As others have already said, file names starting with a capital letter will be listed before lower-case names in ASCIIbetical sorting (LC_COLLATE=C) which helps make the file visible at a first glance.

The README file is part of a bunch of files a user of a free software package would normally expect to find. Others are INSTALL (instructions for building and installing the software), AUTHORS (list of contributors), COPYING (license text), HACKING (how to get started for contributing, maybe including a TODO list of starting points), NEWS (recent changes) or ChangeLog (mostly redundant with version control systems).

This is what the GNU Coding Standards have to say about the README file.

The distribution should contain a file named README with a general overview of the package:

the name of the package;

the version number of the package, or refer to where in the package the version can be found;

a general description of what the package does;

a reference to the file INSTALL, which should in turn contain an explanation of the installation procedure;

a brief explanation of any unusual top-level directories or files, or other hints for readers to find their way around the source;

a reference to the file which contains the copying conditions. The GNU GPL, if used, should be in a file called COPYING. If the GNU LGPL is used, it should be in a file called COPYING.LESSER.

Since it is always good to strive for the least surprise of your users, you should follow this convention unless there are compelling reasons for a deviation. In the UNIX world, file name extensions were traditionally used sparingly so the canonical name of the file is README without any suffix. But most users probably would have no troubles understanding that a file named README.txt has the same meaning. If the file is written in Markdown, a file name like README.md might also be reasonable. Avoid using more complicated markup languages like HTML in the README file, however, because it should be convenient to read on a text-only terminal. You can point users to the manual of the software or its on-line documentation, that might be written in a more sophisticated format, for details from the README file.

Title: Readme.txt vs. README.txt


问:
Should listener interfaces be nested?
In Java the observer pattern is implemented with at least one interface (often ending in Listener or Observer). Such interfaces can be placed nested inside the class or be separate, for example:

```<code>public class FooService extends RunnableService {
    // Nested interface
    public interface Listener {
        // ...
    }

    private Collection<Listener> listeners;

    // ...
}

// Separate interface
public interface FooServiceListener {
    // ...
}

public class FooService extends RunnableService {
    private Collection<FooServiceListener> listeners

    // ...
}
</code>```

The name of the nested interface is only one character longer and does not have to be prefixed with the name of the class to avoid simple name conflicts.

Are there other arguments for or against either one of both variants (besides personal preference)?

答:
If you embed the interface within the class, you are tightly coupling the interface to an implementation. This pre-supposes that this implementation will be the only one for that interface, which is a bad assumption to make. In fact, with this thinking, why even have the interface in the first place.

Such coupling of the interface to the implementation is example of the entourage anti-pattern in action: using the interface forces you to bring along an implementation with it, even if not needed.

So the conclusion is: keep the two separate. They are separate entities and should not be coupled.

Title: Should listener interfaces be nested?


答:
Did you consider the Book "Implementing Domain Driven Design" by "Vaugh Vernon"? It gives a view on the concepts behind DDD from an implementation perspective with lots of really good real-live examples.

Regarding your explicit questions:

Clean Architecture, as stated by Maciej Chałapuk, is orthogonal to DDD. It is a very sound and solid concept to structure your system and gives room for domain modelling concepts like DDD.

I would not put too much thought into the explicit structure of this bounded context. Try to write a very broad acceptance test of a basic use case against the outer system boundary. Try to implement it with the fewest possible interactors while keeping a reasonable separation between the created components. Write Unit Tests if applicable.

I prefer this outside-in approach ("Growing Object Oriented Software, guided by Tests" is a good reference here), since it drives a domain model that is less gold plated and more fitting to the actual use cases.

Title: How to start using DDD in designing a "library" application

Body:
I want to design an online book reader. The first step is describing all the use cases which I have listed below:

I should be able to search a book by title.

I should be able to borrow a book.

I should be able to bookmark a borrowed book.

The system should allow one user per book at a time.

The system should allow to add a new book.

The system should allow to delete an existing book.

That said, I know now I need some Service Objects which would operate on Entities / Value Objects to get the thing done. I am deferring the database design / decision for now as its not considered a good practice. For the similar reasons Delivery mechanisms too is deferred.

After some reading I came to the conclusion that I would need the following:

Services (Algorithms without any states, depends on entities / values)

SearchBook (Takes a title and gives the result back)

BorrowService (Checks if a book can be borrowed)

Member service (Enroll/Unroll members in a library)

Entities (real world mutable objects with unique ID)

Library

Book (ISBN number as a UID)

User (Email as UID, it can be author or reader)

Associations

An author can have many books under his name, a user can only borrow one book at a time. A library can hold many books at a time, it can have many members too.

Notes

For simplicity there will be only single library / store.

No two users can read the same book at a time.

Questions

I am not able to find any value object till now or I am not able to recognize / find it?

I have followed Clean Architecture for some time and helped to build a toy project before. What is the difference between this and DDD?

Am I on the right track?


答:
It is entirely a choice of language design. It also depends on the underlying implementation of primitive types, and performance considerations due to that.

.NET has just one static Math.Sqrt method that acts on a double and returns a double. Anything else you pass to it must be cast or promoted to a double.

```<code>double sqrt2 = Math.Sqrt(2d);
</code>```

On the other hand, you have Rust which exposes these operations as functions on the types:

```<code>let sqrt2 = 2.0f32.sqrt();
let higher = 2.0f32.max(3.0f32);
</code>```

But Rust also has universal function call syntax (someone mentioned that earlier), so you can choose whatever you like.

```<code>let sqrt2 = f32::sqrt(2.0f32);
let higher = f32::max(2.0f32, 3.0f32);
</code>```

Title: Why is Math.Sqrt() a static function?

Body:
It is entirely a choice of language design. It also depends on the underlying implementation of primitive types, and performance considerations due to that.

.NET has just one static Math.Sqrt method that acts on a double and returns a double. Anything else you pass to it must be cast or promoted to a double.

double sqrt2 = Math.Sqrt(2d);

On the other hand, you have Rust which exposes these operations as functions on the types:

let sqrt2 = 2.0f32.sqrt();
let higher = 2.0f32.max(3.0f32);

But Rust also has universal function call syntax (someone mentioned that earlier), so you can choose whatever you like.

let sqrt2 = f32::sqrt(2.0f32);
let higher = f32::max(2.0f32, 3.0f32);


问:
Should the main method be separate in a separate class?
In Java main methods often do little more than parsing the command line arguments and initializing an object that then takes over, for example:

```<code>public class FooServer {
    // ...

    public static void main(String[] args) {
        // Process arguments ...
        FooServer server = new FooServer(...);
        // Initialize server ...
        server.start();
    }
}
</code>```

I have seen that some software extracts this main method into a separate "main" class (often ending in Launcher or Main):

```<code>public class FooServer {
    // ...
}

public class FooServerLauncher {
    public static void main(String[] args) {
            // Process arguments ...
            FooServer server = new FooServer(...);
            // Initialize server ...
            server.start();
        }
}
</code>```

The "main" class is closely coupled to the other class, so I suppose the "main" class is separate so that it doesn't pollute the interface of the other class.

I discussed the question with a co-worker and the person was of the opinion that contemporary object-oriented programmers chop up classes into too many small separate classes to pretend that everything is interchangeable while it's not. The person argued that this is a good example of the issue as the sole purpose of the main method is to start an object from the command line and thus is in fact part of its interface.

Are there other objective arguments for against separating the main method into its own class?

答:
In Java, almost everything is an object, so main() must has to be declared somewhere obviously.  Its concern is distinct from the rest of our class(which defines some data and behaviour that we are trying to encapsulate), which is getting the program ready to execute the whole thing.

In my own opinion main should not be pushed with the other data and behavior of a class.  The main method's concern is with running our program.  It will return to logic necessary that is declared inside of it's body.  With that being said I would go ahead and keep it away from any other class and/or logic in your program.


问:
Why is Python sorted() result like this?
I might be missing something obvious here, but why does Python 2.x sorted() function work like this?

```<code>In [95]: l = [1, '5', 4, 2, '3', 'b', 'c', '-a']
In [96]: sorted(l)
Out[96]: [1, 2, 4, '-a', '3', '5', 'b', 'c']
</code>```

Python 3 returns exception (TypeError: unorderable types: str() < int()), which I expect more than this result.

答:
It looks like the ASCII values of the characters are used to sort relative to the actual numbers.

After converting the characters to their decimal ASCII values, the sorted list looks something like this:

```<code>[1, 2, 4,  '-a', '3', '5', 'b', 'c']
[1, 2, 4, 45 97,  51,  53,  98,  99]
</code>```

Note that '-a' is sorted by the first character first, as is normal for an "alphabetical" ordering.

Body:
It looks like the ASCII values of the characters are used to sort relative to the actual numbers.

After converting the characters to their decimal ASCII values, the sorted list looks something like this:

[1, 2, 4,  '-a', '3', '5', 'b', 'c']
[1, 2, 4, 45 97,  51,  53,  98,  99]

Note that '-a' is sorted by the first character first, as is normal for an "alphabetical" ordering.


问:
What is a Service Locator?
I've heard the term pop all around. I've read various articles regarding the subject and heard two main definitions to the term "Service Location":

A glorified Registry - Bad practice, global variables, general evil.

A type of Dependency Injection Container - Can help with managing dependencies, making modular and extensible applications, generally helpful.

But I can't differentiate between the two. What does a Service Location really means? Can you give a simple example of a Service Locator? Is it good or evil?

答:
The two definitions that you gave are for different things.

The first one (A glorified Registry) is actually called the Service Locator. It means that there is some entity (called the Service Locator) that other classes depend on to retrieve their dependencies at runtime. Take a look at this article for an example and for a reason why it is considered an anti-pattern.

The second one (DI containers) is not necessarily considered a service locator. It depends on where you are using it. If you are using it inside your classes to obtain dependencies, then it is used as a service locator. On the other hand, if you use it only in the Composition Root, then it is not used as a service locator. And many people consider using DI containers in the Composition Root a very good way to do Dependency Injection.

Title: What is a Service Locator?


答:
The pattern you mentioned isn't necessarily the pattern used in all programs.  For example, if I want to make a program that reads messages, processes them, and sends output somewhere, I might have a main structure that's more like this:

```<code>public static void main(String[] args)
{
    Reader reader = new Reader(args[0]);
    Writer writer = new Writer(args[1]);
    Processor processor = new Processor(args[2]);
    reader.start();
    writer.start();
    processor.start();
    ...
}
</code>```

The gist here being that the thing that is launching parts of my application is not solely using one class, like in your examples.  Here I would likely put the main function into a MyProgramLauncher class, because it's not directly tied to any single class, and we could potentially be adding more classes in the future(initializing logging, database connection, graphics engine, etc)

main is also a logical place to check for all of the preconditions of running your program.  Eg. If you can't connect to your database, you might want to fail early and tell the user to check internet connection settings and try again.

If I have a main method like your FooServerLauncher, then I would put it in FooServer.  So long as there's one main method, and it references nothing other than FooServer, then it belongs in the FooServer file.  Alternatively, if you have multiple main files that utilize FooServer, then they need to be in their own Launcher style classes, so that the functionality of each 'executable' of your system remains separate.

Analyzing it with typical design metrics(when compared to having main in FooServer):

Readability - If anything is reduced, because the thing doing the execution and the thing being executed are separate.  And in a very literal sense you have to read two different files to understand what's going on.

Modularity - Increased, but I would say this is following the dogma of 'modularity' to a fault.

Maintainability - Is also reduced for similar reasons to readability.  While maintaining FooServer you likely need to alter FooServerLauncher.  I would argue it's much less likely to alter FooServer and forget to update main as needed if they're in the same file.  Having the separate files introduces 'out of sight, out of mind'.

Coupling - High, because it's 100% dependent on the implementation of FooServer.  In your example, main has initialization steps and starts FooServer, which depending on your preferences may be too much coupling.

Cohesion - I would say low, for the same reason we have high coupling.  If everything in main exists to do something tied to FooServer, then the logical place to put main is in FooServer.

For a couple of these I think you could argue they stay the same, but I'm not quickly coming up with ways in which they're improved.  So, all things considered, having main in a separate file seems to be equal-to or less-than having it in the same file.

Title: Should the main method be separate in a separate class?

Body:
In Java main methods often do little more than parsing the command line arguments and initializing an object that then takes over, for example:

```<code>public class FooServer {
    // ...

    public static void main(String[] args) {
        // Process arguments ...
        FooServer server = new FooServer(...);
        // Initialize server ...
        server.start();
    }
}
</code>```

I have seen that some software extracts this main method into a separate "main" class (often ending in Launcher or Main):

```<code>public class FooServer {
    // ...
}

public class FooServerLauncher {
    public static void main(String[] args) {
            // Process arguments ...
            FooServer server = new FooServer(...);
            // Initialize server ...
            server.start();
        }
}
</code>```

The "main" class is closely coupled to the other class, so I suppose the "main" class is separate so that it doesn't pollute the interface of the other class.

I discussed the question with a co-worker and the person was of the opinion that contemporary object-oriented programmers chop up classes into too many small separate classes to pretend that everything is interchangeable while it's not. The person argued that this is a good example of the issue as the sole purpose of the main method is to start an object from the command line and thus is in fact part of its interface.

Are there other objective arguments for against separating the main method into its own class?

Body:
The pattern you mentioned isn't necessarily the pattern used in all programs.  For example, if I want to make a program that reads messages, processes them, and sends output somewhere, I might have a main structure that's more like this:

public static void main(String[] args)
{
    Reader reader = new Reader(args[0]);
    Writer writer = new Writer(args[1]);
    Processor processor = new Processor(args[2]);
    reader.start();
    writer.start();
    processor.start();
    ...
}

The gist here being that the thing that is launching parts of my application is not solely using one class, like in your examples.  Here I would likely put the main function into a MyProgramLauncher class, because it's not directly tied to any single class, and we could potentially be adding more classes in the future(initializing logging, database connection, graphics engine, etc)

main is also a logical place to check for all of the preconditions of running your program.  Eg. If you can't connect to your database, you might want to fail early and tell the user to check internet connection settings and try again.

If I have a main method like your FooServerLauncher, then I would put it in FooServer.  So long as there's one main method, and it references nothing other than FooServer, then it belongs in the FooServer file.  Alternatively, if you have multiple main files that utilize FooServer, then they need to be in their own Launcher style classes, so that the functionality of each 'executable' of your system remains separate.

Analyzing it with typical design metrics(when compared to having main in FooServer):

Readability - If anything is reduced, because the thing doing the execution and the thing being executed are separate.  And in a very literal sense you have to read two different files to understand what's going on.

Modularity - Increased, but I would say this is following the dogma of 'modularity' to a fault.

Maintainability - Is also reduced for similar reasons to readability.  While maintaining FooServer you likely need to alter FooServerLauncher.  I would argue it's much less likely to alter FooServer and forget to update main as needed if they're in the same file.  Having the separate files introduces 'out of sight, out of mind'.

Coupling - High, because it's 100% dependent on the implementation of FooServer.  In your example, main has initialization steps and starts FooServer, which depending on your preferences may be too much coupling.

Cohesion - I would say low, for the same reason we have high coupling.  If everything in main exists to do something tied to FooServer, then the logical place to put main is in FooServer.

For a couple of these I think you could argue they stay the same, but I'm not quickly coming up with ways in which they're improved.  So, all things considered, having main in a separate file seems to be equal-to or less-than having it in the same file.


问:
Code quality : what's the worth of the looking at the ifs?
We've all seen discussions on the ideal length of a method. My favourite litmus test for code quality is to look at the "if" statements, to see whether the values being tested belong to the current class. The further removed the tested value from the context of the test, the stronger the smell of a modelling problem.

So my question is... can anyone fill me in on the origin and the worth of this measure. Is this a recognised metric? Is it possible/desireable to model objects such that all conditional logic tests only class members? What importance would you give to this measure?

答:
The use of an if statement is what I call a "bifurcation."  It splits the code into two different execution paths, increasing its cyclomatic complexity.  That's why examining the if statements is a useful exercise for code analysis.

You can touch other classes without involving if statements, so I'm not sure that the specific combination of if conditions and touching other classes is especially meaningful, other than to identify a specific brand of hell.


问:
Python -- Class and Object
I got a question that quite disturbs me a lot and I think it might help a lot if I had an answer to it. So I got this:

```<code>class Klasse1:
    variable1 = "haha"
class Klasse2:
    variable2 = "hoho"

print Klasse1.variable1
print Klasse2.variable2
</code>```

and this:

```<code>class Klasse1:
    variable1 = "haha"
class Klasse2:
    variable2 = "hoho"

Object1 = Klasse1()
Object2 = Klasse2()
print Object1.variable1
print Object2.variable2
</code>```

Now the question is: Why would I use the second(too much code) instead of the first(obviously easier.) In many sites and tutorials I've seen people create objects for something they could easily get without creating them. So I'm probably missing something and I would like to know.

P.S. Same case with Java

答:
Think of classes as cookie cutters and objects as cookies.

Each cookie has the same shape; that of the cookie cutter.  But each cookie might have a different color: color = "green"

You would do it the second way because you would never imagine baking a single cookie during your entire lifetime, nor would every cookie you bake be green.

Title: Python -- Class and Object


答:
As an end user, I couldn't care less about an assertion. It's meant to protect 'your implementation'. Hence I would like the message to tell me what I did wrong and/or what should I do to fix it.

There is absolutely nothing wrong in leaving the message out if the "auto generated assertion message" satisfies my requirement above, e.g. the two assertions you provided in the question.

But I wouldn't be happy if the assertion is something like _n > (0.75 * _m) && _free_nodes < (0.3 * _max_size). In this case I would appreciate a message saying:

Please check the capacity limits set on this graph at the time of creation. Either increase the max capacity or respect it.

P.S. Don't try to decipher the assertion condition. I just wanted to write something an end user won't understand.

Title: Purpose of assertion messages