问:
Better way of manipulating large objects
I am doing a lot of work with SOAP Api in PHP and the objects that are returned are quite big. I am then updating the objects from local db changes and pushing them back.

So more often than not I have a large object returned from a db query and a large object retrieved from a SOAP call and I have to update the one from the other.

So I end up with a lot of this:

```<code>$api_object->Organisation->Location[0]->AddressLine1 = $db_object->MainAddress->address_line_1;
$api_object->Organisation->Location[0]->AddressLine2 = $db_object->MainAddress->address_line_2;

$api_object->Organisation->Location[1]->AddressLine1 = $db_object->SecondaryAddress->address_line_1;
$api_object->Organisation->Location[1]->AddressLine2 = $db_object->SecondaryAddress->address_line_2;
</code>```

And so on, and so on with many more elements! And as you can see the names of the fields don't often match in naming or depth.

I just wondered if anyone had any suggestions how to do it better.

答:
Along with Robert Harvey's advice, rather than 'setting' an existing API object's properties from an instance of a DB Object directly where you need it to happen, why not just 'create' a brand new API object using a factory that uses your DB object as a template?

```<code>class ApiObjectFactory
{
    public static function createFromDbObject($dbObject, ApiFactoryInterface $factory)
    {
        return $factory->createFromObject($dbObject);
    }
}
</code>```

The secondary factory you pass in to this one will be the one responsible for creating individual items.  The purpose of this outer factory is to encapsulate all of these secondary factories to a single spot (so anywhere else that needs to create an API Object from a DB Object will call here).

```<code>interface ApiFactoryInterface
{
    public function createFromObject($dbObject);
}
</code>```

This interface is just setting up the contract that your other type factories will adhere to.  This is not strictly necessary, but is good for future proofing and setting up the expectations on exactly what these objects will be doing.

```<code>class  OrganizationApiFactory implements ApiFactoryInterface
{
    public function createFromObject($dbObject)
    {
        $organization = new StdClass;
        $organization->Location = [];
        $organization->Location[0] = $this->createAddress($dbObject->MainAddress);
        $organization->Location[1] = $this->createAddress($dbObject->SecondaryAddress);

        return $organization;
    }

    protected function createAddress(StdClass $address)
    {
        $returnAddress = new StdClass;
        $returnAddress->AddressLine1 = $address->address_line_1;
        $returnAddress->AddressLine2 = $address->address_line_2;

        return $returnAddress;
    }
}
</code>```

If you are able to take advantage of dependency injection, you could offload the filling of the organization's addresses to an AddressApiFactory and be able to completely decouple this process by injecting related factories into the organization factory.

```<code>class  OrganizationApiFactory implements ApiFactoryInterface
{
    public function __construct(AddressApiFactory $addressFactory)
    {
        $this->addressFactory = $addressFactory;
    }

    public function createFromObject($dbObject)
    {
        $organization = new StdClass;
        $organization->Location = [];
        $organization->Location[0] = $this->addressFactory->createFromObject($dbObject->MainAddress);
        $organization->Location[1] = $this->addressFactory->createFromObject($dbObject->SecondaryAddress);

        return $organization;
    }
}

class AddressApiFactory implements ApiFactoryInterface
{
    public function createFromObject($dbObject)
    {
        $returnAddress = new StdClass;
        $returnAddress->AddressLine1 = $address->address_line_1;
        $returnAddress->AddressLine2 = $address->address_line_2;

        return $returnAddress;
    }
}
</code>```

This approach does a couple things for you:

It separates the concerns out for all of your different API model 'types'.  If you are typing the same things over and over again, that is a code smell.  You should endeavor to create small, functional units that do a single thing and a single thing well.  An organization factory in this context knows precisely how to take your database object and convert it into whatever format you need to send it over to your API.  It has absolutely zero knowledge of anything else.

If done correctly, it can greatly increase the readbility and maintainability of your code.  When complete, you should be able to save any object to your API given an existing object from your database with just a handful lines of code. Less code to debug = faster debugging.  Less code to debug = less debugging, since less code has a tendency to break less often.

An example of how you could update an API Object using this approach:

```<code>// Simulating fetching an object from the api and loading your corresponding
// object from the database
$myApiObject = getObjectFromApi();
$myDbObject = getObjectFromDb($myApiObject);

// Simulate updating your object locally
$myDbObject->address_line_1 = '111 Testing Dr';

// Now you need an API Object to save...
$factory = new ApiObjectFactory;
$apiObjectToSave = $factory->createFromDbObject($myDbObject, new OrganizationApiFactory);

// Save your updated data to your API
sendApiSaveRequest($apiObjectToSave);

// ... or even better ...
$apiObjectToSave->save();
</code>```

Body:
Along with Robert Harvey's advice, rather than 'setting' an existing API object's properties from an instance of a DB Object directly where you need it to happen, why not just 'create' a brand new API object using a factory that uses your DB object as a template?

class ApiObjectFactory
{
    public static function createFromDbObject($dbObject, ApiFactoryInterface $factory)
    {
        return $factory->createFromObject($dbObject);
    }
}

The secondary factory you pass in to this one will be the one responsible for creating individual items.  The purpose of this outer factory is to encapsulate all of these secondary factories to a single spot (so anywhere else that needs to create an API Object from a DB Object will call here).

interface ApiFactoryInterface
{
    public function createFromObject($dbObject);
}

This interface is just setting up the contract that your other type factories will adhere to.  This is not strictly necessary, but is good for future proofing and setting up the expectations on exactly what these objects will be doing.

class  OrganizationApiFactory implements ApiFactoryInterface
{
    public function createFromObject($dbObject)
    {
        $organization = new StdClass;
        $organization->Location = [];
        $organization->Location[0] = $this->createAddress($dbObject->MainAddress);
        $organization->Location[1] = $this->createAddress($dbObject->SecondaryAddress);

        return $organization;
    }

    protected function createAddress(StdClass $address)
    {
        $returnAddress = new StdClass;
        $returnAddress->AddressLine1 = $address->address_line_1;
        $returnAddress->AddressLine2 = $address->address_line_2;

        return $returnAddress;
    }
}

If you are able to take advantage of dependency injection, you could offload the filling of the organization's addresses to an AddressApiFactory and be able to completely decouple this process by injecting related factories into the organization factory.

class  OrganizationApiFactory implements ApiFactoryInterface
{
    public function __construct(AddressApiFactory $addressFactory)
    {
        $this->addressFactory = $addressFactory;
    }

    public function createFromObject($dbObject)
    {
        $organization = new StdClass;
        $organization->Location = [];
        $organization->Location[0] = $this->addressFactory->createFromObject($dbObject->MainAddress);
        $organization->Location[1] = $this->addressFactory->createFromObject($dbObject->SecondaryAddress);

        return $organization;
    }
}

class AddressApiFactory implements ApiFactoryInterface
{
    public function createFromObject($dbObject)
    {
        $returnAddress = new StdClass;
        $returnAddress->AddressLine1 = $address->address_line_1;
        $returnAddress->AddressLine2 = $address->address_line_2;

        return $returnAddress;
    }
}

This approach does a couple things for you:

It separates the concerns out for all of your different API model 'types'.  If you are typing the same things over and over again, that is a code smell.  You should endeavor to create small, functional units that do a single thing and a single thing well.  An organization factory in this context knows precisely how to take your database object and convert it into whatever format you need to send it over to your API.  It has absolutely zero knowledge of anything else.

If done correctly, it can greatly increase the readbility and maintainability of your code.  When complete, you should be able to save any object to your API given an existing object from your database with just a handful lines of code. Less code to debug = faster debugging.  Less code to debug = less debugging, since less code has a tendency to break less often.

An example of how you could update an API Object using this approach:

// Simulating fetching an object from the api and loading your corresponding
// object from the database
$myApiObject = getObjectFromApi();
$myDbObject = getObjectFromDb($myApiObject);

// Simulate updating your object locally
$myDbObject->address_line_1 = '111 Testing Dr';

// Now you need an API Object to save...
$factory = new ApiObjectFactory;
$apiObjectToSave = $factory->createFromDbObject($myDbObject, new OrganizationApiFactory);

// Save your updated data to your API
sendApiSaveRequest($apiObjectToSave);

// ... or even better ...
$apiObjectToSave->save();


问:
Can someone please explain reverse look up tables?
Im finding it difficult to understand reverse look up tables and how it works, and the concept of hash chains. This is apart of a computer security model i am taking.
So i understand that brute force, dictionary attack and look up table take up a lot of time, and store all options and then search through all the database. however reverse look up tables addresses this problem, and sacrifices time for storage. But how this happens i am getting confused.
Many thanks</p>

答:
Let's say you want to crack passwords which are stored as MD5 Hashes (This is very old technology). Since brute force takes a real long time, and this function is "non-reversible", then the attack is the Reverse Lookup table.

The idea is that you create a table storing what you enter as input and the hash it generates. After you run your routine with as many inputs you think are valid, you can then attack the password file with a reverse lookup table:  you browse your database browsing not by the password but for what Hash matches.

Reverse lookup then, is simply not looking by the same input, but for inputs which generate the same output. For example:

```<code>input | Hash generated

admin |  21232f297a57a5a743894a0e4a801fc3
</code>```

Instead of looking for the admin string, in your table you would be looking by the string which matches the hash 21232f297a57a5a743894a0e4a801fc3.

For more details, look for Raibow tables in the wikipedia, I think you will note that they are not exactly the same, but in the article you can find the difference between both.

How it sacrifices time for storage?
The idea is that you would need a full database with the data as similar to the one above, and this is storage. The time per query, is only a B-tree lookup (O(log n)) on the database, since the key could be the hash. This does not mean that to generate the table you don't spend time. It just means that once you have the database, you can query it in a very small time.

ContentLicense: CC BY-SA 3.0

Body:
Let's say you want to crack passwords which are stored as MD5 Hashes (This is very old technology). Since brute force takes a real long time, and this function is "non-reversible", then the attack is the Reverse Lookup table.

The idea is that you create a table storing what you enter as input and the hash it generates. After you run your routine with as many inputs you think are valid, you can then attack the password file with a reverse lookup table:  you browse your database browsing not by the password but for what Hash matches.

Reverse lookup then, is simply not looking by the same input, but for inputs which generate the same output. For example:

input | Hash generated

admin |  21232f297a57a5a743894a0e4a801fc3

Instead of looking for the admin string, in your table you would be looking by the string which matches the hash 21232f297a57a5a743894a0e4a801fc3.

For more details, look for Raibow tables in the wikipedia, I think you will note that they are not exactly the same, but in the article you can find the difference between both.

How it sacrifices time for storage?
The idea is that you would need a full database with the data as similar to the one above, and this is storage. The time per query, is only a B-tree lookup (O(log n)) on the database, since the key could be the hash. This does not mean that to generate the table you don't spend time. It just means that once you have the database, you can query it in a very small time.


答:
This feels like a "service" class or an implementation of the "unit of work" pattern would be beneficial. I'm leaning towards Unit of Work here.

You can define multiple "unit of work" classes in a hierarchy to break up the updates. Plus you can define additional classes for updating the $db_object with values from the $api_object. While this adds complexity, it does decouple the two layers giving you explicit integration points, and it reflects the transactional nature of what you are trying to accomplish. It gives you a tree structure of objects that do the work for you in an organized and isolated fashion.

```<code>class UpdateApiUnitOfWork {
    private $update_organization;

    public function UpdateApiUnitOfWork() {
        $this->update_organization = new UpdateApiOrganizationUnitOfWork();
    }

    public function execute($api_object, $db_object) {
        $this->update_organization->execute($api_object->Organization, $db_object);
    }
}

class UpdateApiOrganizationUnitOfWork {
    private $update_location;

    public function UpdateApiOrganizationUnitOfWork() {
        $this->update_location = new UpdateApiLocationUnitOfWork();
    }

    public function execute($organization, $db_object) {
        $this->update_location->execute($organization->Location[0], $db_object->MainAddress);

        if (isset($organization->Location[1]))
            $this->update_location->execute($organization->Location[1], $db_object->SecondaryAddress);

        // ...
    }
}

class UpdateApiLocationUnitOfWork {
    public function execute($location, $address) {
        $location->AddressLine1 = $address->address_line_1;
        $location->AddressLine2 = $address->address_line_2;
        // ...
    }
}
</code>```

Using this "unit of work" pattern becomes very easy:

```<code>$api_object = // Get from the Web API
$db_object = // Get from the database

$updater = new UpdateApiUnitOfWork();
$updater->execute($api_object, $db_object);
</code>```

If you don't need to update the whole chain of objects, you can pick and choose which unit of work you want to apply:

```<code>$updater = new UpdateApiOrganizationUnitOfWork();
$updater->execute($api->Organzation, $db_object);
</code>```

After that, you just need to call the Web API to update the information, or call into your data access layer to persist those changes to the database.

Title: Better way of manipulating large objects

Body:
I am doing a lot of work with SOAP Api in PHP and the objects that are returned are quite big. I am then updating the objects from local db changes and pushing them back.

So more often than not I have a large object returned from a db query and a large object retrieved from a SOAP call and I have to update the one from the other.

So I end up with a lot of this:

```<code>$api_object->Organisation->Location[0]->AddressLine1 = $db_object->MainAddress->address_line_1;
$api_object->Organisation->Location[0]->AddressLine2 = $db_object->MainAddress->address_line_2;

$api_object->Organisation->Location[1]->AddressLine1 = $db_object->SecondaryAddress->address_line_1;
$api_object->Organisation->Location[1]->AddressLine2 = $db_object->SecondaryAddress->address_line_2;
</code>```

And so on, and so on with many more elements! And as you can see the names of the fields don't often match in naming or depth.

I just wondered if anyone had any suggestions how to do it better.

Body:
This feels like a "service" class or an implementation of the "unit of work" pattern would be beneficial. I'm leaning towards Unit of Work here.

You can define multiple "unit of work" classes in a hierarchy to break up the updates. Plus you can define additional classes for updating the $db_object with values from the $api_object. While this adds complexity, it does decouple the two layers giving you explicit integration points, and it reflects the transactional nature of what you are trying to accomplish. It gives you a tree structure of objects that do the work for you in an organized and isolated fashion.

class UpdateApiUnitOfWork {
    private $update_organization;

    public function UpdateApiUnitOfWork() {
        $this->update_organization = new UpdateApiOrganizationUnitOfWork();
    }

    public function execute($api_object, $db_object) {
        $this->update_organization->execute($api_object->Organization, $db_object);
    }
}

class UpdateApiOrganizationUnitOfWork {
    private $update_location;

    public function UpdateApiOrganizationUnitOfWork() {
        $this->update_location = new UpdateApiLocationUnitOfWork();
    }

    public function execute($organization, $db_object) {
        $this->update_location->execute($organization->Location[0], $db_object->MainAddress);

        if (isset($organization->Location[1]))
            $this->update_location->execute($organization->Location[1], $db_object->SecondaryAddress);

        // ...
    }
}

class UpdateApiLocationUnitOfWork {
    public function execute($location, $address) {
        $location->AddressLine1 = $address->address_line_1;
        $location->AddressLine2 = $address->address_line_2;
        // ...
    }
}

Using this "unit of work" pattern becomes very easy:

$api_object = // Get from the Web API
$db_object = // Get from the database

$updater = new UpdateApiUnitOfWork();
$updater->execute($api_object, $db_object);

If you don't need to update the whole chain of objects, you can pick and choose which unit of work you want to apply:

$updater = new UpdateApiOrganizationUnitOfWork();
$updater->execute($api->Organzation, $db_object);

After that, you just need to call the Web API to update the information, or call into your data access layer to persist those changes to the database.


问:
What to call an HTTP API that is not RESTful?
What would you call an API that is HTTP-based, uses URI to name resources and HTTP verbs (PUT, POST, DELETE, GET...) to manipulate those resources?

According to Roy Fielding's complaints it is not REST, because there is no hypermedia.

Internally, in my team, everyone calls it "REST API". I call it "REST-like" but it is not descriptive and its meaning is fuzzy. I'm quite confused about it, since there is huge disagreement about REST. I don't want take part in flame wars, but just use correct terms.

答:
Call it an HTTP API.

It conforms to HTTP standards, and doesn't have anything else layered on top (e.g. SOAP).

The HTTP standards define resources, verbs, headers, content negotiation, etc.

REST (REpresentational State Transfer) is an architecture with requirements that happen to be amenable to existing HTTP standards, but HTTP works all on its own.

In my experience, 90% of "REST HTTP APIs" should call themselves "just" an HTTP API.

Don't be ashamed to leave off the REST label. As with microservices and non-relational databases, you don't have to have a RESTful API to be cool. Roy set out to create the longest-lived, most backwards compatible, networked application architecture that he could. He did a good job. But not everything needs 40+ years of compatibility.


问:
Null object pattern or nullable
What's better for implementing null object pattern:

1) provide special state for instance

or

2) use everywhere ? (Nullable) operator?

And I'm thinking about structs only.

答:
In general, you should avoid null where possible.

If you really have an optional parameter/field, then it is ideomatic to make the instance nullable.

If you have a struct where null means something special - something that is not "this instance does not exist" then it depends. If other parts of your code/api use null to mean this special thing, then just use null. If not, then it may be better to make a specific instance of the struct mean that other value, or create your own Maybe Type.

As always, there's no single "better" for all situations. Program design is a matter of trade offs.

Title: Null object pattern or nullable


问:
Getting to know my way around a database with hundreds of tables
I'm new to a small company that's pretty much run by one guy. He knows all the ins and outs of the system which is quite large. We have a database with about 300 different tables. I'm struggling to keep track of where everything in the database is and what relates to what. What methods can be used to manage large databases, or does it mostly come down to going through other examples in the code base to find what you need?</p>

答:
What have worked for me is:

Plot a giant physical model of the database.

You must use a tool like Sybase Power Designer and reverse-engineer the model. There are also free tools that could be used. Once there you must find a plot service and have it plotted in big format. Then put it on the wall.

It helps if you first re-format the model for better readability of relatioships. What I do is:

Use non-diagonal lines

Have the join printed with every relationship

Prevent overlapping lines.

Minimize crossing lines

Group tables in clusters


答: Use null. It doesn't clutter your stuff up with a null instance, it doesn't fool people who think they have an instance into realizing they don't have an instance well after the bug occurred, and it's simply much easier codewise to be able to use the same rules for all nullable things.

Title: Null object pattern or nullable

Body:
What's better for implementing null object pattern:

1) provide special state for instance

or

2) use everywhere ? (Nullable) operator?

And I'm thinking about structs only.


答:
You can call it whatever you like, people tend to (almost religiously) latch onto any part of the REST 'spec' that you're not following and use that as a point of protest which is highly detrimental to the development. But that said, the simple fact is that there are (nearly) zero services exist that implement true REST for their API serves.

In our team we named ours the Stateless API while it was in development because we had a legacy Stateful and Functional SOAP API that we were replacing (the legacy API itself never had an agreed and meaningful name either so we didn't get too caught up in names).

Now this project only has one API it's simply called the <project> API. When we eventually replace it, the new API will simply be known as the new <project> API.

Giving it any fancy and descriptive internal name is almost meaningless unless you have so many APIs that you need to differentiate this one from the rest (in which case you probably should rename all the others as well).

Title: What to call an HTTP API that is not RESTful?

Body:
What would you call an API that is HTTP-based, uses URI to name resources and HTTP verbs (PUT, POST, DELETE, GET...) to manipulate those resources?

According to Roy Fielding's complaints it is not REST, because there is no hypermedia.

Internally, in my team, everyone calls it "REST API". I call it "REST-like" but it is not descriptive and its meaning is fuzzy. I'm quite confused about it, since there is huge disagreement about REST. I don't want take part in flame wars, but just use correct terms.


答:
You can call it a Web API. It's a very broad term but it can avoid nitpicking about meaning of other API type definitions. The term is less technical and precise compared to alternatives like HTTP API, but that might be an advantage when talking to non-technical people.

This term is also used by Leonard Richardson (who defined the Richardson Maturity Model that is already mentioned another answer - a well accepted measurement for how close an API is to a REST architecture). It is what you get if you drop the "RESTful" part of a "RESTful Web API".


问:
Why should we expect user-space coroutines to be lighter than OS threads?
I have heard it said that managing concurrent TCP connections using user-space coroutines uses less resources per open connection than using an OS thread per connection.

Actually, OS threads and coroutines are essentially different ways of representing the same thing: a combination of control and state.

An OS thread stores:

A pc counter (representing control)

A stack pointer + other registers (representing state)

A coroutine requires:

A function pointer (representing control)

An environment pointer (representing state)

Why should we believe user-space coroutines to be a more resource-efficient approach?

答: All thing being equal, user space will have fewer layer of abstraction to work through.  OS thread will require relatively slow calls through the kernel.  User space, done correctly will avoid these abstractions.  This results in the opportunity for higher performance.</p>


问:
Merge directed acyclic graphs minimizing number of nodes
I have some DAGs (directed acylic graphs) and I want to merge them in order to minimize the number of nodes (we could say that every node has a cost, while edges are free).

These four different DAGs (directed from left to right)...

```<code>a-b-c
a-d-c
a-c
c-a
</code>```

...should become:

```<code> /---\
a--b--c-a
 \-d-/
</code>```

This is not a real DAWG (directed acyclic word graph): I don't want to store information like "is 'adc' included?". My structure could only answer to this question: "it would be possible that 'adc' was one of the words?".

Is there an algorithm for this purpose?

Update (12/15/14) - Levenshtein distance

I tried something different: I used Levenshtein distance to find the minimum number of edits required in order to transform a string into another (node=character and chain=sequence of nodes/characters=word). My algorithm ignores deletion, and insert characters instead of replacing them. Here's the interesting part (Python code):

```<code>current = words[0]
for word in words[1:]:
    edit = editops(current, word)
    customEdit = [('insert', s, d) for op, s, d in edit if op != 'delete']
    current = apply_edit(customEdit, current, word)
</code>```

Sometimes there are unneeded characters, so I remove them at the end of the process.
If I change the words order I get different results, so I run my code many times shuffling words in order to find a shorter string (shuffling seems to provide better result with fewer iterations than permutations, even if words are sorted by length).

If every character is a node, and every word is a DAG, I can easily get a good approximation of the DAG I'm looking for.

The main problem with this approach is that I don't know how the best result will look like so I don't know when to stop (I can't check every result of my permutation: it will take too much time!).

Here's my code (tested with Python 2; python-Levenshtein is needed). The output looks like this:

```ldoarmilpesouimtr (17)
iapmdsoeluiortem (16)
diolposarmieutm (15)
^C
Original size: 22
Compressed: 15

dio<strong>l</strong>p<strong>o</strong>sa<strong>r</strong>mi<strong>e</strong>ut<strong>m</strong> (lorem)
d<strong>i</strong>ol<strong>p</strong>o<strong>s</strong>armie<strong>u</strong>t<strong>m</strong> (ipsum)
<strong>d</strong>i<strong>ol</strong>p<strong>o</strong>sa<strong>r</strong>mieutm (dolor)
diolpo<strong>s</strong>arm<strong>i</strong>eu<strong>t</strong>m (sit)
diolpos<strong>a</strong>r<strong>m</strong>i<strong>e</strong>u<strong>t</strong>m (amet)
```

Is it a good way to solve this problem? What it could be improved? Do you know if it's possible to know the minimum number of nodes/characters needed in order to stop the algorithm when I get the optimum?

答:
I think your structure is the line graph of the minimal DAWG. I have generated these before, three years ago, by building the minimal DAWG, from that its line graph, then minimising the line graph. I searched the literature and Google extensively and never found this last step. I concluded that the DAWG was more useful, generally, but the line DAWG was better for display to those unaccustomed to DAWGs. There is another name for a DAWG used in natural language processing, a Word Something, the something elludes me right now.

Your adc example suggests a DAWG where everyone node has a # edge to the sink.


问:
Checking for valid state inside function or outside
This is a common occurrence in programming and is language agnostic, you have a function that needs to do something but in only in some cases. Maybe it's a feature-toggle, maybe it's a function that needs some data to be passed in to it.

You're left with two choices:

Do you check for that state inside the function, or do you check for that state before you call the function?

Here is an example in JavaScript to illustrate what I mean:

```<code>// method 1 if statement inside function
var getReviews = function() {
    if (enabled !== true) { return []; }

    return doWork();
}

var reviews = getReviews();

// method2 if statement outside function
var getReviews = function() {
    return doWork();
}

var reviews = enabled === true ? getReviews() : [];
</code>```

Pros of check inside:

Easy to call, the caller of the function doesn't have to be aware of certain required states, they can simply call, and will get back empty data.

Pros of check outside:

If a function is being called when the state is not proper it can raise an exception alerting devs to a possibly bad state, this isn't possible if we silently exit as we do with the check-inside.

The function itself is idempotent because it relies on state outside itself. This generally helps with maintainability of functions.

答:
This question mainly stems from worrying about maintenance so I will make an assumption that you are going to have many of these state-dependent functions.

I would recommend having a layer in between your client and the function that it is calling which is state dependent. Then let this layer handle the state management. This will do two things for you:

1) Offload the logic from your client and from your function.

2) Centralize all of your state management in one place instead of having it all over the place outside of functions or inside of each individual function.

If you are checking states inside of your functions you are adding more responsibility to what they already are doing and therefore violating the single responsibility principle.

Additionally, you are scattering your state logic all over the place (whether you check inside or outside) instead of having it in one centralized place - As you have mentioned yourself, this is a maintenance nightmare as your functions start to add up and you decide to make a change.


答:
Hypermedia never really got popular with REST-like APIs - to the point that when an API actually implements hypermedia navigation, the term RESTful simply isn't enough to distinguish it from any other "RESTful" web APIs. REST has become an catch-all term or any resource-based web APIs and new names like Hypermedia API have been coined to focus on the hypermedia concept.

I don't really want to advocate the usage of incorrect terms, but I think that the general modern interpretation of REST simply means using uniform URLs and HTTP verbs for most people. It's not correct, but anyone who knows Fieldings definition, should also know that many others don't. On the other hand, anyone who knows REST only by observing how existing "RESTful" APIs are implemented, won't know what you are talking about when you mention lesser known REST constraints like HATEOAS or on-demand code. Fielding may not like it, but I think it is to late to get back to the original definition*. And let's be honest: If you hear someone talk about his REST API for the first time, you instantly assume it does not include hypermedia, don't you?

Insisting on the correct definition of RESTful usually only creates additional confusion. As with many terms that have changed their meaning over time or that the masses simply adopted wrong, I appreciate if someone knows the original definition but I wouldn't correct anyone who is using the broader modern interpretation of REST.

* and also to late to establish new terms for REST-like non-hypermedia APIs, for that matter. How should we call them anyway? ... RESTish ?


问:
When would someone use MongoDB (or similar) over a Relational DBMS?
I'm a bit confused about the whole NoSQL thing and such.
When would you choose to use something like MongoDB over something like Oracle or MySQL?
I don't really understand the "difference" as far as usage goes between them.

From my understanding NoSQL type databases aren't meant to replace RDBMSes, but what exactly are they meant to do?

答:
Databases like MongoDB are great when you usually know where your data is(as opposed to needing to write several complicated queries).  With Mongo, "related" data is either nested in the parent data or it has primary/foreign keys.  This is great if, for example, you have Posts and Comments; generally, you aren't going to be displaying comments outside the context of a post, so it makes sense that comments be contained within a post(that way you get all the comments for the post without needing to query a separate table).

MongoDB is schemaless.  This means that it will take whatever structure of data you throw at it, for the most part.

On the other hand, if you are need to use aggregate functions and feel the need to query data in complex ways that cannot be achieved through embeds or simple relations in Mongo, that's when you know it's time to use a RDBMS like MySQL or PostgreSQL.

MongoDB isn't meant to replace SQL.  It simply fulfills different needs, and MongoDB and an RDBMS can be used in conjunction.  In my opinion, MongoDB isn't all that necessary if you don't need your data to be flexible or embedded in a parent document.  Development with MongoDB is very fun because there are far fewer steps involved in getting a project(say in Rails) up and running.  Need to make a change?  No problem.  Just add an attribute to your model.  Done.

I can't speak for many other NoSQL databases, though I know that they are usually similarly designed to fulfill a specific need that cannot be met by an RDBMS.  Some reside entirely in memory or are able to be sharded or scaled very easily.  I'm pretty sure that Cassandra is designed to continue operating without data loss if a node goes down.  Redis is basically a key value store that resides in memory(with periodic disk writes for persistence), but also has the ability to store data types like sets and sort them.


问:
Inheritance vs Class Diagram
What is the difference between an inheritance diagram and a class diagram in UML? For the Computer Science A Level (a British test administrated by Cambridge University, so it's possible that this terminology is Britain-specific), they require knowledge of how to make both separately.

I guessed that the inheritance diagram only has class names in boxes with arrows and the class diagram includes members, but I wanted to make sure.

答:
According to Wikipedia and also according to the UML reference , UML does not contain a diagram type called "inheritance diagram". That does not mean some tool vendors invented their own definition of what an inheritance diagram should be (like this one). When using UML means, to display just an inheritance tree, IMHO the most obvious solution would be to use a class diagram with only class names and inheritance relationships, as you wrote above. So call this an inheritance diagram, if you like, but be aware that there is no standard saying that this is the "correct" definition.

In fact, when you are asked for this term as part of a "Computer Science A Level" test, you should check the material from the university what they call an inheritance diagram.

Title: Inheritance vs Class Diagram


答:
It's about scheduling overhead, and about how some solutions fit specific problems better than others.

Scheduling is the activity of deciding who is executing right now, and switching between processes/threads. Cooperative scheduling is simple to implement, and requires that each participating thread must yield to the scheduler when a sensible pause state is reached. Imagine a few threads in a discussion:

A: So, how was your day? YIELD

  B: Today I visited a zoo. YIELD

  A: YIELD

  B: There were kangaroos and llamas. YIELD

  A: Can you pass me the butter? YIELD

  B: Here you are :) YIELD

Of course, there's now a problem when process B never yields:

A: So, how was your day? YIELD

  B: Today I visited a zoo and there were like kangaroos and llamas and all kinds of animals and stuff and…

  (A tries to make themselves noticed and raises a hand, but B never stops)

  B: … their fluffy fur and I took tons of pictures and do you want to see them here they are this is me next to a …

  (A would really like that butter, but B still won't stop)

  B: … and here I made a selfie with an orang-utan and look how it …

  (at this point, A starts plotting to kill B)

Cooperative scheduling only works when we can rely on everyone to yield regularly to give others a chance to execute as well. That works well for a single program that was designed by a single organization which has control over all parts and is aware of what specific soft real-time requirements have to be met. But for most operating systems, programs can be written by third parties, and these might forget to yield regularly. Therefore, we build a preemptive scheduler that yields for them. Ideally, the conversation works like this:

A: So, how was your day? dum dee dum

  Scheduler: NEXT

  B: Today I visited a zoo. There were

  Scheduler: NEXT

  A: dum dee dum twiddly thumb

  Scheduler: NEXT

  B: kangaroos and llamas. dum dee dum

  Scheduler: NEXT

  A: Can you pass me the butter? dum dee dum

  Scheduler: NEXT

  B: Here you are :) dum dee dum

However, the scheduler might interrupt all processes when they are in the middle of a thought. Afterwards they have to remember where they left off.

A: So, how was your

  Scheduler: NEXT!

  A: I was asking: How was your day?

  Scheduler: NEXT!

  B: Today I visited a

  Scheduler: NEXT!

  B: A zoo. I visited a zoo. And there were

  Scheduler: NEXT!

  B: Will you let me talk! There were kangaroos and

  Scheduler: NEXT!

  B: Where was I? There were kangaroos and llamas.

  Scheduler: NEXT!

  etc.

The scheduler slows things down: Not only does scheduling take time that could otherwise have been used productively, it also requires the state of the thread to be restored. That involves setting the CPU registers to their previous values from values in memory, requires the instruction pointer to be reset and the CPU instruction pipeline to be flushed. And when execution continues, the CPU chache will contain useless data from other threads, so reading from memory will be slow.

These context switches are what makes preemptive scheduling so terribly expensive. So while preemptive context switches are bad, they are better than the alternative: a computer that freezes up because some badly-written process forgets to yield. This can be adjusted by changing the frequency of interrupts, but a lower frequency also means the computer takes longer to react to input etc.

Title: Why should we expect user-space coroutines to be lighter than OS threads?

Body:
I have heard it said that managing concurrent TCP connections using user-space coroutines uses less resources per open connection than using an OS thread per connection.

Actually, OS threads and coroutines are essentially different ways of representing the same thing: a combination of control and state.

An OS thread stores:

A pc counter (representing control)

A stack pointer + other registers (representing state)

A coroutine requires:

A function pointer (representing control)

An environment pointer (representing state)

Why should we believe user-space coroutines to be a more resource-efficient approach?


问:
Program design - how to improve it and how to avoid coupling (Python)?
In the Python program structure below there are two modules with functions.

Problem description:

Functions are used inside other functions all over the place. Strong coupling (dependency). For example func1() in module 2 that reads from file is called many many times because it's called in almost every other function in both modules. That's resource and performance intensive, yet alone a bad practice.

Reading from file so many times (each time funct1() is called) can be costly.

Question: What is a good way to improve this design?

For example, passing functions from helper module 2 to functions in module 1 AS PARAMETERS? [ If I do that, I still have functions in module 2 dependent upon each other (ie funct4() uses funcr1(), funct2(), funct3(), etc) ]

My paradigm I started with: I was thinking: "Ah, I'm going to have a main module where the main thing happens. Then I will have a side module for functions that do some prep work and clean-up and called them from module 1." (Well, now I have this mess.) I wonder if a good design is to make functions less dependent on each other? Each function does one thing and DOESN'T call other functions?? Should I use classes? How? Is it about when to use classes versus modules? Functional versus OO design?

How would you redesign this so as little coupling as possible and file is read only once (or as few times as possible)?

Thanks for any tips.

module 1

```<code>(main module, program execution happens here)

from module2 import *

f1()
- uses funct1() 4 times
- uses funct2() 2 times

f2()
- uses func1() 2 times
- uses func2() 2 times

f3()
- uses func1() 1 time

f4()
- uses func2() 3 times
- uses func3() 3 times
- uses func4() 1 time

f5()
- uses func1() 2 times
- uses func2() 2 times
- uses func4() 4 times

f6()
- uses func1() 3 times
- uses func2() 3 times
- uses func4() 2 times
</code>```

module 2

(has helper functions that provide clean up and other functionality to module 1)

```<code>func1()
reads from file (with open('x.txt', 'r') af f: ...

func2()
- uses func1 1 time

func3()
- uses func1 1 time

func4()
- uses func1() 1 time
- uses func2() 2 times - uses func3() 1 time
</code>```

答:
There are at least two questions being asked here (arguably a lot more, so I'll have to ignore many of the little ones), but the solution to both comes down to writing a class that effectively encapsulates retrieving (your) data from (your) files. Since you specifically asked whether it should be a class or something else, in this language classes are the main data abstraction that's capable of remembering things, which is obviously necessary if you want to avoid reading the same file over and over, so that's why this should be a class.

Since you haven't told me what any of the functions in module 2 actually do after calling func1, I'm going to make up some fairly generic requirements. Let's pretend func1 reads a comma-separated value file of numbers. Say func2 gets the sum of all numbers. Say func3 gets the average and standard distribution of each row.

What you want to do is write a class that handles reading and parsing these files, and exposes methods to retrieve certain aspects of the data it finds. For instance, you might have the class' constructor take a single filename/filepath argument, so the file gets read exactly once during construction, and all method calls on the object merely manipulate the in-memory representation of the data you've already read. The important thing is that no other module should know (exactly) how this class gets its data. They should see getNums() and getStdDev() and getTotal() methods, but they probably shouldn't know whether these values come from a .csv file or an Excel spreadsheet or a website or wherever, and they certainly should not know whether that file/site is being cached or not.

If you do this right, it will be trivial to add getEigenvectors() and whatnot to module2 whenever you feel like it without even thinking about what module1 is doing. That is always the main goal of reducing coupling. This applies to pretty much every language that supports OOP.

If you need more specific help you'll have to explain more about what these functions actually do and why the generic advice I just gave is insufficient.


问:
Should I build undo stack in model or its wrapper?
I am building an application (Python/PyQt). The first-order item will be a tree view/model with many helper functions to add new items, move them around in the tree, etc.. Then I will have a main window object that will basically serve as a wrapper for the tree. This main window has a toolbar with buttons for the user to add/remove/move items (these buttons call the helper methods built into the tree object).

It's just about done, but alas I have decided to add undo/redo functionality using Qt's undo framework. It is my first time using undo/redo functionality, and I am curious whether there is consensus/experience on whether to implement the undo stack in the main window wrapper, or push the details into the internals of the tree class. I can see going either way.

Initially I put the undo stack functionality into the wrapper, so I could keep my tree simpler, and I was thinking that undo/redo is largely a sort of simple wrapper itself, not something I wanted to include in the functionality of the tree itself.

As I started, though, I realized I seemed to be breaking modularity, and because of the way these undo classes are implemented (they are fairly complicated and get into the internals of the tree model), it was starting to feel like I was making the wrapper concern itself with too many details of how the tree is implemented. This defeats the purpose of a simple wrapper.

So now I'm leaning toward incorporating the undo stack, in particular QUndoCommand classes, into the tree model, which is happy to deal with all these internals. This would likely simplify the wrapper, which is sort of the point. In other words, I'm thinking that I was naive about how complicated it was to add undo/redo functionality. It isn't simple, but something the model itself really should be working on.

However, I am completely new to this, so am wondering if I am making a silly design error  that will haunt me in two years when I try to expand the project. One thing I appreciate now: the way I incorporate undo/redo into this application will be a pain to switch in the future, so I want to do it right the first time.

Note added

Based on a comment, I searched 'undo design patterns' and got some potentially relevant links:

https://stackoverflow.com/questions/3448943/best-design-pattern-for-undo-feature

https://stackoverflow.com/questions/49755/design-pattern-for-undo-engine

If you look at the docs for Qt's undo framework linked above, it seems to use the command design pattern, so that's what I'm working with. So reposing my question in that light, should I generate the command objects within the original class, or its wrapper? Is there any obvious flaw in my above reasoning that it is better for modularity to do it in the original class?

Update added in 2020

I implemented the undo/redo functionality in the main class, not its wrapper and this was clearly the right move.

答:
It seems that you are not asking how to implement undo, since you've already chosen to work with Qt's Undo Framework, which already has an implementation to hook in to.

If I understand you correctly, you are more interested in where to implement the necessary code.  It seems that you have tried implementing it in two places which leads to complexity in either situation (been there before).  So in some ways it is an arbitrary choice.

One thing you may not have considered is creating more than one wrapper.  If you were to wrap your tree with a wrapper which added the undo functionality and then another wrapper which adds additional functionality your application requires, then you may end up with a better architecture.  Kind of in line with the Single Responsibility Principle.  Note you may wrap the tree in a different order, depending on your needs.

ContentLicense: CC BY-SA 4.0


问:
What is ## used for?
I have looked at other questions about this and the general consensus seems to be that ## is used for commenting out code. However, in the Interactive Editor for Python, prefixing a line with ## appears to make a sort of section header for the code. Why is this?

答:
In Python's syntax, a hash indicates the start of a comment, and all subsequent characters on the line are ignored. To quote the language reference:

A comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Comments are ignored by the syntax; they are not tokens.

The second hash therefore has no syntactic meaning in Python itself.

However, assuming you mean this specific "Interactive Editor for Python", one of its features is:

Matlab-style cell notation to mark code sections (by starting a line with ##).

Because the comments are not meaningful syntax, tools are free to interpret and use them how they like. Another example of this is pylint, which allows specially-formatted comments (# pylint: disable=message-name) to deactivate specific messages.

Title: What is ## used for?


问:
Is there a reason to have a bottom type in a programming language?
A bottom type is a construct primarily appearing in mathematical type theory. It is also called the empty type. It is a type that has no values, but is a subtype of all types.

If a function's return type is the bottom type, that means that it does not return. Period. Maybe it loops forever, or maybe it throws an exception.

What is the point of having this weird type in a programming language? It's not that common, but it is present in some, such as Scala and Lisp.

答:
In some languages, null has the bottom type, since the subtype of all types nicely defines what languages use null for (despite the mild contradiction of having null be both itself and a function that returns itself, avoiding the common arguments about why bot should be uninhabited).

It can also be used as a catch-all in function types (any -> bot) to handle dispatch gone awry.

And some languages allow you to actually resolve bot as an error, which can be used to provide custom compiler errors.


问:
Immutable vs Read-only vs Unmodifiable naming difference
So, I've looked at some similar questions asked here in regards to how these three should be used in naming. Usually, the answer is something along the lines of "it's conventional" and "just be consistent". I'm wondering if that's the same answer for my question.

I have an interface StatSet defined as

```<code>public interface StatSet {

    int getHitpoints();

    int getAttack();

    int getDefense();
}
</code>```

I want to define an implementation, where all fields are defined in the constructor:

```<code>public final class ReadOnlyStatSet {

    public ReadOnlyStatSet(final int hitpoints, final int attack, final int defense) {
        this.hitpoints = hitpoints;
        this.attack = attack;
        this.defense = defense;
    }

    public int getHitpoints() {
        return hitpoints;
    }

    public int getAttack() {
        return attack;
    }

    public int getDefense() {
        return defense;
    }

    private final int hitpoints;
    private final int attack;
    private final int defense;
    // no other fields
}
</code>```

My question is: is ReadOnlyStatSet the best name for this type of class. Or, would Immutable be more suited. In which grammar would I use one over the other.

答:
Naming your object immutable/read-only/unmodifiable seems superfluous.

It seems strange to me that you need to use immutable, read-only, unmodifiable or whatever else in the class name if the class already acts as immutable.

That's something that you should describe using keywords/class structure but not by the name of the class.


答:
Any of the above seem logical. Immutable, Unmodifable and ReadOnly all are acceptable choices. It is important however, that you stick to a convention. If some of your classes are 'Immutable' while others are 'ReadOnly', this could imply that there is a difference, which could confuse a consumer of your public code.

I personally use and prefer Immutable to describe objects which cannot be mutated, but I also see no reason why anybody who follows a different approach is wrong.

On an aside, I have seen Google's Guava project use 'Immutable', such as in ImmutableSet, while the Java collections use 'Unmodifiable', such as UnmodifiableSet. The only difference I have been able to discern is that Guava's ImmutableSet and friends are their own instances of a collection, while UnmodifiableSet and friends are wrappers which provide an 'Unmodifiable' view of a collection which may change underneath. A consumer of the UnmodifiableSet view cannot change the collection, but someone with a reference to the wrapped collection underneath could change what the UnmodifiableSet contains, so one could very easily argue that the UnmodifiableSet is not 'immutable.' This might be why it was not named as ImmutableSet when it was created.

Title: Immutable vs Read-only vs Unmodifiable naming difference

Body:
So, I've looked at some similar questions asked here in regards to how these three should be used in naming. Usually, the answer is something along the lines of "it's conventional" and "just be consistent". I'm wondering if that's the same answer for my question.

I have an interface StatSet defined as

```<code>public interface StatSet {

    int getHitpoints();

    int getAttack();

    int getDefense();
}
</code>```

I want to define an implementation, where all fields are defined in the constructor:

```<code>public final class ReadOnlyStatSet {

    public ReadOnlyStatSet(final int hitpoints, final int attack, final int defense) {
        this.hitpoints = hitpoints;
        this.attack = attack;
        this.defense = defense;
    }

    public int getHitpoints() {
        return hitpoints;
    }

    public int getAttack() {
        return attack;
    }

    public int getDefense() {
        return defense;
    }

    private final int hitpoints;
    private final int attack;
    private final int defense;
    // no other fields
}
</code>```

My question is: is ReadOnlyStatSet the best name for this type of class. Or, would Immutable be more suited. In which grammar would I use one over the other.


问:
Sometimes, "programming to interfaces" introduces possible (and avoidable) runtime exceptions?
Please consider the com.google.common.collect.ImmutableMap

Programming to its interface, Map , creates a bug that could blow-up in the runtime as such:

```<code>Map<String, Integer> myMap = ImmutableMap.copyOf(justSomeMap);
myMap.put(key, val); // bang. runtime error.
</code>```

In this case, the idea of "program to the interface, and don't worry about the implementing class" introduces a possible runtime bug.

The author of the ImmutableMap factory method recognized that and made the return type a class, not an interface. The methods that mutate Map were deprecated in ImmutableMap thus allowing the compiler to issue warnings.

Is everything I said above correct?

Next, a new interface ImmutableMapInterface could have easily been created for the ImmutableMap class. ImmutableMapInterface would exactly be Map but just without the methods that would allow ImmutableMap to mutate. Were there ImmutableMapInterface , you can keep programming to interfaces.

So, why is there no ImmutableMapInterface ? I am going to guess the reason is just expediency. I agree. Creating an interface for every single class sounds a little too extreme. right?

答:
Java does this in a few occasions and it is an abomination unto man.

This sort of thing is a textbook violation of the Liskov Substitution Principle, which leads to the sort of bugs you describe. Well written code does not do that.

You are right that making an interface for every single class is absurd. You need to use a little pragmatism in deciding what to make an interface for and what not to. The other thing to remember is that advice existed back in the C, C++ days. "Program to an interface" does not mean a literal interface in Java or C#. It works just as well with web apis or Internet protocols... Here an interface is a guaranteed/exposed behavior, not the underlying implementation.


答:
Maybe it loops forever, or maybe it throws an exception.

Sounds like a useful type to have in those situations, rare though they may be.

Also, even though Nothing (Scala's name for the bottom type) can have no values, List[Nothing] does not have that restriction, which makes it useful as the type of an empty list.  Most languages get around this by making an empty list of strings a different type than an empty list of integers, which kind of makes sense, but makes an empty list more verbose to write, which is a big drawback in a list-oriented language.

Title: Is there a reason to have a bottom type in a programming language?

Body:
A bottom type is a construct primarily appearing in mathematical type theory. It is also called the empty type. It is a type that has no values, but is a subtype of all types.

If a function's return type is the bottom type, that means that it does not return. Period. Maybe it loops forever, or maybe it throws an exception.

What is the point of having this weird type in a programming language? It's not that common, but it is present in some, such as Scala and Lisp.


问:
Managing scaffolding for debug vs production builds
The more I program the more I realize that most of my time is spent writing scaffolding for programs so that I can debug them and then strip away the scaffolding for production.

The problem is that I haven't found a language where the idea of scaffolding is a built-in notion. Ideally I want the scaffolding to be part of the actual program that gets stripped away for production deployments instead of being sections of code that are commented and un-commented whenever I'm debugging a problem.

An example of what I'm talking about in some made-up pseudo-language

```<code>def scaffold(f, *args)
  # ... pre condition verifications and state logging
  f(*args)
  # ... post condition verifications and state logging
end

@scaffold
def buggy_function(a, b, c)
  # ... some buggy code
end
</code>```

This looks a little bit like python decorators but the semantics is different. When running in production @scaffold literally dissolves from the AST and is nowhere to be found. Some of you might argue that I've created a very bloated and ad-hoc kind of type system but it's not quite that. I'll give an example to demonstrate.

I had written a parser for single and double quoted strings and it was failing somewhere in the middle of parsing another expression. The reason it was failing was because I wasn't handling the empty case ('') properly and I'm not aware of any type system that would have been able to verify the validity of the state-machine for the string parser to verify that the empty case was handled properly. The only way to uncover this would have been to write tests and even then getting a reduced test case would have required the kind of scaffolding I had to put in place to pinpoint the problem. Plus, you can easily imagine other scenarios where neither the type system nor tests would have hit the bug.

I haven't figured out a good way to manage the kind of scaffolding I need during debugging and an easy way to get rid of it once I'm done debugging. How do people usually handle it?

答:
Some languages (Including Delphi where I used it for this very purpose) have the concept of setting variables that can be checked at compile time so you can use an "IFDEF debug" directive to surround your scaffolding code and define / undefine debug appropriately.

IIRC you would set the variables in a dialog at the program level.

If your language is a bit more manual you should still be able to define a "debug" variable early on and do an IFDEF check for it throughout your code.


问:
Where can I get free public raw data?
In web development, a mashup is a web page or application that uses and combines data, presentation or functionality from two or more sources to create new services.

There are many sources for getting data (raw information). Governments are good examples.

However many of those cost and have complicated licensing.
For instance SMHI in Sweden sells temperature data meanwhile our neighbor country Norway gives it away for free.

One would say what kind of application are you building and what data do you need?  I would say give me some interesting data and I will do a good mashup of it. I could just plot it on Google maps for instance.

So the question is: Where can I get free data?

Note: I'm not interested in data mining using a webcrawler!

Please share your sources with me.

答:
New York City has a number of free MTA transit data feeds.

There's also a lot of other interesting public data sets in NYC such as restaurant health inspection data.

ContentLicense: CC BY-SA 2.5

Title: Where can I get free public raw data?


答:
I'll take a simple example: C++ vs Rust.

Here is a function used to throw an exception in C++11:

[[noreturn]] void ThrowException(char const* message,
                                 char const* file,
                                 int line,
                                 char const* function);
```

<p>And here is the equivalent in Rust:</p>

<pre class="lang-rust prettyprint-override"><code>fn formatted_panic(message: &str, file: &str, line: isize, function: &str) -> !;
</code>```

On a purely syntactic matter, the Rust construct is more sensible. Note that the C++ construct specifies a return type even though it also specifies it is not going to return. That's a bit weird.

On a standard note, the C++ syntax only appeared with C++11 (it was tacked on top), but various compilers had been providing various extensions for a while, so that third party analysis tools had to be programmed to recognize the various ways this attribute could be written. Having it standardized is obviously clearly superior.

Now, as for the benefit?

The fact that a function does not return can be useful for:

optimization: one can prune any code after it (it won't return), there is no need to save the registers (as it won't be necessary to restore them), ...

static analysis: it eliminates a number of potential execution paths

maintainability: (see static analysis, but by humans)

Body:
I'll take a simple example: C++ vs Rust.

Here is a function used to throw an exception in C++11:

[[noreturn]] void ThrowException(char const* message,
                                 char const* file,
                                 int line,
                                 char const* function);

And here is the equivalent in Rust:

fn formatted_panic(message: &str, file: &str, line: isize, function: &str) -> !;

On a purely syntactic matter, the Rust construct is more sensible. Note that the C++ construct specifies a return type even though it also specifies it is not going to return. That's a bit weird.

On a standard note, the C++ syntax only appeared with C++11 (it was tacked on top), but various compilers had been providing various extensions for a while, so that third party analysis tools had to be programmed to recognize the various ways this attribute could be written. Having it standardized is obviously clearly superior.

Now, as for the benefit?

The fact that a function does not return can be useful for:

optimization: one can prune any code after it (it won't return), there is no need to save the registers (as it won't be necessary to restore them), ...

static analysis: it eliminates a number of potential execution paths

maintainability: (see static analysis, but by humans)


答:
You are by far not the first person to have this need; many others have had it before you, so there has been quite a bit of research on the subject, and a solution in almost every decent language out there.

For a theoretical discussion, you might want to look at Programming by Contract, preconditions, postconditions and invariants.  It includes a list of languages with native support for that stuff, and also a list of third-party support libraries for languages that do not have native support.

As far as rolling your own is concerned:

(Because what good is it if it is "not invented here"?)

in C and C++ you have #ifdef;

in C# you have #if and also the [Conditional] attribute;

in java you have the built-in assertion keyword and also plain old if() which, when controlled by a constant, supposedly gets optimized out.

All these mechanisms can be used to achieve what you want to achieve.

Title: Managing scaffolding for debug vs production builds

Body:
The more I program the more I realize that most of my time is spent writing scaffolding for programs so that I can debug them and then strip away the scaffolding for production.

The problem is that I haven't found a language where the idea of scaffolding is a built-in notion. Ideally I want the scaffolding to be part of the actual program that gets stripped away for production deployments instead of being sections of code that are commented and un-commented whenever I'm debugging a problem.

An example of what I'm talking about in some made-up pseudo-language

```<code>def scaffold(f, *args)
  # ... pre condition verifications and state logging
  f(*args)
  # ... post condition verifications and state logging
end

@scaffold
def buggy_function(a, b, c)
  # ... some buggy code
end
</code>```

This looks a little bit like python decorators but the semantics is different. When running in production @scaffold literally dissolves from the AST and is nowhere to be found. Some of you might argue that I've created a very bloated and ad-hoc kind of type system but it's not quite that. I'll give an example to demonstrate.

I had written a parser for single and double quoted strings and it was failing somewhere in the middle of parsing another expression. The reason it was failing was because I wasn't handling the empty case ('') properly and I'm not aware of any type system that would have been able to verify the validity of the state-machine for the string parser to verify that the empty case was handled properly. The only way to uncover this would have been to write tests and even then getting a reduced test case would have required the kind of scaffolding I had to put in place to pinpoint the problem. Plus, you can easily imagine other scenarios where neither the type system nor tests would have hit the bug.

I haven't figured out a good way to manage the kind of scaffolding I need during debugging and an easy way to get rid of it once I'm done debugging. How do people usually handle it?


问:
What kind of programming pattern is appropriate for programming an algorithm with rules and exceptions?
I'm interested in coming up with an algorithm to solve a guessing game. The player is attempting to guess a sequence of 4 unique numbers from 1 to 9. After a guess, they are told how many numbers of their guess are correct and in the correct position and how many are correct and in the wrong position.

The approach I'm taking is to have a starting collection of all of the possible guesses and a collection of all the possible numbers. The collection of guesses is used to give the player an idea of all valid guesses remaining. The collection of numbers stores information about each digit:

whether it is definitely present or definitely not, and

which position it is definitely in or definitely not in.

Then, as the player is given more clues, I remove all guesses that must be invalid and update assumptions about the digits. The idea is that, after a certain number of guesses, the algorithm should continue to improve their odds of choosing the correct sequence.

I want to accomplish the process of striking items off of the list and making assumptions about the digits by creating rules. Whenever a rule's conditions are met, the number collection and/or guess collection should update. Rules should include:

if the current guess has no numbers in the correct position, all numbers in the sequence are definitely not in their current position,

if 4 of the numbers in the sequence are present, then all guesses without all 4 of these numbers are invalid,

if two guesses have 8 unique numbers between them and the sum of present numbers is only 3, then the 9th digit not guessed is definitely present,

etc.

I like the idea that I, as the developer, can continue to add rules as I discover patterns that I have not noticed (or have not been able to formalize) without much hassle. The problem lies in implementation.

Is there a programming pattern that allows me to make an extendable set of rules to test for and react to?

答:
Your problem is comparable to a program simulating a chess player. When in need of using a set of knowledge rules to produce the most suitable decisions, the logic programming seems to be the ideal solution. Using such a programming language (like Prolog), you can define the whole set of rules that govern your 'world', and finally you have to create a query regarding the ways in which a specific logical statement can become true. The program will execute all the possible paths from the initial condition to the final one, and it will output all the possible solutions. However, be aware that if the decision tree has too many branches, then this will be quite cpu-stressful.

On the other side, you can use a procedural language (like Java or perhaps R would be good, since it is focused on Machine Learning features). You can implement on your own one of the well-known Pathfinding algorithms (established by the AI community) to dynamically solve your problem. Each node in your graph will correspond to a decision state and the target node will be the final state. In the web you can find a lot of tutorials and demos of implementations of those algorithms.


答:
You might also look into expert systems, business rule engines, declarative programming, inference engines, A* search algorithm, Rete algorithm, Prolog, Datalog, CLIPS, metaknowledge, metaprogramming, reflection, etc...

J.Pitrat's blog has interesting entries, e.g. Know thyself etc...

Is there a programming pattern that allows me to make an extendable set of rules to test for and react to?

Yes, it is called an expert system (and is probably more a programming paradigm, or even a buzzword, than a programming pattern), the set of rules and facts being called the knowledge base

Experts systems have been in vogue in the 1980s & 1990s. Then came the so called AI winter (where AI meant artificial intelligence - an expression whose meaning has varied a lot during time).

Off-topic: I believe that the next AI winter would be an Abstract Interpretation winter. Static analysis of source code is today also a buzzword, even if formal methods are very useful, but they are not the silver bullet that some people proclaim.

AGI (artificial general intelligence) is however a very interesting research field.

Title: What kind of programming pattern is appropriate for programming an algorithm with rules and exceptions?

Body:
I'm interested in coming up with an algorithm to solve a guessing game. The player is attempting to guess a sequence of 4 unique numbers from 1 to 9. After a guess, they are told how many numbers of their guess are correct and in the correct position and how many are correct and in the wrong position.

The approach I'm taking is to have a starting collection of all of the possible guesses and a collection of all the possible numbers. The collection of guesses is used to give the player an idea of all valid guesses remaining. The collection of numbers stores information about each digit:

whether it is definitely present or definitely not, and

which position it is definitely in or definitely not in.

Then, as the player is given more clues, I remove all guesses that must be invalid and update assumptions about the digits. The idea is that, after a certain number of guesses, the algorithm should continue to improve their odds of choosing the correct sequence.

I want to accomplish the process of striking items off of the list and making assumptions about the digits by creating rules. Whenever a rule's conditions are met, the number collection and/or guess collection should update. Rules should include:

if the current guess has no numbers in the correct position, all numbers in the sequence are definitely not in their current position,

if 4 of the numbers in the sequence are present, then all guesses without all 4 of these numbers are invalid,

if two guesses have 8 unique numbers between them and the sum of present numbers is only 3, then the 9th digit not guessed is definitely present,

etc.

I like the idea that I, as the developer, can continue to add rules as I discover patterns that I have not noticed (or have not been able to formalize) without much hassle. The problem lies in implementation.

Is there a programming pattern that allows me to make an extendable set of rules to test for and react to?


问:
Recurring database migration
I'm importing data from older website to new one using database migrations. I have created first as one of first steps of development phase of new site. Then I planned to create another one, that will do final data import at the end of development process.

I was then faced with question, what will happen, if another import will be required a bit later?

Since (for many reasons) we cannot afford for a better solution (like a full installer, able to migrate current data at any point in time) and since such situation have small changes to arise and won't happen again. I suggested, that in this case we should copy import migration on top of all others and execute it once more.

In reply I was suggested, that I should rather create a recurring migration. I.e. the one, that updates migration table in database at the end of migration process, changes its own timestamp and thus forces migration system to "think", that there's always a new migration to be applied on top of all others.

I was a bit surprised with such suggestion. Is it wise and secure to create such thing?

答:
If I got you correctly, you need to migrate just data from a production one database to a development database, and you might have to repeat that process a few times. So as long as you implement the migration in a repeatable, idempotent manner, that should be not much of a problem. The most simple solution might be to clear all previously migrated data from your development database before a new migration, but you might not be happy with that due to performance reasons, or because you have some data in your development database which might be kept there. If that is the case, you will have to design some synching mechanism between those two database, or at least a mechanism to keep or recreate the data in the development DB you do not want to be deleted.

What I cannot tell you is if fiddling around with the time stamps of your migration table will be a problem - for this one needs to know the gory details of your framework.

Title: Recurring database migration


答:
Karl's answer is good. Here is an additional use that I don't think anyone else has mentioned. The type of

```<code>if E then A else B
</code>```

should be a type that includes all the values in the type of A and all the values in the type of B.  If the type of B is Nothing, then the type of the if expression can be the type of A. I'll often declare a routine

```<code>def unreachable( s:String ) : Nothing = throw new AssertionError("Unreachable "+s)
</code>```

to say that code is not expected to be reached.  Since its type is Nothing, unreachable(s) can now be used in any if or (more often) switch without affecting the type of result. For example

```<code> val colour : Colour := switch state of
         BLACK_TO_MOVE: BLACK
         WHITE_TO_MOVE: WHITE
         default: unreachable("Bad state")
</code>```

Scala has such a Nothing type.

Another use case for Nothing (as mentioned in Karl's answer) is List[Nothing] is the type of lists each of whose members has type Nothing. Thus it can be the type of the empty list.

The key property of Nothing that makes these use cases work is not that it has no values --although in Scala, for example, it does have no values-- it is that it is a subtype of every other type.

Suppose you have a language where every type contains the same value -- let's call it (). In such a language the unit type, which has () as its only value, could be a subtype of every type. That doesn't make it a bottom type in the sense that the OP meant; the OP was clear that a bottom type contains no values. However, as it is a type that is a subtype of every type, it can play much the same role as a bottom type.

Haskell does things a bit differently. In Haskell, an expression that never produces a value can have the type scheme forall a.a. An instance of this type scheme will unify with any other type, so it effectively acts as a bottom type, even though (standard) Haskell has no notion of subtyping.  For example, the error function from the standard prelude has type scheme forall a. [Char] -> a. So you can write

```<code>if E then A else error ""
</code>```

and the type of the expression will be the same as the type of A, for any expression A.

The empty list in Haskell has the type scheme forall a. [a]. If A is an expression whose type is a list type, then

```<code>if E then A else []
</code>```

is an expression with the same type as A.

Body:
Karl's answer is good. Here is an additional use that I don't think anyone else has mentioned. The type of

if E then A else B

should be a type that includes all the values in the type of A and all the values in the type of B.  If the type of B is Nothing, then the type of the if expression can be the type of A. I'll often declare a routine

def unreachable( s:String ) : Nothing = throw new AssertionError("Unreachable "+s)

to say that code is not expected to be reached.  Since its type is Nothing, unreachable(s) can now be used in any if or (more often) switch without affecting the type of result. For example

 val colour : Colour := switch state of
         BLACK_TO_MOVE: BLACK
         WHITE_TO_MOVE: WHITE
         default: unreachable("Bad state")

Scala has such a Nothing type.

Another use case for Nothing (as mentioned in Karl's answer) is List[Nothing] is the type of lists each of whose members has type Nothing. Thus it can be the type of the empty list.

The key property of Nothing that makes these use cases work is not that it has no values --although in Scala, for example, it does have no values-- it is that it is a subtype of every other type.

Suppose you have a language where every type contains the same value -- let's call it (). In such a language the unit type, which has () as its only value, could be a subtype of every type. That doesn't make it a bottom type in the sense that the OP meant; the OP was clear that a bottom type contains no values. However, as it is a type that is a subtype of every type, it can play much the same role as a bottom type.

Haskell does things a bit differently. In Haskell, an expression that never produces a value can have the type scheme forall a.a. An instance of this type scheme will unify with any other type, so it effectively acts as a bottom type, even though (standard) Haskell has no notion of subtyping.  For example, the error function from the standard prelude has type scheme forall a. [Char] -> a. So you can write

if E then A else error ""

and the type of the expression will be the same as the type of A, for any expression A.

The empty list in Haskell has the type scheme forall a. [a]. If A is an expression whose type is a list type, then

if E then A else []

is an expression with the same type as A.


问:
Alternative to goto-statement in this case?
Currently I am using gotos for closing handles and general cleanup if an error occurs.

Since I don't want to nest all the ifs and a function for cleanup would require a return besides the cleanup(); call, I don't have any good ideas left.

The structure is like so:

```<code>if (condition1) {
   goto cleanup;
}

if (condition2) {
   goto cleanup;
}

if (condition3) {
   goto cleanup;
}

// do stuff only if all checks passed

cleanup:
CloseHandle(x);
CloseHandle(y);
// etc.
</code>```

答:
In C a typical way to simplify error checking and avoid deep nested if is:

```<code>do
{
  if (condition1) break;

  /* 1. do something... */

  if (condition2) break;

  /* 2. do something else... */

  if (condition3) break;

  /* 3. do something else... */
} while(0);

/* Cleanup */
</code>```

There are various opinion on this "idiom" (e.g. take a look at Do you consider this technique “BAD”?).

Possibly you should add a comment on the do to make it clear to anyone what's happening.

You can often rewrite the code using a helper function and change the fake do-loop into:

```<code>void func(X *x, Y *y)
{
  if (condition1) return;

  /* 1. do something... */

  if (condition2) return;

  /* 2. do something else... */

  if (condition3) return;

  /* 3. do something else... */
}

/* ... */
X x;
Y y;

func(&x, &y);

/* Cleanup */
</code>```

and it won't be considered a "bad practice" since it's more expected.

If you haven't the intermediate steps (1. and 2.) this is probably enough:

```<code>int stop = condition1 || condition2 || condition3;

if (!stop)
{
  /* ... */
}

/* Cleanup */
</code>```

Body:
In C a typical way to simplify error checking and avoid deep nested if is:

do
{
  if (condition1) break;

  /* 1. do something... */

  if (condition2) break;

  /* 2. do something else... */

  if (condition3) break;

  /* 3. do something else... */
} while(0);

/* Cleanup */

There are various opinion on this "idiom" (e.g. take a look at Do you consider this technique “BAD”?).

Possibly you should add a comment on the do to make it clear to anyone what's happening.

You can often rewrite the code using a helper function and change the fake do-loop into:

void func(X *x, Y *y)
{
  if (condition1) return;

  /* 1. do something... */

  if (condition2) return;

  /* 2. do something else... */

  if (condition3) return;

  /* 3. do something else... */
}

/* ... */
X x;
Y y;

func(&x, &y);

/* Cleanup */

and it won't be considered a "bad practice" since it's more expected.

If you haven't the intermediate steps (1. and 2.) this is probably enough:

int stop = condition1 || condition2 || condition3;

if (!stop)
{
  /* ... */
}

/* Cleanup */


答: If your data needs lots of querying then a NoSQL solution is not good and when you need transactional support (ACID) then a NoSql is not the best fit. I think NoSQL shines when you have a lot of reads which needs to be fast and when the structure is somewhat adhoc, you retrieve by document or by page structure, something like that. But a lots of NoSQL-solutions improves a lot quite fast so there shortcomings maybe soon will be gone. Anyway I think relational databases are still a good fit for most applications. </p>

Title: When would someone use MongoDB (or similar) over a Relational DBMS?

Body:
I'm a bit confused about the whole NoSQL thing and such.
When would you choose to use something like MongoDB over something like Oracle or MySQL?
I don't really understand the "difference" as far as usage goes between them.

From my understanding NoSQL type databases aren't meant to replace RDBMSes, but what exactly are they meant to do?


答:
The cleanup could be in an outer function, and then return can be used instead of goto:

```<code>void main_func() {
    /* Set-up goes here */
    handle x = ...;
    handle y = ...;
    void result = inner_func(x, y);

    /* Clean-up goes here */
    CloseHandle(x);
    CloseHandle(y);
}

void inner_func(x, y) {
    if (condition1) return;
    if (condition2) return;
    if (condition3) return;

    /* Do things here */
}
</code>```

But goto for things like this isn't that bad, in my opinion.

Title: Alternative to goto-statement in this case?

Body:
Currently I am using gotos for closing handles and general cleanup if an error occurs.

Since I don't want to nest all the ifs and a function for cleanup would require a return besides the cleanup(); call, I don't have any good ideas left.

The structure is like so:

```<code>if (condition1) {
   goto cleanup;
}

if (condition2) {
   goto cleanup;
}

if (condition3) {
   goto cleanup;
}

// do stuff only if all checks passed

cleanup:
CloseHandle(x);
CloseHandle(y);
// etc.
</code>```

Body:
The cleanup could be in an outer function, and then return can be used instead of goto:

void main_func() {
    /* Set-up goes here */
    handle x = ...;
    handle y = ...;
    void result = inner_func(x, y);

    /* Clean-up goes here */
    CloseHandle(x);
    CloseHandle(y);
}

void inner_func(x, y) {
    if (condition1) return;
    if (condition2) return;
    if (condition3) return;

    /* Do things here */
}

But goto for things like this isn't that bad, in my opinion.


答:
It is useful for static analysis to document the fact that a particular code path is not reachable. For example if you write the following in C#:

```<code>int F(int arg) {
 if (arg != 0)
  return arg + 1; //some computation
 else
  Assert(false); //this throws but the compiler does not know that
}
void Assert(bool cond) { if (!cond) throw ...; }
</code>```

The compiler will complain that F does not return anything in at least one code path. If Assert were to be marked as non-returning the compiler would not need to warn.

Body:
It is useful for static analysis to document the fact that a particular code path is not reachable. For example if you write the following in C#:

int F(int arg) {
 if (arg != 0)
  return arg + 1; //some computation
 else
  Assert(false); //this throws but the compiler does not know that
}
void Assert(bool cond) { if (!cond) throw ...; }

The compiler will complain that F does not return anything in at least one code path. If Assert were to be marked as non-returning the compiler would not need to warn.


答:
Yes this is a quite useful type; while its role would be mostly interior to the type system, there are some occasion where the bottom type would appear in openly.

Consider a statically typed language in which conditionals are expressions (so the if-then-else construction doubles as the ternary operator of C and friends, and there might be a similar multi-way case statement). Functional programming language have this, but it happens in certain imperative languages as well (ever since ALGOL 60). Then all branch expressions must ultimately produce the type of the whole conditional expression. One could simply require their types to be equal (and I think this is the case for the ternary operator in C) but this is overly restrictive especially when the conditional can also be used as conditional statement (not returning any useful value). In general one wants each branch expression to be (implicitly) convertible to a common type that will be the type of the full expression (possibly with more or less complicated restrictions to allow that common type to be effectively found by the complier, cf. C++, but I won't go into those details here).

There are two kinds of situations where a general kind of conversion will allow necessary flexibility of such conditional expressions. One is already mentioned, where the result type is the unit type void; this is naturally a super-type of all other types, and allowing any type to be (trivially) converted to it makes it possible to use the conditional expression as conditional statement. The other involves cases where the expression does return a useful value, but one or more branches are incapable of producing one. They will usually raise an exception or involve a jump, and requiring them to (also) produce a value of the type of the whole expression (from an unreachable point) would be pointless. It is this kind of situation that can be gracefully handled by giving exception-raising clauses, jumps, and calls that will have such an effect, the bottom type, the one type that can be (trivially) converted into any other type.

I would suggest writing such a bottom type as * to suggest its convertibility to arbitrary type. It may serve other useful purposes internally, for instance when trying to deduce a result type for a recursive function that does not declare any, the type inferencer could assign the type * to any recursive call to avoid a chicken-and-egg situation; the actual type will be determined by non-recursive branches, and the recursive ones will be converted to the common type of the non-recursive ones. If there are no non-recursive branches at all, the type will remain *, and correctly indicate that the function has no possible way of ever returning from the recursion. Other than this and as result type of exception throwing functions, one can use * as component type of sequences of length 0, for instance of the empty list; again if ever an element is selected from an expression of type [*] (necessarily empty list), then the resulting type * will correctly indicated that this can never return without an error.


问:
What are the real benefits of static code analysis?
Tools like pc-lint or QAC can be used to perform static code analysis on a code base.

In my experience the static analysis often yields a huge amount of noise, i.e. warnings on things that are not real bugs but somehow violate one of the rules in a given rule set. Turning off certain rules (either for good in the rule set or via special comments in the code) can be a real cumbersome process.

What are the real benefits of static code analysis?

答: In my previous company we have used the static analyzer by Parasoft. And it was believed within the team that at least 60% of the run time bugs were caught before compilation. </p>


问:
Converting a one-to-many xml design to a many-to-many
I have an xml file format that looks something like this:

```<code><topLevelTag>
  <category name="foo">
    <item attrib="value">ItemName</item>
    <item attrib="value2">AnotherItem</item>
  </category>
  <category name="bar">
    <item attrib="value">ItemName</item>
    <item attrib="value2">AnotherItem</item>
  </category>
</topLevelTag>
</code>```

The code that parses this creates an instance of ItemName and is told that it's one category is, in the first case, "foo", and then creates a second instance of ItemName which has associated category "bar".

The problem is that I need to redesign the system so that each Item can have more than one Category. But I still need to be able to create multiple items as well. For example (using bullets instead of xml) I might need to create the following instances:

ItemName

Primary Category - "foo"

Secondary Category - "bar"

ItemName

Primary Category - "bar"

Secondary Category - "foo"

ItemName

Primary Category - "foo"

Secondary Category - "quux"

AnotherItem

Primary Category - "baz"

Secondary Category - "foo"

Tertiary Category - "monkey"

etc ... (no cap)

StillAnotherItem

etc ...

etc ... (no cap)

How can I design my XML format to encapsulate this many-to-many relationship?

I am aware this question is on the borderline between StackOverflow and Programmers. I chose to put it here because it is a software architecture and design question. If not please let me know and I'll be happy to move it. Precedent one | Precedent two | Precedent three

答:
Why can't you use the same structure as in your bullets?

```<code><topLevelTag>
    <item id="1">
        <value>ItemName</value>
        <category level="primary">foo</category>
        <category level="secondary">bar</category>
    </item>
    <item id="2">
        <value>ItemName</value>
        <category level="primary">foo</category>
        <category level="secondary">bar</category>
    </item>
</topLevelTag>
</code>```

(the "id" distinguishes two instances of the same itemName).

For sure, you can't have a "many to many" structure explicitly - you must pivot (root?) either on item, or on category, since you need a hierarchical data set.

Or you change completely layout and pivot on the many-to-many relationship; this is easiest to convert to and from a RDBMS storage.

```<code><topLevelTag>
    <item id="1">...</item>
    <category id="1">foo</category>
    <mapping>
        <map item="1" category="1" />
        <map item="1" category="2" />
        <map item="2" category="2" />
    </mapping>
</topLevelTag>
</code>```

Body:
Why can't you use the same structure as in your bullets?

<topLevelTag>
    <item id="1">
        <value>ItemName</value>
        <category level="primary">foo</category>
        <category level="secondary">bar</category>
    </item>
    <item id="2">
        <value>ItemName</value>
        <category level="primary">foo</category>
        <category level="secondary">bar</category>
    </item>
</topLevelTag>

(the "id" distinguishes two instances of the same itemName).

For sure, you can't have a "many to many" structure explicitly - you must pivot (root?) either on item, or on category, since you need a hierarchical data set.

Or you change completely layout and pivot on the many-to-many relationship; this is easiest to convert to and from a RDBMS storage.

<topLevelTag>
    <item id="1">...</item>
    <category id="1">foo</category>
    <mapping>
        <map item="1" category="1" />
        <map item="1" category="2" />
        <map item="2" category="2" />
    </mapping>
</topLevelTag>


问:
How implement an IP stack?
I want to understand what implement an IP stack means.

I explain myself : I've wrote two Java little applications (Client-Server) which communicate over a LAN with TLS. In my code, I didn't have to deal with IP addressing :
First I would get IP from the Server with an UDP multicast, and then I would create a SSL Socket and connect it to that IP address.

Now, I have to work on Suse, with C. And I have to implement an IP stack.

I don't understand how an IP stack can be implemented in a application, I thought it was implemented in the OS.

Can someone explain what i'm missing ?

答:
You can implement an IP stack whereever you want, in the kernel, in a driver, in a service, in a library, or in an app. Whatever makes the most sense in your case.

An IP stack is an application just like any other. You write it just like any other … well, actually, with an IP stack you have the huge advantage that you have a precise specification of the desired behavior, and don't have to coax some fuzzy set of imprecise requirements out of a clueless client. The specification is so precise, in fact, that you can interpret the ASCII art diagrams from the RfC and automatically generate packet parsers from that. (That's how the VPRI FONC project is able to implement a full IP stack in 30 lines.)

Title: How implement an IP stack?


问:
Handling Destructors in MVVM
I'm making a Model View View-Model (MVVM) application using Delphi XE6.

Since I'm using Pascal rather than C#, I need to manage destruction myself.
I'm not sure how to handle form destruction.

My Form has an associated FormViewModel. The FormViewModel should be responsible for all the form's behaviour. I would expect this to include destruction. Also, when the Form is destroyed, so must the FormViewModel be destroyed. So it makes sense to handle these things together. The problem is I can't destroy the FormViewModel from a method within the FormViewModel, since this is being destroyed.

On the other hand, I can handle the job in another class, such as a Controller class. But then I have to get the Form to tell the Controller which FormViewModel instance to destroy. This would involve the Form knowing about the FormViewModel, which is not compliant with MVVM.

Have I misunderstood something about MVVM? Is there a way to do this in an unmanaged language without violating MVVM?

答:
If your Form object holds a reference to its FormViewModel object, the FormViewModel object can be easily disposed in the destructor of the Form object.

Your notion that the Form object should know nothing about the FormViewModel object is misplaced (and impossible in MVVM).  The FormViewModel object is always tightly-bound to the Form object; the whole point of having a FormViewModel object is to have a layer of abstraction you can tightly bind to, so that you can decouple from the business domain objects.

Title: Handling Destructors in MVVM


问:
Can you refer to the callback function as an API?
A system design is decoupled into two layers say layer A and layer B.
The interaction between layer A and layer B occurs through an interface that is exposed by layer B in form of an API. This interaction has an asynchronous design pattern. Layer A registers a callback function with the layer B API. Now can one technically refer to the callback function as exposed by layer A and refer to it as API of layer A?</p>

答:
Normally, no.  The callback is part of the API exposed by layer B.

The API of Layer B defines the form (prototype) of the callback, the API of Layer B defines the functions to register and unregister the callback, and Layer B defines the conditions under which the callback will be invoked. Furthermore, since the callback gets registered, it will work even if it is not publicly exposed by Layer A. (The callback can be a private method of the object that implements Layer A.)  Therefore, it is totally, completely, unquestionably, part of Layer B's API.

Now, if Layer A decides to also publicly expose the callback, then it also becomes part of Layer A's API, but that's twisted, and probably useless.  The chances of some third Layer X finding it useful to invoke the callback of A as part of the public API of A are very slim.  As a matter of fact, even on such an unlikely occasion, I would still avoid having Layer X invoke the callback, because it would cause confusion.  I would have A expose an entirely separate method for that.