问:
Pooling (Singleton) Objects Against Connection Pools
Given the following scenario

A canned enterprise application that maintains its own connection pool

A homegrown client application to the enterprise app. This app is built using Spring framework, with the DAO pattern

While I may have a simplistic view of this, I think the following line of thinking is sound:

Having a fixed pool of DAO objects, holding on to connection objects from the pool. Clearly, the pool should be capable of scaling up (or down depending on need) and the connection objects must outnumber the DAOs by a healthy margin. Good

Instantiating brand new DAOs for every request to access the enterprise app; each DAO will attempt to grab a connection from the pool and release it when it's done. Bad

Since these are service objects, there will be no (mutable) state held by the objects (reduced risk of concurrency issues)

I also think that with #1, there should be little to no resource contention, while in #2, there'll almost always be a DAO waiting to be serviced. Is my thinking correct and what could go wrong?

答: In addition to the practical insight from Robert Harvey's answer, I think it's important to keep in mind that big picture, both schemes are doing equivalent things. There will be some sort of queuing involved, regardless of which scheme you choose. The difference will be where that logic lives. If there is resource contention with providing connections to DAO objects, there would have been resource contention with allocating a DAO object to its consumer.</p>


问:
Algorithm/data structure to answer "what recipes can I make with this set of ingredients?"
Formally, let s(U, Q) = {V | V ∈ U and V ⊆ Q} where U, Q, and V all represent sets, and U, more specifically, represents a set of sets. For the sake of example, U might be a set of the (sets of) ingredients required for various recipes in a cookbook with Q representing the set of ingredients I have V representing a recipe I could make with those ingredients. The query s(U, Q) corresponds to the question "What all can I make with these ingredients?"

What I'm looking for is a data representation that indexes U in such a way that it supports efficient queries of s(U, Q) where Q and all members of U will generally be small compared to the union of all the members of U. In addition, I'd like it to be able to efficiently update U (e.g., add or remove a recipe).

I can't help but think that this problem must be well understood, but I haven't been able to find a name or reference for it. Does anyone know of a strategy for solving this efficiently or a place where I can read more about it?

As far as thinking about a solution, one thought I had was to build a decision tree for the set U. At each node in the tree, the question "does your ingredient list contain x?" would be asked with x chosen to maximize the number of members of U that get eliminated by the answer.  As U gets updated, this decision tree would need to be re-balanced to minimize the number of questions required to find the correct result. Another thought is to represent U with something like an n-dimensional boolean 'octree' (where n is the number of unique ingredients).

I believe that "What recipes can be made with these ingredients?" can be answered by taking the cartesian product of the (sets of ingredients required for the) recipes in the cookbook with the powerset of the ingredients one has and filtering the resulting ordered pairs for pairs in which both elements are equal, but this is not an efficient solution, and what I'm asking about is how to optimize this kind of operation; how would one compose this in SQL such that it would be efficient and what does SQL do that allows this to be efficient?

Although I use the illustration of a cookbook of recipes and a set of ingredients, I anticipate that the number of 'recipes' and the number of 'ingredients' will be very large (up to hundreds of thousands each), though the number of ingredients in a given recipe and the number of ingredients in a given ingredient set will be relatively small (probably around 10-50 for a typical 'recipe' and around 100 for a typical 'ingredient set'). Additionally, the most common operation will be the query s(U, Q), so it should be most optimal. This also means that a brute force algorithm that requires checking every recipe or operating over every ingredient would be undesirably slow on its own, however. With clever caching, I think this might not perform too badly, though.

答:
For the numbers you gave, just brute force it.

Here's a JavaScript program that brute forces it for 10 ingredients in the DB, 10 recipes in the DB, each recipe needs 2 ingredients, and I have 5 ingredients available:

```<code>var i, j;
var numIngredients = 10;
var numRecipes = 10;
var numIngredientsPerRecipe = 2;
var numIngredientsInQuery = 5;

function containsAll(needles, haystack){
  var i, len;
  for(i = 0 , len = needles.length; i < len; i++){
      if(haystack.indexOf(needles[i]) == -1) {
          return false;
      }
  }
  return true;
}

// Set up a fake DB of recipes
var ingredients = [];
for (i = 0; i < numIngredients; i++) {
    ingredients.push(i);
}
console.log('Here are the ingredients:', ingredients);

var recipes = [];
for (i = 0; i < numRecipes; i++) {
    var neededIngredients = [];
    for (j = 0; j < numIngredientsPerRecipe; j++) {
        neededIngredients.push(Math.floor(Math.random() * numRecipes));
    }
    recipes.push({ recipeId: i, needed: neededIngredients});
}
console.log('Here are the recipes:', recipes);

// Set up a fake query
var ingredientsAvailable = [];
for (i = 0; i < numIngredientsInQuery; i++) {
    ingredientsAvailable.push(Math.floor(Math.random() * numRecipes));
}

console.log("Here's a query:", ingredientsAvailable);

//Time how long brute force takes
var start = Date.now();
var result = [];
for (i = 0; i < numRecipes; i++) {
    var candidateRecipe = recipes[i];
    if (containsAll(candidateRecipe.needed, ingredientsAvailable)) {
        result.push(candidateRecipe);
    }
}
var end = Date.now();
console.log('Found ' + result.length + ' recipes in ' + (end - start) + ' milliseconds.');
console.log(result);
</code>```

It runs in 0 milliseconds. I chose these small numbers so you could run it yourself a couple of times and convince yourself it does what you want and is relatively free of bugs.

Now change it so that we have 1'000'000 ingredients in the DB, 1'000'000 recipes in the DB, 50 ingredients per recipe and 100 ingredients available to me. I.e. values that are all equal or greater than the largest use case you gave.

It runs in 125 milliseconds under nodejs, and this is with the dumbest implementation with absolutely no effort to optimize.

ContentLicense: CC BY-SA 3.0

Body:
For the numbers you gave, just brute force it.

Here's a JavaScript program that brute forces it for 10 ingredients in the DB, 10 recipes in the DB, each recipe needs 2 ingredients, and I have 5 ingredients available:

var i, j;
var numIngredients = 10;
var numRecipes = 10;
var numIngredientsPerRecipe = 2;
var numIngredientsInQuery = 5;

function containsAll(needles, haystack){
  var i, len;
  for(i = 0 , len = needles.length; i < len; i++){
      if(haystack.indexOf(needles[i]) == -1) {
          return false;
      }
  }
  return true;
}

// Set up a fake DB of recipes
var ingredients = [];
for (i = 0; i < numIngredients; i++) {
    ingredients.push(i);
}
console.log('Here are the ingredients:', ingredients);

var recipes = [];
for (i = 0; i < numRecipes; i++) {
    var neededIngredients = [];
    for (j = 0; j < numIngredientsPerRecipe; j++) {
        neededIngredients.push(Math.floor(Math.random() * numRecipes));
    }
    recipes.push({ recipeId: i, needed: neededIngredients});
}
console.log('Here are the recipes:', recipes);

// Set up a fake query
var ingredientsAvailable = [];
for (i = 0; i < numIngredientsInQuery; i++) {
    ingredientsAvailable.push(Math.floor(Math.random() * numRecipes));
}

console.log("Here's a query:", ingredientsAvailable);

//Time how long brute force takes
var start = Date.now();
var result = [];
for (i = 0; i < numRecipes; i++) {
    var candidateRecipe = recipes[i];
    if (containsAll(candidateRecipe.needed, ingredientsAvailable)) {
        result.push(candidateRecipe);
    }
}
var end = Date.now();
console.log('Found ' + result.length + ' recipes in ' + (end - start) + ' milliseconds.');
console.log(result);

It runs in 0 milliseconds. I chose these small numbers so you could run it yourself a couple of times and convince yourself it does what you want and is relatively free of bugs.

Now change it so that we have 1'000'000 ingredients in the DB, 1'000'000 recipes in the DB, 50 ingredients per recipe and 100 ingredients available to me. I.e. values that are all equal or greater than the largest use case you gave.

It runs in 125 milliseconds under nodejs, and this is with the dumbest implementation with absolutely no effort to optimize.


问:
Implementing a series of independent Actions that are disparate but with common accessibility
I have a requirement to implement a type of AI for a project, the issue is that I am having trouble visualizing how the AI should actually be implemented.

Essentially, I want the AI to be as dynamic as possible. That is, if I decide in the future to add another type of AI Action (as we'll call it), I don't need to rewrite the class using the AI or AI Action.

What I have now, is a very rough idea, but it should help clarify.

```<code>public interface IAiAction
{
    List<IAiProperty> Properties { get; }

    DateTime LastUpdate { get; }

    bool Update(Entity e);
}

public interface IAiProperty
{

}
</code>```

Then I have something like:

```<code>public class WanderAction : IAiAction
{
    private List<IAiProperty> _Properties = new List<IAiProperty>();
    public List<IAiProperty> Properties { get { return _Properties; } }

    private DateTime _LastUpdate;
    public DateTime LastUpdate { get { return _LastUpdate; } }

    private Point _WanderTo;

    public bool Update(Entity e)
    {
        // Do stuff here

        return true;
    }
}

public struct WanderDistance : IAiProperty
{
    private Point _Home;
    private float _MaxDistance;

    public Point Home { get { return _Home; } private set { _Home = value; } }
    public float MaxDistance { get { return _MaxDistance; } private set { _MaxDistance = value; } }

    public WanderDistance(Point h, float m)
    {
        _Home = h;
        _MaxDistance = m;
    }
}
</code>```

Then, in the class with the actions:

```<code>private List<IAiAction> _AiActions = new List<IAiAction>();
public List<IAiAction> AiActions { get { return _AiActions; } }

public override void Update(Vector2F force)
{
    foreach (IAiAction action in AiActions)
        action.Update(this);

    base.Update(force);
}
</code>```

The problem is that this does not extend well. I'm not even sure how I got to this stage, as I've never had to do something like this before.

This code is by no means a requirement. If anyone has any other ideas for how it can be done (even if they are far separate from what this indicates) I am up for it.

For example, if I had an IAiAction that was to determine what the Entity was going to say randomly, this leaves very poor room to do that. I also, for the WanderAction as an example, need to return a Vector2F to the calling class, to add it to the force parameter of the Update(Vector2F) method.

If any clarification beyond this is necessary, please let me know. This isn't holding up the project, but it is causing me issue.

The only other method I can think of is to implement a sort of state that is carried through the programme. This would technically satisfy my requirements, but I'm curious if there is a better way.

答:
If I'm understanding correctly, you have an Entity, which can do things (like walk, talk, and so on), and want to use classes to be able to provide this entity with AI behaviours. These will be triggered in some loop (or by schedule, or whatever) and will then cause some behaviour in the entity (walking, talking, etc.).

There's a few you're going to need two things:

An interface for AI actions, allowing them to be triggered

A way for the AI action to actually effect the change in behaviour

For the first one, you have your interface IAiAction. Let's look at how it's used:

```<code>foreach (IAiAction action in AiActions)
    action.Update(this);
</code>```

So from this, it seems like actually, the only member on IAiAction should be:

```<code>void Update(Entity entity);
</code>```

This also relieves you of needing IAiProperty at all. WanderDistance, for example, can just be a normal, private member on WanderAction.

Looking at this interface, there also doesn't seem to be anything AI-specific about it. It could work just as well for user-controlled actions, or actions so dumb they can't really be called AI (like waiting in place forever). Why not just IAction, or IInstructor or something?

It may be that as you implement more of these AI classes, you do find common structure. You could pull that out into a dependency or base class. But there's no need to pre-emptively impose structure, and certainly no need to expose it publicly. Just expose what consumers actually need. As an example, maybe you were considering using LastUpdated so that the Entity could only call actions that have been updated more than a second ago, or whatever. But why not keep LastUpdated private, and let the actions can make that decision themselves?

As for the second bullet point, it'd be tough to try to have some general way for the AI action to return an instruction for the Entity to understand. Instead, Entity should expose what it can do through methods on an interface:

```<code>void SetDestination(Vector2D destination){ /*...*/ }
void Say(string utterance) { /*...*/ }
</code>```

Now an AI action can call methods, instead of having to return something and assume the Entity will have the logic to handle it. You could, for example easily add a ReactToDangerAction which both yells and runs away from the danger, given the above two methods.

This is a starting point, but one design improvement which may go a long way is to not pass the Entity in to the Update method, but instead pass it in through the constructor. After all, it doesn't make sense for your example WanderAction to be shared by two different entities, as they'd probably have different homes. So it might as well be tied to one particular entity permanently, rather than accepting one each time the method is called and hoping it always gets the same one. This would probably require a little boilerplate (factory classes, possibly), but would enable some design improvements.

For example, you could adhere better to the Interface Segregation Principle by splitting the Entity's interface into several (IDirectable, IVocal, etc.). Or, if you don't like the idea of Entity exposing methods allowing it to be ordered around by all and sundry, you could even make the SetDestination and Say methods private and pass them into the actions' constructors as delegates. It would also give flexibility if in the future you found that some actions shouldn't be tied to particular entities, or should be tied to multiple.

Body:
If I'm understanding correctly, you have an Entity, which can do things (like walk, talk, and so on), and want to use classes to be able to provide this entity with AI behaviours. These will be triggered in some loop (or by schedule, or whatever) and will then cause some behaviour in the entity (walking, talking, etc.).

There's a few you're going to need two things:

An interface for AI actions, allowing them to be triggered

A way for the AI action to actually effect the change in behaviour

For the first one, you have your interface IAiAction. Let's look at how it's used:

foreach (IAiAction action in AiActions)
    action.Update(this);

So from this, it seems like actually, the only member on IAiAction should be:

void Update(Entity entity);

This also relieves you of needing IAiProperty at all. WanderDistance, for example, can just be a normal, private member on WanderAction.

Looking at this interface, there also doesn't seem to be anything AI-specific about it. It could work just as well for user-controlled actions, or actions so dumb they can't really be called AI (like waiting in place forever). Why not just IAction, or IInstructor or something?

It may be that as you implement more of these AI classes, you do find common structure. You could pull that out into a dependency or base class. But there's no need to pre-emptively impose structure, and certainly no need to expose it publicly. Just expose what consumers actually need. As an example, maybe you were considering using LastUpdated so that the Entity could only call actions that have been updated more than a second ago, or whatever. But why not keep LastUpdated private, and let the actions can make that decision themselves?

As for the second bullet point, it'd be tough to try to have some general way for the AI action to return an instruction for the Entity to understand. Instead, Entity should expose what it can do through methods on an interface:

void SetDestination(Vector2D destination){ /*...*/ }
void Say(string utterance) { /*...*/ }

Now an AI action can call methods, instead of having to return something and assume the Entity will have the logic to handle it. You could, for example easily add a ReactToDangerAction which both yells and runs away from the danger, given the above two methods.

This is a starting point, but one design improvement which may go a long way is to not pass the Entity in to the Update method, but instead pass it in through the constructor. After all, it doesn't make sense for your example WanderAction to be shared by two different entities, as they'd probably have different homes. So it might as well be tied to one particular entity permanently, rather than accepting one each time the method is called and hoping it always gets the same one. This would probably require a little boilerplate (factory classes, possibly), but would enable some design improvements.

For example, you could adhere better to the Interface Segregation Principle by splitting the Entity's interface into several (IDirectable, IVocal, etc.). Or, if you don't like the idea of Entity exposing methods allowing it to be ordered around by all and sundry, you could even make the SetDestination and Say methods private and pass them into the actions' constructors as delegates. It would also give flexibility if in the future you found that some actions shouldn't be tied to particular entities, or should be tied to multiple.


问:
Why List<E> interface is additionally introduced in collection hierarchy?
Below is the diagram, where, if we just consider the implementations of List,

AbstractList maintains the core behavior of list. To introduce the new implementation class MyList(say) one can inherit AbstractList and override(if necessary) required methods. By extending AbstractList. Additionally, class MyList is obeying the contract to behave like a list.

```<code>class MyList extends AbstractList{..}
</code>```

Users can use collection hierarchy, as,

```<code>AbstractList l = new ArrayList<String>();
l.add("one"); //execute ArrayList's add method
</code>```

A class can also maintain composition relation with any list implementation(at runtime), by having

```<code>AbstractList l;
</code>```

as member, that gets populated at runtime, with any list implementation.

So,

I would like to understand the clear reason, Why additionally interface List<E> is introduced?

note1: Intention is to understand, how to use interface. This not a duplicate question, because both abstract class and interface are used.I did not use the word 'instead of' or 'rather'

note2: Let us not get into java-8 default methods, as above collection hierarchy was designed with whatever was provided till java-7

答:
In both of your code snippets, the use of AbstractList is discouraged.1  The correct usage is to put the new instance of list in a List variable.

The abstract classes AbstractList and AbstractSequentialList are provided for the convenience of implementers (i.e. library writers) of list-like containers, by providing default implementations(*) for some of the instance methods, in an effort to reduce code duplication.

(*)There is an ongoing, legitimate debate on what are the (i) preferred-, (ii) tolerable- and (iii) discouraged-ways of providing default implementations of instance methods in the Java language. Please see some of the other questions asked by overexchange for a starting point.

Every list-like container must implement the List interface directly or indirectly, for them to be usable by other applications in a list-like manner. Inheritance from AbstractList or AbstractSequentialList is optional.

Likewise, applications that would like to accept a list-like container should accept a List. It should not require an AbstractList or AbstractSequentialList because it would disqualify some list-like containers.

As to the motivation for naming the interface List as is, it is likely2 the decision of some influential Java founding fathers that decided that interfaces shall not have any naming decorations that indicate they are interfaces (i.e. not backed by any concrete implementations). That position is debatable but it will stay with the Java language forever.

1 "discouraged" is used as an euphemism for "plainly wrong."

2 Citation needed. Feel free to edit this post to add the necessary reference, or to remove this paragraph if this is incorrect.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
I know i said i wouldnt make a post but i'll write one answer. As much as everyone else says no there are no evils i'll say yes there are some absolute evils

Setjmp/LongJmp is pure evil.

ContentLicense: CC BY-SA 2.5

Title: Is anything in programming truly evil?


问:
Polyglot Node.js with Typesafe Akka for Actor Model
I have a case that needs to manipulate a large stream of JSON and inject it into Apache HBase. Our system works on Node.js with Mongo then, since we need to enhance performance, so HBase is choosen to handle the big data things.

To enhance my system scalability, I prefer using the Actor Model by Akka for messaging instead of using any other messaging system. It's because Actor Model that Akka provides gives me any advantages about fail safe, Actor management, and other features that's very helpful to make my job easy. But it still in JVM layer that directly injecting and consuming data from HBase.

I want my Node.js apps also works under Akka system maybe using node-java. Is it good practice? If it's not, is there any solution that Node.js can communicate with Akka?

ps. my question here is about how to work with Akka and Node.js, not arguing about "why choose to use Node.js when JVM has really fast JSON manipulating library", because our system are already benchmarked and Node.js was the chosen one to handle JSON manipulation. Also it's already at production stage, so migration totally from Node.js to full Scala is not our priority today.

答:
I don't buy the argument that the JVM is not as good to manipulate JSON than Node.
The JVM is filled with a lot of really fast JSON parsers, Jackson being one of them. As a bonus it handles streaming json as well. Look at the project before making an opinion.
Your problem is fairly common, you want to connect to a firehose of social data, via an actor, pass the entity to another actor to validate or modify to your desired kind of Json, then pass it to another actor to persist to your data store.
You might use some queues (LinkedBlockingQueues, etc) in the middle if needed.
In the validating and parsing actor, just Jackson or the Json4s project (https://github.com/json4s/json4s) to enrich or modify your JSON. The rest is fairly standard.</p>


答:
I would like to understand the clear reason, Why additionally interface List is introduced?

In Java, types form a directed acyclic graph, but classes form a tree. As such, types are strictly more flexible than classes. When designing APIs, you should prefer uses non-class types as much as possible for your parameters and your return types. And pretty much your only choice in Java for a non-class type is an interface.

In other words, interfaces are nicer for users of your types.

However (at least prior to Java 8), if you actually want these types to have an implementation, you need a (possibly abstract) class. So classes are nicer for implementors of your types.

In order to satisfy both users and implementors, the designers of the List API provided both a List interface and an AbstractList abstract class.

Funnily enough, today with Java 8, interfaces can have so called "default implementations", thus removing the need for the AbstractList abstract class. So your question should be phrased the other way: "Why was the additional abstract class AbstractList introduced?" and the answer would have been "due to historical reasons, old Javas did not have default methods."

Title: Why List<E> interface is additionally introduced in collection hierarchy?

Body:
Below is the diagram, where, if we just consider the implementations of List,

AbstractList maintains the core behavior of list. To introduce the new implementation class MyList(say) one can inherit AbstractList and override(if necessary) required methods. By extending AbstractList. Additionally, class MyList is obeying the contract to behave like a list.

```<code>class MyList extends AbstractList{..}
</code>```

Users can use collection hierarchy, as,

```<code>AbstractList l = new ArrayList<String>();
l.add("one"); //execute ArrayList's add method
</code>```

A class can also maintain composition relation with any list implementation(at runtime), by having

```<code>AbstractList l;
</code>```

as member, that gets populated at runtime, with any list implementation.

So,

I would like to understand the clear reason, Why additionally interface List<E> is introduced?

note1: Intention is to understand, how to use interface. This not a duplicate question, because both abstract class and interface are used.I did not use the word 'instead of' or 'rather'

note2: Let us not get into java-8 default methods, as above collection hierarchy was designed with whatever was provided till java-7


问:
TEA algorithm constant 0x9e3779b9 said to be derived from golden ratio, but the golden number is 1.618?
I'm trying to understand a constant 0x9e3779b9.

What kind of data is this? It's not binary, not decimal, what is this?

It's a constant used on the TEA algorithm.
It says it's derived from the golden number,
but the golden number is 1.618?

答:
The number comes from the hexadecimal representation of the golden ratio.

Just like 1/4 is 0.25 (25/100) in decimal is 0.4 (4/16) in hex, the fractional portion of the golden ratio has a different representation in hex than in decimal.

You are not dividing 0x9e3779b9 by 10^8, but 16^8 (or 2/32), and 0x9e3779b9/0x100000000 = 2654435769/4294967296 ≈ 0.6180339886


问:
DTOs vs Domain Models and invoking Command Handlers directly
I was just hoping someone might be able to answer a few questions I have regarding the proper design of DTOs and Domain Models. I'm currently working on a project which involves leveraging a SOAP API.

Since we're working with SOAP we have the added benefit of generating a number of objects (DTOs) using the provided WSDL file. I've also subsequently built a number of commands which are allowing us to better encapsulate the intent of each request and simplify our interface to the API.

Each command handler has an associated "command" object which stores all of the necessary data to complete the request successfully.

I actually have three questions regarding this approach:

1) Is it unusual to call command handlers directly, thereby replacing the Command Bus as our invoker. Obviously we would lose the ability (at least in these select instances) to pass our commands into a queuing application which would allow us to execute the command in a non-sequential order.

However, I have identified some cases where we would actually need to parse the API response data on runtime. Could this be construed as a potential issue in the design of our application?

2) We're currently performing validation on the request data before passing it into our immutable command objects. However, there may be some cases where we need parse data from the DB/CLI prior to initializing our commands.

As a result, I've considered placing our validation logic into the command objects themselves. If validation fails then a exception might be thrown. Does this seem like a reasonable approach or am I again violating some design principles?

3) This may sound foolish but what exactly is the difference between a Domain Object and a DTO. I've heard the command objects themselves being referred to as a DTO yet they appear to belong to the domain layer (unless I'm mistaken).

Could the command object be more accurately described as a DTO or a Domain Model?

Thanks again.
I do appreciate the feedback.

答:
I'm not very experienced in these terms exactly but I've done a lot of serialization with really complex data types with all kinds of weird dependencies, so here's my 2 cents on managing your POCOs(TLDR; keep them POCO).

I have identified some cases where we would actually need to parse the
  API response data on runtime. Could this be construed as a potential
  issue in the design of our application?

Yes, You should be done with processing all the data you get as soon as you can. Otherwise you may end up with a lot of spaghetti code in all the layers of your application doing de/serialization 'on-demand'

I've considered placing our validation logic into the command objects
  themselves. If validation fails then a exception might be thrown. Does
  this seem like a reasonable approach or am I again violating some
  design principles?

Yes, some validation may require data from other objects, some may require time, some results of expensive algorithms used for validation may be needed to accessed multiple times. You may need to do something if the validation fails that may include telling the web server that the validation failed. for that You either have to use some delegates or events or do it right there. both mean calling the the network library, not pretty and of course creating other DTOs in a DTO, all kinds of spaghetti there.


问:
Is overriding Object.finalize() really bad?
The main two arguments against overriding Object.finalize() is that:

You don't get to decide when it's called.

It may not get called at all.

If I understand this correctly, I don't think those are good enough reasons to hate Object.finalize() so much.

It is up to the VM implementation and the GC to determine when the right time to deallocate an object is, not the developer. Why is it important to decide when Object.finalize() gets called?

Normally, and correct me if I'm wrong, the only time Object.finalize() wouldn't get called is when the application got terminated before the GC got a chance to run. However, the object got deallocated anyway when the application's process got terminated with it. So Object.finalize() didn't get called because it was not needed to be called. Why would the developer care?

Every time I'm using objects that I have to manually close (like file handles and connections), I get very frustrated. I have to be constantly checking if an object has an implementation of close(), and I'm sure I have missed a few calls to it at some points in the past. Why isn't it just simpler and safer to just leave it to the VM and GC to dispose of these objects by putting the close() implementation in Object.finalize()?

答:
In addition to why leaving it to the finalizer to release resources is generally a bad idea, finalizeable objects come with performance overhead.

From Java theory and practice: Garbage collection and performance (Brian Goetz), Finalizers are not your friend:

Objects with finalizers (those that have a non-trivial finalize() method) have significant overhead compared to objects without finalizers, and should be used sparingly. Finalizeable objects are both slower to allocate and slower to collect. At allocation time, the JVM must register any finalizeable objects with the garbage collector, and (at least in the HotSpot JVM implementation) finalizeable objects must follow a slower allocation path than most other objects. Similarly, finalizeable objects are slower to collect, too. It takes at least two garbage collection cycles (in the best case) before a finalizeable object can be reclaimed, and the garbage collector has to do extra work to invoke the finalizer. The result is more time spent allocating and collecting objects and more pressure on the garbage collector, because the memory used by unreachable finalizeable objects is retained longer. Combine that with the fact that finalizers are not guaranteed to run in any predictable timeframe, or even at all, and you can see that there are relatively few situations for which finalization is the right tool to use.


问:
Where should PDOExceptions be dealt with?
I wrote a database wrapper class to help with queries and I'm trying to figure the best way to implement try-catch blocks.

In my database class, I have a helper function;

```<code>public function fetchAll($sql, $bind = array()) {

        $stmt = $this->query($sql, $bind);
        $result = $stmt->fetchAll($this->_fetch_mode);

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

that I can call outside of the class:

```<code>$this->db->fetchAll($sql,[$var1,$var2]);
</code>```

My question is where to put the try-catch blocks.  It would be "easier" if I just put them inside of my database class:

```<code>    public function fetchAll($sql, $bind = array()) {

            $stmt = $this->query($sql, $bind);
            try {
                  $result = $stmt->fetchAll($this->_fetch_mode);
                } catch (PDOException $e) {
                   //log the error...give some message
                }

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

instead of wrapping each call to the database class:

```<code>try {
     $this->db->fetchAll($sql,[$var1,$var2]);
    } (catch PDOException $e) {
     //log the error...give some message
    }
</code>```

However, my feeling (without being able to come up with a concrete example...) is that even though it would be more work to wrap each call to the database class, if I do hard code the try-catch block in my database class, it won't be as flexible in terms of handling errors.

Or, would it be better to have a "catch-all" in my index.php (I use MVC) to catch general exceptions (for example, PDO related), and then if I need more specific ones in my application (for example, those thrown when connecting to 3rd party services), then add additional try-block catches for them:

In my index.php, which all requests pass through via my .htaccess file:

```<code>try {
    $db = new Db();
    $db->connect(['host'=>DB_HOST,'dbname'=>DB_NAME,'username'=>DB_USERNAME,'password'=>DB_PASSWORD]);

    $bootstrap = new Bootstrap();

    $bootstrap->setControllerPath('application/controllers');
    $bootstrap->setModelPath('application/models');

    $bootstrap->init(); //load the controller/model/classes
} (catch Exception $e) {
    //log error
    //if ajax request return json_encoded message other redirect to error page
}
</code>```

答:
The answer depends on the responsibilities of your wrapping class. If all it does is encapsulate your connection settings for convenience, then simply letting PDOException pass through is preferable. If your wrapper has more responsibilities such as encapsulating certain queries or connection pooling, you may want to develop an exception or two for this wrapper, which in turn wrap PDOException to help you be sure about where the error originated.

A good rule of thumb to help answer the question, "where should exceptions be caught," would be to catch them as soon as the application can move on from it.

Suppose a method in class A needs an integer value and calls a method in class B which in turn expects an array from a method in the db wrapper. If returning an empty value from the db wrapper (like array()) allows the application to continue sensibly with degraded results, then catching in B is OK. But if the empty array is an expected value, letting the exception bubble up the call stack to A is reasonable. Be sure to stop as soon as you reach a frame where you can move on from the failure. In a well-designed application, this shouldn't be more than 2 frames.

Catching exceptions at the soonest possible point yields problems communicating the failure to the caller, when the exception can do exactly that. For example, if a method returns data from a nullable integer column from a database, you have no reasonable return value to flag an error. But the exception will always clearly indicate the failure.

Or, would it be better to have a "catch-all" in my index.php

In general, you should have one of those to ensure that you have control of otherwise unhandled exceptions and to ensure that you do things like logging and properly releasing resources you've acquired. Avoid them elsewhere in your application to ensure you aren't swallowing information vital to explaining how your application is behaving.


问:
Is the Entity Component System architecture object oriented by definition?
Is the Entity Component System architecture object oriented, by definition?  It seems more procedural or functional to me.  My opinion is that it doesn't prevent you from implementing it in an OO language, but it would not be idiomatic to do so in a staunchly OO way.

It seems like ECS separates data (E & C) from behavior (S). As evidence:

The idea is to have no game methods embedded in the entity.

And:

The component consists of a minimal set of data needed for a specific purpose

Systems are single purpose functions that take a set of entities which have a specific component

I think this is not object oriented because a big part of being object oriented is combining your data and behavior together.  As evidence:

In contrast, the object-oriented approach encourages the programmer to place data where it is not directly accessible by the rest of the program. Instead, the data is accessed by calling specially written functions, commonly called methods, which are bundled in with the data.

ECS, on the other hand, seems to be all about separating your data from your behavior.

答:
Data-Oriented Entity Component Systems can coexist with Object-Oriented Paradigms:
- Component Systems lend themselves to polymorphism.
- Components can be both POD (plain old data) and ALSO Objects (with a Class and Methods), and the whole thing is still 'data oriented', provided that Component Class Methods only manipulate data owned by the local object.

If you choose this path, I recommend that you avoid using Virtual Methods, because if you have them, your component is no longer purely component data, plus those methods cost more to call - this is not COM. Keep your component classes clean of any references to external anything, as a rule.

Example would be vec2 or vec3, a data container with some methods to touch that data, and nothing more.

ContentLicense: CC BY-SA 4.0


问:
How definite of an order is there to a depth-first search of a graph?
I have the following graph that I need to simulate a depth-first search of; starting at g:

My question is: How definite of an order is there when performing a depth-first search? When doing a DFS of a tree, I always see the left-most child searched first (completely), then after backtracking, the second-most-left child...

But with a graph, "left" seems a lot more arbitrary.

For the above graph, I got the following order:

```<code>g, j, i, m, n, o, k, h, p, l, e, a, f, c, b, d
</code>```

But along the way, I found that there were many other possible paths to take. I'm guessing when implementing a DPS, I would visit the vertices in the order that they appear in the adjacency list (providing I'm using an adjacency list), but I don't have such information here.

Am I right that there are many possible answers to this question? And is my trace of the DPS correct?

答: If your graph is a spatial one, look toward Z-Filling algorithms, and depending on your intent, Marching algorithms to direct your tree walk toward a particular goal or interest region.</p>


问:
Looking for a specific programming paradigm
I am searching for programming languages with a certain paradigm, or the name of the paradigm which works like follows:

You start with writing the source code of a program or something more like a script.

This is then executed by the "compiler" (interpreted or just in time compiled) and produces a actual executable.

You run the produced machine code.

So the compiler does not only translate source code to machine code but also provides a runtime environment while doing so. The code is executed by the compiler at one, with no user interaction, just the source code as input (no Read–eval–print loop, console or such things).

For example, C++ (11/14/17) then to go in this direction with things like recursive templates and constexpr, where entire functions can be executed at compile time (not runtime). But I imagine it even more generic and allowing for reflection (like Smalltalk, where everything is an object). It could help to reduce redundancy of the source code and allow more abstraction.

Code example:

```<code>const char* names[] = { "a", "b", "c", ... };
template<int size>
struct S {
    assert(size < sizeof(names)/sizeof(void*));
    for(int i = 0; i < size; ++i)
        this.add_field(Type::float, names[i]);
}
</code>```

This can not be done in C/C++, D has a bit more features like static ifs ans so on, but no language I know actually supports this.

Is there a name for this paradigm and are there languages which are heavily based on it?

答:
From what you describe, it sounds like you are looking for a potent preprocessor to generate the code that is subsequently compiled. Preprocessors are, of course, almost as old as computer languages themselves, however, most are really limited in extend and syntactic capabilities. Afaik, there are basically two kinds of preprocessors:

Non-turing complete preprocessors that provide little more than header inclusion and/or conditional compilation. These are not what you need.

Turing complete preprocessors. You can do any computation in these, however, their syntax generally sucks just as much as the syntax of the non-turing complete ones.

I know of two such preprocessors:

m4

C++ templates. Though not exactly a preprocessor (they work somewhere in the middle of the parse rather than doing string transformations on the input text), they are quite often abused to do complex calculations at compile time.

m4 has the advantage of allowing you to inspect the resulting code. That makes m4 generated programs easier to debug than template generated programs. But, as I said, the syntax sucks in both cases, so you can't write complex preprocessor programs and expect your code to remain readable.

For complex preprocessing tasks, I would look at a real interpreted language like python or ruby to generate the source code. Doing code generation in such a language feels a bit clumsy because you have to explicitly write the resulting code to a file, but readability is significantly higher than either m4 or C++ templates.


问:
Advantages of these recommendations in ooprogramming using Java
Below are the recommendation from section 5.1 of this essay.

While Java is not a pure object-oriented language, it is possible to program in a pure object-oriented style by obeying the following rules:

1) Classes only as constructors A class name may only be used after the keyword new.

2) No primitive equality The program must not use primitive equality (==). Primitive equality exposes representation and prevents simulation of one object by another.

3) In particular, classes may not be used as types to declare members, method arguments or return values. Only interfaces may be used as types. Also, classes may not be used in casts or to test with instanceof.

This is generally considered good object-oriented style

For instance,

below part of jdk code does not follow third point mentioned above:

return type of toArray method.

```<code>public Object[] toArray() {
     //whatever
   }
</code>```

in java.util.AbstractCollection.

or

return type of toString() nethod.

```<code>public String toString() {
        //whatever
    }
</code>```

below part of jdk code does follow third point above:

```<code>public Iterator<E> iterator() {
        return new Itr();
    }
</code>```

What advantages do we find in following these recommendation? Can some design patterns be pulled in(automatically), by following such recommendations?

答:
What you gain by following his recommendations is the ability to accept any object regardless of implementation as long as it implements an interface correctly. There's nothing special about this and it's a commonly-used technique. As the paper points out, what you lose is:

The ability to restrict variables to a specific class, which matters when correctness is important. For example, if Java's SecurityManager accepted the CharSequence interface instead of the String class, you could subvert its security checks by passing in a mutable string.

The ability for methods to look at the implementation details of two objects. For instance the Set interface can't have a reasonable set union method because there's no guarantee two Sets have the same implementation. The only way to calculate the union of two Sets is the naive, inefficient way - iterate through both of them.


问:
Focus of unit tests on code
I discover mocking strategies after 50% of tests was writen, and I'm confused about how much focus unit tests should have, for example on class method. I know that for external dependencies you should mock those but what if we call some other method in the same class. Would this considered to be dependency? ... Because we want to test correctness only the method that we are testing... right? But where unit test focus ends?

Unit test should test in OOP the smalest block of code... and 2 tests should not be dependant. So if the smallest block of code is class method, the unit test should test 1 class method only. But if someone modify one method and test for that method fails, it will fails all other method in class that depends on it. So in order to make test truly independant i should mock dependants method?

My thinking before writing my first test was that unit test is testing smallest group of code like class method or function and make assertions obout it's side effects... What are your thoughts about this and what should be best practice.

答:
Perhaps you could rephrase your question to:
What exactly is a unit in unit testing.

I think it is commonly agreed upon, that, if you are doing OOP, a class holds for a unit. But there is no formal definition of that. You could do unit-tests with whole subsystems, mainly testing the glue code, but indirectly all of the dependencies together.

There is a nice article by Martin Fowler on the "problem" of a unit.

I know that for external dependencies you should mock those but what if we call some other method in the same class

Mostly you define an object under test, say a customerservice.
This customerservice is called from another object. This behaviour trigger your tests. The customerservice makes calls to the customerrepository. These calls are perfect candidates for mocking.

You are testing the customerservice and want reliable answers to it`s behaviour. From this it should be clear, that it makes no sense, somehow to mock calls on yor object under test. If you have to make a call to another function of the same service, that is part of the test.

Would this considered to be dependency?

Not in the common sense of dependencies meaning external dependencies.

But where unit test focus ends?

By the borders of the unit you test. In the example given all methods of the unit called customerservice.

Title: Focus of unit tests on code


问:
When should you avoid iterative and incremental development?
I'm currently reading some literature about software development process models. Everywhere I look, I only read the problems with the Waterfall model and how the iterative and incremental development approach solves these problems. But, I cannot find any information about when you should avoid this approach.

So, for what kind of projects should you better avoid iterative and incremental development?

答:
The need for iterative and incremental development on most software projects comes from the fact that those projects' requirements are in constant flux, and the fact that quickly delivering a prototype then iterating on it seems to produce better results than trying to produce a comprehensive specification before starting development.

The only situation I can think of where this would arguably not apply is one in which implementing the project is easy, but designing it is hard, and once designed it cannot be easily changed. For example, a new programming language, or the embedded software for some physical device, or the device itself (though that's not software anymore). In these cases, getting it right on the first release might be far more important than the ability to release at any moment or respond to change quickly after release.

Of course, there are no absolutes. To go with my programming language example, Clojure was famously designed over the course of two and a half years by just one guy before he released anything to the public. On the flip side, Rust has had many alpha versions that broke core functionality before settling on a stable 1.0 release. I've heard good things about both languages.

Generally speaking, the harder it is to change things after release, the more you want to rely on upfront design and testing rather than prototypes and future iterations. But personally, I would never avoid iterative development; I would at most begrudgingly accept its impracticality.


答:
My humble opinion is that this kind of bold statements can be wrong,  boldly.

Will not be possible to use a static class. And won't allow some ways of creating a singleton for instance.

Sometimes it is useful and helps the algorithm. But read this post  it will help you make up your own decision. http://cubussapiens.hu/2012/05/java-primitive-type-comparison-a-wat-look/

Classes are ok in a lot cases. Interfaces are good if you think you will be replacing the implementation of a class and also interfaces allow you to do dependency injection which helps unit testing. So I don't agree with 3 either.

Title: Advantages of these recommendations in ooprogramming using Java

Body:
Below are the recommendation from section 5.1 of this essay.

While Java is not a pure object-oriented language, it is possible to program in a pure object-oriented style by obeying the following rules:

1) Classes only as constructors A class name may only be used after the keyword new.

2) No primitive equality The program must not use primitive equality (==). Primitive equality exposes representation and prevents simulation of one object by another.

3) In particular, classes may not be used as types to declare members, method arguments or return values. Only interfaces may be used as types. Also, classes may not be used in casts or to test with instanceof.

This is generally considered good object-oriented style

For instance,

below part of jdk code does not follow third point mentioned above:

return type of toArray method.

```<code>public Object[] toArray() {
     //whatever
   }
</code>```

in java.util.AbstractCollection.

or

return type of toString() nethod.

```<code>public String toString() {
        //whatever
    }
</code>```

below part of jdk code does follow third point above:

```<code>public Iterator<E> iterator() {
        return new Itr();
    }
</code>```

What advantages do we find in following these recommendation? Can some design patterns be pulled in(automatically), by following such recommendations?


问:
What does it mean for an algorithm to converge?
I keep coming across this term when reading about reinforcement learning, for example in this sentence:

If the problem is modelled with care, some Reinforcement Learning algorithms can converge to the global optimum

(source)

or here:

For any fixed policy Pi, the TD algorithm described above has been proved to converge to VPi

(source)

My understanding of the word converge is that it means several things coming together to the same point, but how can a single thing (the algorithm) do that?

答:
An iterative algorithm is said to converge when, as the iterations proceed, the output gets closer and closer to some specific value. More precisely, no matter how small an error range you choose, if you continue long enough the function will eventually stay within that error range around the final value.

In some circumstances, an algorithm will not converge, having an output that always varies by some amount. It could even diverge, where its output will undergo larger and larger value swings, never approaching a useful result. More precisely, no matter how long you continue, the function value will never settle down within a range of any "final" value.

The "converge to a global optimum" phrase in your first sentence is a reference to algorithms which may converge, but not to the "optimal" value (e.g. a hill-climbing algorithm which, depending on the function and initial conditions, may converge to a local maximum, never reaching the global maximum).


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
That would be nice to have the possibility to set the primitive type (bool|boolean, int|integer, float, double, string, object) of a parameter in a method as array is allowed.

Example:

current:

```<code>class HttpResponse {
public function __construct($version, $statuscode = HttpStatus::OK, HttpResponseHeaders $headers = array(), $body = '');
</code>```

}

hope:

```<code>class HttpResponse { public function __construct($version, integer $statuscode = HttpStatus::OK, HttpResponseHeaders $headers = array(), string $body = ''); }
</code>```

I thought also to have an Assert static class that can be useful.

Body:
That would be nice to have the possibility to set the primitive type (bool|boolean, int|integer, float, double, string, object) of a parameter in a method as array is allowed.

Example:

current:

class HttpResponse {
public function __construct($version, $statuscode = HttpStatus::OK, HttpResponseHeaders $headers = array(), $body = '');

}

hope:

class HttpResponse { public function __construct($version, integer $statuscode = HttpStatus::OK, HttpResponseHeaders $headers = array(), string $body = ''); }

I thought also to have an Assert static class that can be useful.


问:
Connection between futures and exceptions?
Is there a connection between futures and exceptions? async-await looks very similar to throw-catch.

答:
Yes, in some implementations of futures: in both cases the (single) thread of execution moves up the call stack on await/throw, and both can be seen as a form of
condition, as in the Common Lisp Condition System, and async on a function definition is analogous to throws, specifying the kind of condition it may signal.

However, the closer analogy is that await in an asynchronous function (a kind of promise) is like yield in a generator function, since in both cases it only returns one level up the call stack (rather than automatically propagating), and in both cases the function is resumable, and logically a coroutine.

The key difference between futures and exceptions execution-wise is that typically futures are implemented by resumable conditions, while exceptions are non-resumable conditions.

Concretely, the throw in an exception unwinds the call stack up to the catch (*). After that you can retry from the catch, but not from the throw: you can't resume where it left off.

(*) Implementations differ: often the unwinding only happens if it is caught: uncaught exceptions in C++ don't unwind the stack.

By contrast, the (asynchronous) function that computes a future behaves as a coroutine, like a single-element generator. When you use await it is suspended (like when using yield in a generator), and then it resumes where it left off when it is reactivated. Implementation-wise, the current execution context is saved as a continuation, which is invoked when the promise is reactivated. From the perspective of OOP, the continuation inside promise/generator is an instance of the underlying function. It is possible to implement futures using generators (or coroutines), but it's awkward: calling a single function asynchronously is common, so language support is warranted to make this simple.

More precisely, in the .NET (C#, Visual Basic) implementation of futures (Task), now also used in Dart and to come in JavaScript, when you use await in an async function, it immediately (*) returns a future, just like throw immediately throws an exception. However, a crucial difference is that exceptions automatically propagate (up the call stack) until they hit a catch, while futures only return one level (to the caller). There is no need for a catch with futures, since they only return one level, and await is rather "suspend current function (yield to caller), return future, then resume current function and get value of future when yielded back to". This is complex to state but easy to reason about: the flow is like yield in a generator, with the wrapping in a future (for caller) and then unwrapping a future (from awaited callee).

A function that calls an async function (and receives a future) must either synchronously wait on the future or return the future (in which case it is itself synchronous), or itself be async, in which case there must be a chain of await statements up the call stack, ending in a sync function (since the program as a whole is synchronous, suspended by the OS if it blocks), most commonly the event handler. This allows cooperative multi-tasking, as with other uses of coroutines.

(*) In .NET, await does not suspend if the future value is already available, which is more efficient, while in Dart it always suspends, which is more predictable.

This manual propagation of asynchronicity is in contrast to the automatic propagation of exceptions, and is a very, very good design choice: execution is sequential except where there is an explicit await, which marks where execution is suspended, and makes the interleaving of execution explicit. Contrast with exceptions, where an exception can be thrown at any time, and is not visible at the call site.

In some other implementations futures are implicit: they look just like a normal value of the underlying type, and using the value automatically causes await. This is more elegant at use but makes flow of execution much less clear, because it's not clear when evaluation actually occurs and where it is deferred: using await (resp., returning a future) make these explicit.

In other models, futures are computed by creating a new thread (hence executed in an indeterminate concurrent order, often in parallel), or lazily only when the value is used; neither of these is similar to exceptions.

Lastly, using await on a future may throw an exception, which was thrown (then suspended) by the promise, but this is just due to using exceptions for error-handling, and is otherwise unrelated: it could just as easily return a pair (value, err) as in Go. For example in C#:

```<code>Task task = fAsync(); // No try-catch here, as exception is caught by future.
try
{
    await task; // fAsync may throw an exception, which is caught by future, then rethrown by await.
}
catch (SomeException e)
{
    // Handle exception.
}
</code>```

See also:

Does async/await solve a real problem?, for an interesting discussion in the context of JavaScript.

Body:
Yes, in some implementations of futures: in both cases the (single) thread of execution moves up the call stack on await/throw, and both can be seen as a form of
condition, as in the Common Lisp Condition System, and async on a function definition is analogous to throws, specifying the kind of condition it may signal.

However, the closer analogy is that await in an asynchronous function (a kind of promise) is like yield in a generator function, since in both cases it only returns one level up the call stack (rather than automatically propagating), and in both cases the function is resumable, and logically a coroutine.

The key difference between futures and exceptions execution-wise is that typically futures are implemented by resumable conditions, while exceptions are non-resumable conditions.

Concretely, the throw in an exception unwinds the call stack up to the catch (*). After that you can retry from the catch, but not from the throw: you can't resume where it left off.

(*) Implementations differ: often the unwinding only happens if it is caught: uncaught exceptions in C++ don't unwind the stack.

By contrast, the (asynchronous) function that computes a future behaves as a coroutine, like a single-element generator. When you use await it is suspended (like when using yield in a generator), and then it resumes where it left off when it is reactivated. Implementation-wise, the current execution context is saved as a continuation, which is invoked when the promise is reactivated. From the perspective of OOP, the continuation inside promise/generator is an instance of the underlying function. It is possible to implement futures using generators (or coroutines), but it's awkward: calling a single function asynchronously is common, so language support is warranted to make this simple.

More precisely, in the .NET (C#, Visual Basic) implementation of futures (Task), now also used in Dart and to come in JavaScript, when you use await in an async function, it immediately (*) returns a future, just like throw immediately throws an exception. However, a crucial difference is that exceptions automatically propagate (up the call stack) until they hit a catch, while futures only return one level (to the caller). There is no need for a catch with futures, since they only return one level, and await is rather "suspend current function (yield to caller), return future, then resume current function and get value of future when yielded back to". This is complex to state but easy to reason about: the flow is like yield in a generator, with the wrapping in a future (for caller) and then unwrapping a future (from awaited callee).

A function that calls an async function (and receives a future) must either synchronously wait on the future or return the future (in which case it is itself synchronous), or itself be async, in which case there must be a chain of await statements up the call stack, ending in a sync function (since the program as a whole is synchronous, suspended by the OS if it blocks), most commonly the event handler. This allows cooperative multi-tasking, as with other uses of coroutines.

(*) In .NET, await does not suspend if the future value is already available, which is more efficient, while in Dart it always suspends, which is more predictable.

This manual propagation of asynchronicity is in contrast to the automatic propagation of exceptions, and is a very, very good design choice: execution is sequential except where there is an explicit await, which marks where execution is suspended, and makes the interleaving of execution explicit. Contrast with exceptions, where an exception can be thrown at any time, and is not visible at the call site.

In some other implementations futures are implicit: they look just like a normal value of the underlying type, and using the value automatically causes await. This is more elegant at use but makes flow of execution much less clear, because it's not clear when evaluation actually occurs and where it is deferred: using await (resp., returning a future) make these explicit.

In other models, futures are computed by creating a new thread (hence executed in an indeterminate concurrent order, often in parallel), or lazily only when the value is used; neither of these is similar to exceptions.

Lastly, using await on a future may throw an exception, which was thrown (then suspended) by the promise, but this is just due to using exceptions for error-handling, and is otherwise unrelated: it could just as easily return a pair (value, err) as in Go. For example in C#:

Task task = fAsync(); // No try-catch here, as exception is caught by future.
try
{
    await task; // fAsync may throw an exception, which is caught by future, then rethrown by await.
}
catch (SomeException e)
{
    // Handle exception.
}

See also:

Does async/await solve a real problem?, for an interesting discussion in the context of JavaScript.


问:
Why isn't the isa pointer hardwired in Objective-C classes?
I've been studying the Objective-C runtime for some years, and even hacked libobjc a little bit (both Apple's and GNUStep's), and I've been wondering about a design decision on the compilers.

Every Objective-C object is expected to have its size at least of sizeof(Class), having its first field being Class isa, as seem in struct objc_object. We see it's explictly declared in root classes like NSObject and old defunct Object. We also know that the runtime adds the pointer to the new objects when they are created by class_createInstance() (see code example below).

So, my question is: then why isn't the isa pointer automatically prepended to the class declarations? Why does it need them to declare it explictly even if that is error-prone?

Example with bad code:

```<code>#import <stdlib.h>
#import <stdio.h>
#import <objc/runtime.h>

@interface Foo {
  @public
  int x;
};
- (void)bar;
@end

@implementation Foo
- (void)bar {
  printf("bar\n");
};
@end

int main() {

  Class cls = objc_getClass("Foo");
  printf("cls = %p\n", cls);

  // Returns sizeof(int)
  printf("cls size = %ld\n", class_getInstanceSize(cls));

  Foo *obj = class_createInstance(cls, 0);
  printf("obj = %p\n", obj);

  // Are we saving isa?
  printf("hmm: %d\n", *((Class *)obj) == cls);

  // We are! This works ;)
  [obj bar];

  // Evil code
  obj->x = 10;

  // Did we do something wrong?
  printf("hmm: %d\n", *((Class *)obj) == cls);

  // Yeah, we did! Segfault here!
  [obj aaa];

  return EXIT_SUCCESS;
};
</code>```

答:
It's an implementation detail of the Apple/GNUstep/OpenStep Objective-C runtime. libobjc is the Apple Objective-C runtime, and Cocoa/GNUstep classes like NSObject are tied to that Objective-C runtime.

Objective-C (originally) just adds a minimal layer of syntax on top of C, and there's no reason, from a pure Objective-C language point of view, that objects need to be laid out any particular way.

You could theoretically write your own Objective-C runtime that lay out objects and do other stuff differently, and then you write your own Objective-C framework, with your own root classes to work with that runtime.


答:
NIM http://nim-lang.org/docs/tut1.html

Provides arbitrary compile-time calculations with whole feature set of runtime.

Title: Looking for a specific programming paradigm

Body:
I am searching for programming languages with a certain paradigm, or the name of the paradigm which works like follows:

You start with writing the source code of a program or something more like a script.

This is then executed by the "compiler" (interpreted or just in time compiled) and produces a actual executable.

You run the produced machine code.

So the compiler does not only translate source code to machine code but also provides a runtime environment while doing so. The code is executed by the compiler at one, with no user interaction, just the source code as input (no Read–eval–print loop, console or such things).

For example, C++ (11/14/17) then to go in this direction with things like recursive templates and constexpr, where entire functions can be executed at compile time (not runtime). But I imagine it even more generic and allowing for reflection (like Smalltalk, where everything is an object). It could help to reduce redundancy of the source code and allow more abstraction.

Code example:

```<code>const char* names[] = { "a", "b", "c", ... };
template<int size>
struct S {
    assert(size < sizeof(names)/sizeof(void*));
    for(int i = 0; i < size; ++i)
        this.add_field(Type::float, names[i]);
}
</code>```

This can not be done in C/C++, D has a bit more features like static ifs ans so on, but no language I know actually supports this.

Is there a name for this paradigm and are there languages which are heavily based on it?


问:
How to prevent multiple form submissions when user reloads the page
I'm currently working on a project which requires that we integration a 3rd party SOAP API to handle a number of basic CRUD type operations.

Our current implementation allows us to leveraging the Laravel framework's form validation classes prior to execution of these API requests data; however I have some concerns since we're not leveraging any type of queuing mechanism.

The current solutions stack involves placing a heavy burden on the NGINX web server to spawn additional workers for each blocking user request.  Obviously, this may lead to some issues down the line in terms of scalability.

There's also the possibility that users will frequently "refresh" pages after submitting form request data.

I've been looking into the Post/Redirect/Get pattern as a possible solution however I'm not quite sure that I completely understand the concept.

Here's a quote from one stackoverflow discussion:

The client gets a page with a form.

The form POSTs to the server.

The server performs the action, and then redirects to another page.

The client follows the redirect.

As stated above, these are long API calls and step 3 may take upwards of 10s to complete execution- what's to prevent the user from continually refreshing the page after step 2?

答:
I think as per the PRG pattern if there is a refresh after step2 there won't be an issue as the client(browser) will receive and use the redirect url.

The problem happens when the user refreshes before step 2 is completed(before sending the redirect url)!


问:
What do you think about the Joel Test?
The Joel Test is a well known test for determining how good your team is. What do you think about the points? Do you disagree with any of them? Is there anything that you would add?</p>

答: I agree with most of Joel's points.  I'm not so sure about "hallway usability testing".  Usability testing, sure, but actually grabbing someone from the hallway and making them test your program, even though it's not their job?  That seems like a great way to tick people off.</p>

Title: What do you think about the Joel Test?


问:
Managing Production Issues during a Scrum Sprint
The question of managing bugs in production has been a large feature in my mind of late. Sprint's are not meant to have any items added into them, but for critical bugs, this is simply unavoidable.

How does one go about managing this break in the sprint? Do you simply give a sprint a percentage "allowance" of time, thus only filling say 80% of the schedule with sprint items "just in case"?

答:
If it is a critical production issue, then you should be able to handle it directly, the chosen development methodology is irrelevant. A hotfix is not related to a regular release cycle (spints or otherwise).

I'd suggest fixing it in a 'fix' branche, based on the code that's currently in production.


答:
My (least) favourite reason for avoiding Object.finalize is not that objects might get finalized after you expect it, but they can get finalized before you might expect it. The problem is not that an object that is still in scope can be finalized before the scope is exited if Java decides it is no-longer reachable.

```<code>void test() {
   HasFinalize myObject = ...;
   OutputStream os = myObject.stream;

   // myObject is no-longer reachable at this point,
   // even though it is in scope. But objects are finalized
   // based on reachability.
   // And since finalization is on another thread, it
   // could happen before or in the middle of the write ..
   // closing the stream and causing much fun.
   os.write("Hello World");
}
</code>```

See this question for more details.
Even more fun is that this decision might only be made after hot-spot optimisation kicks in, making this painful to debug.

Title: Is overriding Object.finalize() really bad?

Body:
The main two arguments against overriding Object.finalize() is that:

You don't get to decide when it's called.

It may not get called at all.

If I understand this correctly, I don't think those are good enough reasons to hate Object.finalize() so much.

It is up to the VM implementation and the GC to determine when the right time to deallocate an object is, not the developer. Why is it important to decide when Object.finalize() gets called?

Normally, and correct me if I'm wrong, the only time Object.finalize() wouldn't get called is when the application got terminated before the GC got a chance to run. However, the object got deallocated anyway when the application's process got terminated with it. So Object.finalize() didn't get called because it was not needed to be called. Why would the developer care?

Every time I'm using objects that I have to manually close (like file handles and connections), I get very frustrated. I have to be constantly checking if an object has an implementation of close(), and I'm sure I have missed a few calls to it at some points in the past. Why isn't it just simpler and safer to just leave it to the VM and GC to dispose of these objects by putting the close() implementation in Object.finalize()?

Body:
My (least) favourite reason for avoiding Object.finalize is not that objects might get finalized after you expect it, but they can get finalized before you might expect it. The problem is not that an object that is still in scope can be finalized before the scope is exited if Java decides it is no-longer reachable.

void test() {
   HasFinalize myObject = ...;
   OutputStream os = myObject.stream;

   // myObject is no-longer reachable at this point,
   // even though it is in scope. But objects are finalized
   // based on reachability.
   // And since finalization is on another thread, it
   // could happen before or in the middle of the write ..
   // closing the stream and causing much fun.
   os.write("Hello World");
}

See this question for more details.
Even more fun is that this decision might only be made after hot-spot optimisation kicks in, making this painful to debug.


问:
Is Assembly still relevant?
Are there major differences between assembly language and higher level languages when it comes to coding and/or managing projects? Obviously it takes more statements in assembly language to carry out a particular operation than in most other languages, but are there differences that affect how a project needs to (or should) be run based on targeting assembly language (specifically x86/x64 assembly language)?

To the extent that there are differences between assembly language and other languages, it seems reasonable to guess that at least some of these are advantages for the other languages. Can anybody point out specific disadvantages of assembly language, and ways to mitigate those disadvantages?

One specific example would be staff availability. Has anybody had trouble finding experienced assembly language programmers, and if so, what steps can be taken to mitigate this problem?

答:
If you really really want to know why learning assembly is the best bet. Here are reasons.

No need to learn assembly, if you are going to do programming on visual basic and that  MS stuff.

No need to learn assembly, if you have to make no serious microcontroller gadgets.

No need to learn assembly, if you have a real estate of memory at your disposal while working on microcontroller (god helps you while interfacing the memory with microcontroller)

No need to learn assembly, if you do not want god like power over your microcontroller / microprocessor.

Not knowing assembly is like knowing iceberg. You can seen 25% of what yours and your micros capability and 75% you will never know or understand

Try running Kolibris OS completely written in Assembly !!! Have you seen an OS which boots up in less than 5 second and application start running with in 1 sec of mouse click.

Modern compilers have general purpose functions in backend and hence final code generated would be heafty compared to Assembly.

Assembly is like the Natasha Romanoff of Avengers. It's a charm and magic. First, it will bite you but trust me you will never forget the taste.

Title: Is Assembly still relevant?


问:
execute selection in console in C++ like python or R language
I am started to learn C++ using as IDLE Clion of jetbrain company. Normally using the IDLE of Python (i.e., Pycharm of Jetbrain) or R project i am able to execute selection in console line-by-line my code and understand all variables. Is it possible in C++ or i need to compile everytime?</p>

答:
What you are looking for is called a REPL, a quick search for "C++ REPL" gets you to Cling, but I have not used it.

I'm not sure what is the real benefit from using a REPL over to use a debugger with an interface that you are comfortable with. Static typing should help you get the code right before ever running it, also IDE's suggestions become much better than on 'duck typed' languages.


问:
Is guaranteeing immutability a justification for exposing a field instead of a property?
The general guidance for C# is to always use a property over a public field. This makes sense- by exposing a field, you're exposing a lot of implementation detail. With a property, you encapsulate that detail so it's hidden from consuming code, and implementation changes are decoupled from interface changes.

However, I'm wondering if there is sometimes a valid exception to this rule when dealing with the readonly keyword. By applying this keyword to a public field, you make an extra guarantee: immutability. This is not just an implementation detail, immutability is something that a consumer might be interested in. Using a readonly field makes it part of the public contract, and something that cannot be broken by future changes or inheritance without also having to modify the public interface. That's something that a property can't offer.

So is guaranteeing immutability a legitimate reason to choose a readonly field over a property in some cases?

(For clarification, I'm certainly not saying you should always make this choice just because the field happens to be immutable at the moment, only when it makes sense as part of the class's design and it's intended usage to include immutability in its contract. I'm mostly interested in answers focussing on whether this may be justified, rather than specific cases where it's not, such as when you need the member to be on an interface, or want to do lazy-loading.)

答:
Public static readonly fields are certainly okay. They are recommended for certain situations, like when you want a named, constant object but you can't use the const keyword.

Readonly member fields are a bit trickier. There isn't much advantage gained over a property without a public setter, and there is a major disadvantage: fields cannot be members of interfaces. So if you decide to refactor your code to operate against an interface instead of a concrete type, you will have to change your readonly fields to properties with public getters.

A public non-virtual property without a protected setter provides protection against inheritance, unless the inherited classes have access to the backing field. You can completely enforce that contract in the base class.

Not being able to change the "immutability" of the member without changing the public interface of the class is not much of a barrier in this case. Usually if you want to change a public field into a property, it goes smoothly except that there are two cases you have to deal with:

Anything that writes to a member of that object, like: object.Location.X = 4 is only possible if Location is a field. This is not relevant for a readonly field though, because you can't modify a readonly struct. (This is assuming Location is a value type - if not then this issue wouldn't apply anyway because readonly doesn't protect against that sort of thing.)

Any call to a method that passes the value as out or ref. Again, this is not really relevant for a readonly field, because out and ref parameters tend to get modified, and it's a compiler error anyway to pass a readonly value as out or ref.

In other words, although converting a readonly field to a readonly property breaks binary compatibility, other source code would only need to be recompiled without any changes to handle this change. That makes the guarantee really easy to break.

I don't see any advantages to the readonly member field, and the inability to have that sort of thing on an interface is enough of a disadvantage for me that I wouldn't use it.


答:
No.  It is not a justification.

Using the readonly as a guaranty of inmutability in not a justification is more like a hack.

Readonly means the value is assigned by a constructor o when the variable is defined.

I think it will be a bad practice

If you really want to guaranty immutability use an interface it has more pros than cons.

Simple interface example:

Title: Is guaranteeing immutability a justification for exposing a field instead of a property?

Body:
The general guidance for C# is to always use a property over a public field. This makes sense- by exposing a field, you're exposing a lot of implementation detail. With a property, you encapsulate that detail so it's hidden from consuming code, and implementation changes are decoupled from interface changes.

However, I'm wondering if there is sometimes a valid exception to this rule when dealing with the readonly keyword. By applying this keyword to a public field, you make an extra guarantee: immutability. This is not just an implementation detail, immutability is something that a consumer might be interested in. Using a readonly field makes it part of the public contract, and something that cannot be broken by future changes or inheritance without also having to modify the public interface. That's something that a property can't offer.

So is guaranteeing immutability a legitimate reason to choose a readonly field over a property in some cases?

(For clarification, I'm certainly not saying you should always make this choice just because the field happens to be immutable at the moment, only when it makes sense as part of the class's design and it's intended usage to include immutability in its contract. I'm mostly interested in answers focussing on whether this may be justified, rather than specific cases where it's not, such as when you need the member to be on an interface, or want to do lazy-loading.)


答:
Fields are ALWAYS implementation details.  You don't want to expose your implementation details.

A fundamental tenet of software engineering is that we don't know what the requirements will be in the future.  While your readonly field may be good today, there is nothing to suggest that it will be a part of tomorrow's requirements.  What if tomorrow there is a need to implement a hit counter to determine how many times that field is accessed?  What if you need to allow sub-classes to override the field?

Properties are so easy to use and are so much more flexible than public fields that I can't think of a single use case where I would both pick c# as my language and use public readonly fields on a class.  If performance was so tight that I couldn't take the hit of the extra method call, I'd probably be using a different language.

Just because we can do something with the language doesn't mean we should do something with the language.

I actually wonder whether the language designers regret allowing fields to be made public.  I can't remember the last time I even considered using non-const public fields in my code.


答:
From my experience, the readonly keyword is not the magic it promises to.

For example, you have a class where the constructor used to be simple. Given the usage, (and the fact that some of the class properties/fields are immutable after construction) you might think that it does not matter, so you used the readonly keyword.

Later, the class become more complex, and so is its constructor. (Let's say this happens in a project that is either experimental or has a high enough velocity zooming out of scope/control but you need to make it work somehow.) You will find that fields that are readonly can only be modified inside the constructor - you can't modify it in methods even if that method is only called from a constructor.

This technical limitation has been acknowledged by the designers of C#, and might be fixed in a future version. But until it is fixed, the use of readonly is more restrictive and might encourage some bad coding style (putting everything in the constructor method).

As a reminder, neither readonly nor non-public-setter property provides any guarantee of a "fully initialized object". In other words, it is the designer of a class that decides what "fully-initialized" means, and how to protect it against inadvertent use, and such protection is generally not foolproof, meaning that someone might find a way around it.


问:
Best approach to write windows service
We got a situation where we need to write a windows service using c#, the service need to be install on a particular -single- server. Also service need to communicate with a DB to access certain table to process data.

What will be the best approach to pass on the credentials to this service?

We have built the service, but now doing some R&D about passing credentials. We don't want to save them hard coded inside the code of course, also we don't like the idea of saving them in the file on server. We are thinking of passing it as parameters, when we install the service using InstallUtil.

What do you guys think, is it good or there is something better to it?

答:
The best approach is to store these in an encrypted section of your config file, the key to encrypt this should be stored in Windows protected storage for the user it runs as (ie no-one else, not even another admin can then access it). This assumes you need to store and use these credentials to pass on to access the DB, if you are simply running the service as particular user, simply install it as that user. Create a user specifically to run this service, that's even better for security.

With this approach, you're using Windows for security, any private data (eg connection string to the DB) is encrypted so only the service user can access it, and Windows takes care of all the details.

Do not pass them as (commands line) parameters to the service - anyone with rights to view Service control panel applet will be able to see them!

Also, make sure you use AD domain users - NTLM is crackable in minutes with today's hardware,

Title: Best approach to write windows service


问:
using GNU GPL v2 software as pointers to solution to problem
I am coding a PHP serial access class and have been taking pointers from the PHP-serial class on Google Code (here).  That class is based on PHP 4 and I'm creating a PHP 5 class that allows more functionality and is specific to some business demands I have.

There is no code copied and I have done all the coding.  Does the class I'm writing fall under the Google Code's GPL or am I free to select a license that I feel is appropriate?  I'm not sure of the standard that applies to licensing when you are only looking to another work for pointers.

答:
If you just keep your work in-house (ie, don't distribute it), then you can do whatever you want with GPL software.

If you intend to sell your work and you have questions about licensing restrictions, you should talk to a lawyer.

Just a reminder to everyone else on Stack Exchange: There aren't many attorneys on here. The few that are aren't your attorney. Don't find-out the hard way that you're doing something wrong.


问:
What is a good design for allowing backwards compatibility of files between different versions of software?
What is a good design for allowing backwards compatibility of a file type between different versions of software?

For instance, how does microsoft get word 2007, 2010 and 2013 etc... to all open docx files, but different editions can save more / less data and save the data in slightly different ways, all to the same file type, and a file that is saved in one version can be opened in another, but certain elements of the file might not be available in older versions?

I mean, the really obvious way to do it is to have something like

```<code>private string openfile(string filename)
{
    File.Open(filename)

    ... some logic that gets a header from the file that will never change

    switch (fileversion)
        case 2007:
            .....
        case 2010
            .....
        case 2013
            .....
}
</code>```

but that seems incredibly monolithic, not very extensible, and likely to lead to a lot of copy / pasted code.

So I was thinking of using a base interface for all versions which defines the immutable structures, such as the header, that need to be present in the file, and methods that need to be available for serialisation / deserialisation, then multiple inheritance so that each new version's class that implements the interface inherits the old version, and only overrides stuff that has changed, since the file will be the same, for the most part.

I'm not really bothered about the structure of the file, since it's already decided that we'll be using XML, and the initial schema is, by and large, already decided. However there will no doubt be changes to it in the future, and I just want to be able to design the code in a way that makes it easy to accommodate these changes.

答:
I have done this with XML and it works well:

Simply allow any element in your document, to have any attributes and any subelements (and when order is not important - in any order). Beginning from first version of program - when reading document, ignore attributes and sub-elements that you dont know in current version.

In future when you are adding new feature to new version of program then add attribute or sub-element. Older versions will ignore it. New version should check pressence of attribute or sub-element and handle with it.

For example you have some items with texts:

```<code><item text="Hello, world!"/>
</code>```

And in newer version you would like to add color to item so you add attribute color:

```<code><item text="Hello, world!" color="008000"/>
</code>```

Older version will simply ignore color attribute when opening document.
New versions check for pressence of color attribute and if does not exist assigns default color.

With this simple solution you will have both backward and forward compatibility.

Body:
I have done this with XML and it works well:

Simply allow any element in your document, to have any attributes and any subelements (and when order is not important - in any order). Beginning from first version of program - when reading document, ignore attributes and sub-elements that you dont know in current version.

In future when you are adding new feature to new version of program then add attribute or sub-element. Older versions will ignore it. New version should check pressence of attribute or sub-element and handle with it.

For example you have some items with texts:

<item text="Hello, world!"/>

And in newer version you would like to add color to item so you add attribute color:

<item text="Hello, world!" color="008000"/>

Older version will simply ignore color attribute when opening document.
New versions check for pressence of color attribute and if does not exist assigns default color.

With this simple solution you will have both backward and forward compatibility.


答:
I think you're asking "are trucks still relevant if we have cars?". I mean, assembly has a very wide range of applications but not as wide as high level programming has, the same way that there are much less trucks than cars.

In fields like optimization of algorithms, you can use directly processor registers for improving images/video processing algorithms.

In fields like cryptography you can use it in the same way.

In new processors with new architectures (remember when Cell microprocessor was released), for sure they had to write boot loaders and so on in assembly (and with old processors too, but long time used processors have a very stable ground and is difficult to improve it).

And many more examples could be given, so it depends in the field you company is focused, if your company is dedicated to web/mobile development, is very likely that you don't need it, but if your company is focused in microcontrollers, embedded systems, etc. is quite probable that you need it.

And staff availability, it depends on, I guess that if you ask in Intel, Qualcomm, ... they must have a large assembly programmer's list (is like if you ask at your workplace "how many truck drivers are around here?" I think not much, but it doesn't mean that there aren't in other places. What happens if you ask "how many car drivers are around here?").

Title: Is Assembly still relevant?

Body:
Are there major differences between assembly language and higher level languages when it comes to coding and/or managing projects? Obviously it takes more statements in assembly language to carry out a particular operation than in most other languages, but are there differences that affect how a project needs to (or should) be run based on targeting assembly language (specifically x86/x64 assembly language)?

To the extent that there are differences between assembly language and other languages, it seems reasonable to guess that at least some of these are advantages for the other languages. Can anybody point out specific disadvantages of assembly language, and ways to mitigate those disadvantages?

One specific example would be staff availability. Has anybody had trouble finding experienced assembly language programmers, and if so, what steps can be taken to mitigate this problem?


问:
What and how much domain code should be put in an F# module
According to recommendations given here, F# modules should correspond to DDD bounded contexts, i.e. subdivisions of a business domain.

The bounded context I'm working on right now has 2 aggregates totalling a dozen of types, plus some rather complex functions/algorithms. If I follow the prescribed style, I end up with a 500+ LOC file, which IMO isn't very readable or navigatable, and it will only grow longer. Unfortunately, it seems F# modules can't be split across multiple files.

Other solutions I've attempted are :

One module per aggregate. Problem -- if I include the aggregate type in the module, I end up with an inelegant aggregate type name (e.g. MyAggregate.MyAggregate), especially when reused in non-F# .NET code.

One file with all the types of the bounded context under a particular namespace and another file containing the functions inside a module. Still not satisfying since in F# I can't give the same name to the module and namespace, and functions are not really organized inside the file.

```<code>// This gives a "namespace and module named ... both occur in 2 parts of this assembly" error

//File1.fs

namespace MyProject.Domain.MyBC

type MyType =
    // ...

//File2.fs

namespace MyProject.Domain

module MyBC = //...
</code>```

I'm still looking for a solution that satisfies the following

Meaningful organization of code reflecting DDD concepts, so that code lookup feels easy and obvious

Some degree of compartmentalization, to prevent native access to other unrelated parts of the domain and avoid mistakes

Low cognitive load to explore a file (meaning no more than a few hundred lines of code per file)

Simple, non contrived usage from external non-F# .NET code

Have I missed the obvious way of doing it, or does the lack of partial modules + namespace/module collision just make them an awkward scope for DDD?

答:
Having watched the section of the video you refer to, I don't see where Scott says a Bounded Context should correspond to a module.  He just happens to chose a module to represent the Bounded Context in his example.  There is absolutely no reason that a Bounded Context must correspond to a module.

If you feel your Bounded Context does not map well to a module, you are free to split it in whatever way you want.  It can as many modules and types as you want, partitioned by namespace(s), assembly or whatever else floats your boat.  All that matters is that the principles of a Bounded Context that you desire, are achieved.

With regards to file size and navigation, you could try Visual F# Power Tools Navigate To feature.