问:
How can I have a variable timeout value based on machine performance?
I have a similar problem as Criteria for selecting timeout value?. But my question is slight different.

Process A dependes on process B and has a timeout value of 5 seconds, sometimes process B might take longer to respond(e.g. slow machines), in this case process A will think process B is gone and will terminate.

We have a performance requirement, so the goal is to always respond on the least feasible time. This application runs on tablets, notebooks, desktops and even servers. In a scenario were the host machine performance can vary widely, how can we adjust the timeout taking into account machine performance?

答:
I see two different options, use the one that makes more sense for the details of your use case:

Option 1: Immediately return from callback with longer timeout

It doesn't matter if the timeout is longer on a faster system, if it can immediately return and break you out of the wait period once the process is complete. So while the timeout is "10 seconds", on a fast system it could be effectively "1 second" or even faster.

Option 2: Don't give up on the first try

You can wait the 5 seconds, if there's no response, try again. Perhaps take three tries before giving up and terminating. You can modify the user interface to say something like "connecting to process B attempt #1, connecting to process B attempt #2", etc. so that it doesn't seem too long to the user, so that it looks like something is happening.


问:
Reducing the complexity of a class
I have looked at some answers and searched on Google, but I could not find anything helpful (i.e., that wouldn't have awkward side effects).

My problem, in abstract, is that I have an object and need to perform a long sequence of operations on it; I think of it as a sort of assembly line, like building a car.

I believe these objects would be called Method Objects.

So in this example at some point I would have a CarWithoutUpholstery on which I would then need to run installBackSeat, installFrontSeat, installWoodenInserts (the operations do not interfere with one another, and might even be done in parallel). These operations are performed by CarWithoutUpholstery.worker() and yield a new object which would be a CarWithUpholstery, on which I would then run maybe cleanInsides(), verifyNoUpholsteryDefects(), and so on.

The operations in a single phase are already independent, i.e., I am already grappling with a subset of them that may be executed in any order (front and rear seats may be installed in any order).

My logic currently uses Reflection for simplicity of implementation.

That is, once I have a CarWithoutUpholstery, the object inspects itself for methods called performSomething(). At that point it executes all these methods:

```<code>myObject.perform001SomeOperation();
myObject.perform002SomeOtherOperation();
...
</code>```

while checking errors and stuff. While order of operation is unimportant, I have assigned a lexicographic order in case I ever discover some order is important after all. This contradicts YAGNI, but it costed very little - a simple sort() - and it could save a massive method renaming (or introducing some other method of performing tests, e.g. an array of methods) down the line.

A different example

Let us say that instead of building a car I have to compile a Secret Police report on somebody, and submit it to my Evil Overlord. My final object will be a ReadyReport. To construct it I start by gathering basic information (name, surname, spouse...). This is my Phase A. Depending on whether there is a spouse or not, I may then have to proceed to phases B1 or B2, and gather sexuality data on one or two people. This is made of several different queries to different Evil Minions controlling night life, street cams, sex shop sales receipts and what not. And so on and so forth.

If the victim has no family, I will not even enter the GetInformationAboutFamily phase, but if I do, then it's irrelevant whether I first target the father or the mother or the siblings (if any). But I cannot do that if I haven't performed a FamilyStatusCheck, which therefore belongs to an earlier phase.

It all works wonderfully...

if I need some additional operation I only need to add a private method,

if the operation is common to several phases I can have it inherited from a superclass,

operations are simple and self-contained. No value from one operation is ever required by any of the others (operations that do are performed in a different phase),

objects down the line do not need to perform many tests since they could not even exist if their creator objects hadn't verified those conditions in the first place. I.e., when placing inserts in the dashboard, cleaning the dashboard and verifying the dashboard, I needn't verify that a dashboard is actually there.

it allows for easy testing. I can easily mock a partial object and run any method on it, and all operations are deterministic black boxes.

...but...

The problem arose when I added one last operation in one of my method objects, which caused the overall module to exceed a mandatory complexity index ("less than N private methods").

I have already taken the matter upstairs and suggested that in this case, the wealth of private methods is not a telltale of disaster. The complexity is there, but it's there because the operation is complex, and actually it's not all that complex - it's just long.

Using the Evil Overlord example, my problem is that the Evil Overlord (aka He Who Shall Not Be Denied) having requested all dietary information, my Dietary Minions telling me that I need to query restaurants, kitchenettes, street vendors, unlicensed street vendors, greenhouse owners etc., and the Evil (sub)Overlord - familiarly known as He Who Also Shall Not Be Denied - complaining that I'm performing too many queries in the GetDietaryInformation phase.

Note: I am aware that from several points of view this is not a problem at all (ignoring possible performance issues etc.). All that's happening is that a specific metric is unhappy, and there is justification for that.

What I think I could do

Apart from the first, all these options are doable and, I think, defensible.

I have verified that I can be sneaky and declare half my methods protected. But I'd be exploiting a weakness in the testing procedure, and apart from justifying myself when caught, I don't like this. Also, it's a stopgap measure. What if the number of required operations doubles? Unlikely, but what then?

I can split arbitrarily this phase into AnnealedObjectAlpha, AnnealedObjectBravo and AnnealedObjectCharlie, and have one third the operations being performed at each stage. I am under the impression that this actually adds complexity (N-1 more classes), with no benefit except for passing a test. I can of course hold that a CarWithFrontSeatsInstalled and a CarWithAllSeatsInstalled are logically successive stages. The risk of a Bravo method being later required by Alpha is small, and even smaller if I play it well. But still.

I can bunch different operations, remotely similar, in a single one. performAllSeatsInstallation(). This is only a stopgap measure and it does increase the complexity of the single operation. If I ever need to do operations A and B in a different order, and I have packed them inside E = (A+C) and F (B+D), I'll have to unbundle E and F and shuffle the code around.

I can use an array of lambda functions and neatly sidestep the check altogether, but I find that clunky. This is however the best alternative so far. It would get rid of reflection. The two problems I have is that I would probably be asked to rewrite all method objects, not only the hypothetic CarWithEngineInstalled, and while that would be very good job security, it really doesn't appeal all that much; and that the code coverage checker has issues with lambdas (which are solvable, but still).

So...

Which, you think, is my best option?

Is there a better way I haven't considered? (perhaps I'd better come clean and ask directly what is it?)

Is this design hopelessly flawed, and I'd better admit defeat and ditch - this architecture altogether? Not good for my career, but would writing ill-designed code be any better in the long term?

Is my current choice actually the One True Way, and I need to fight to get better quality metrics (and/or instrumentation) installed? For this last option I'd need references... I can't just wave my hand at the @PHB while murmuring These aren't the metrics you're looking for. No matter how much I'd like to be able to

答:
A couple of things you mention stand out as 'bad' to me

"My logic currently uses Reflection for simplicity of implementation"

There really is no excuse for this. are you really using string comparison of method names to determine what to run?! if you change the order will you have to change the name of the method?!

"The operations in a single phase are already independent"

If they are truly independent of each other it suggests that your class has taken on more than one responsibility. To me, both your examples seem to lend themselves to some sort of single

```<code>MyObject.AddComponent(IComponent component)
</code>```

approach which would allow you to split the logic for each opperation into its own class or classes.

In fact I imagine they are not truly independent, I imagine that each examines the state of the object and modifies it, or at least performs some sort of validation before commencing.

In this case you can either:

Throw OOP out the window, and have services which operate on the exposed data in your class ie.

Service.AddDoorToCar(Car car)

Have a builder class which constructs your object by assembling the needed data first and passing back the completed object ie.

Car = CarBuilder.WithDoor().WithDoor().WithWheels();

(the withX logic can again be split into subbuilders)

Take Functional approach and pass functions/delgates into a modify method

Car.Modify((c)=> c.doors++);

ContentLicense: CC BY-SA 3.0

Title: Reducing the complexity of a class

Body:
A couple of things you mention stand out as 'bad' to me

"My logic currently uses Reflection for simplicity of implementation"

There really is no excuse for this. are you really using string comparison of method names to determine what to run?! if you change the order will you have to change the name of the method?!

"The operations in a single phase are already independent"

If they are truly independent of each other it suggests that your class has taken on more than one responsibility. To me, both your examples seem to lend themselves to some sort of single

MyObject.AddComponent(IComponent component)

approach which would allow you to split the logic for each opperation into its own class or classes.

In fact I imagine they are not truly independent, I imagine that each examines the state of the object and modifies it, or at least performs some sort of validation before commencing.

In this case you can either:

Throw OOP out the window, and have services which operate on the exposed data in your class ie.

Service.AddDoorToCar(Car car)

Have a builder class which constructs your object by assembling the needed data first and passing back the completed object ie.

Car = CarBuilder.WithDoor().WithDoor().WithWheels();

(the withX logic can again be split into subbuilders)

Take Functional approach and pass functions/delgates into a modify method

Car.Modify((c)=> c.doors++);


问:
Inheritance when following the Repository Pattern in PHP
I am trying to build a PHP application using the Repository Pattern but I'm not sure how I should implement the save method.

I have an abstract class called ItemRepository which have the following method:

```<code>abstract class ItemRepository
{
    public function save(Item $item);
}
</code>```

Where Item also is an abstract class.

Now I want to implement the class MovieRepository which extends ItemRepository. Here I want to save instances of the Movie class which extends Item.

Though doing it like this in PHP

```<code>// MovieRepository.php
class MovieRepository extends ItemRepository
{
    public function save(Movie $movie)
    {
        ...
    }
}
</code>```

gives the following error

Declaration of MovieRepository::save() should be compatible with ItemRepository::save(Item $item)

What is the right way to do this?

答:
Unless the ItemRepository and MovieRepository classes are actually related, then you don't need a parent class. Instead, go with MovieRepository implementing an interface:

```<code>interface IMovieRepository
{
    function save(Movie $movie);
}

class MovieRepository implements IMovieRepository
{
    public function save(Movie $movie) {
        // ...
    }
}
</code>```

Any place you need the movie repository, use the interface instead. A sample controller utilizing constructor injection is below:

```<code>class MoviesController
{
    private $movies;

    public __construct(IMovieRepository $movies = null) {
        $this->movies = $movies || new MovieRepository();
    }

    public function create($params) {
        $movie = new Movie();
        // Populate $movie based on $params

        $this->movies->save($movie);
    }
}
</code>```

If anything, I would create a BaseRepository class that does not implement any CRUD methods, and just contains common functionality for all repository classes. The saving of one entity to another will change, therefore they are not related and should not share a common parent class.

Body:
Unless the ItemRepository and MovieRepository classes are actually related, then you don't need a parent class. Instead, go with MovieRepository implementing an interface:

interface IMovieRepository
{
    function save(Movie $movie);
}

class MovieRepository implements IMovieRepository
{
    public function save(Movie $movie) {
        // ...
    }
}

Any place you need the movie repository, use the interface instead. A sample controller utilizing constructor injection is below:

class MoviesController
{
    private $movies;

    public __construct(IMovieRepository $movies = null) {
        $this->movies = $movies || new MovieRepository();
    }

    public function create($params) {
        $movie = new Movie();
        // Populate $movie based on $params

        $this->movies->save($movie);
    }
}

If anything, I would create a BaseRepository class that does not implement any CRUD methods, and just contains common functionality for all repository classes. The saving of one entity to another will change, therefore they are not related and should not share a common parent class.


问:
Functional programming, compared to the process of a computer
In functional programming, it is considered bad practice (at least from my observations) to use state changes. Since computers operate in an imperative-language-like matter (performing one operation at a time, changing states of RAM), isn't functional programming contradictory to the way a computer operates?

Note: I'm not trying to say that a functional language cannot exist, because obviously there are several out there that do exist and work very well.

Further note: Besides the difference in processes, wouldn't a functional language be inherently extremely slow, due to the amount of operations involved?

答:
Programming languages have two purposes.  The first is easy to see, "programming languages have to tell a computer what to do."  The second is more subtle: "programming languages have to allow a programmer to convey to the computer what they want it to do, efficiently."  In theory, one could always program in assembly (or even machine code), and tell a computer exactly what to do.  In practice, we choose other languages because they are better tools for expressing what we want the computer to do.

Even the most pure functional programming languages such as LISP and Haskel have a modicum of imperative language in that something tells the computer to evaluate one of the pure functions, and then do something to the state of the machine, such as print the result to the screen.  They push this all the way to the outer edge of the language, such that 99.9999999% of programming is done in a pure functional world, but that edge is always there, simply because the program has to run on a computer, and computers currently use imperative logic.

This is where the translation steps of compiling or interpretation come in.  We have to turn a program written into some language into something the computer can do, and the only hook we get from the computer is "the computer guarantees that, when your program is run, it will start executing instruction as at address XXXXX."  Thus, whether the language is C++, LISP, or even assembly, the code needs to be mapped into something which, when the computer starts executing at address XXXXX, the desired result occurs.

This translation step is where the speed differences of languages come into play, and where optimization plays a big part.  For example, everyone can look at the C++ statement int x = 1 + 2; and see that we want to run opcodes along the lines of (stack based pseudobytecode)

```<code>load-constant 1
load-constant 2
add
store-as x
</code>```

And we might even optimize this, because we see that the constants can't change:

```<code>load-constant 3
store-as x
</code>```

Now consider the equivalent lisp phrase (let x (+ 1 2)).  If I don't optimize, it looks exactly as inefficient as you think it should:

```<code>load-constant '+'  # yes, the + operator is handled as a constant function in LISP
load-constant 1
load-constant 2
call-function 2 # call a 2 argument function, +, on the two arguments, 1 and 2
store-as x
</code>```

We have to explicitly call a function, which often costs an order of magnitude more than merely doing an addition.  It looks like functional languages have to be slow!  However, an optimizer can realize that + is a constant function that doesn't change within the scope of the program, so it can "inline" its behavior to get

```<code>load-constant 1
load-constant 2
add
store-as x
</code>```

This looks familiar, we can even continue the optimization to get

```<code>load-constant 3
store-as x
</code>```

So, for our extremely contrived example, functional programming literally runs as fast as imperative coding.  So what is the difference between them?  Why do we bother with functional programming?

As it turns out, the reason for functional programming is the second purpose of programming languages, to allow a programmer to convey meaning.  There are cases where functional programming is actually a more effective communication mechanism between programmer and computer.  This especially true in asynchronous situations, such as those that show up in GUIs.  In such cases, one is often forced to rely on tricks and workarounds to map such behaviors into imperative phrasings, while the equivalent functional phrasing flows naturally.  This isn't always the case (especially in the case of hardcore mathematics), but in an increasing number of cases, it's a more effective tool.  This is why many imperative languages are starting to add little fragments of functional programming to help them better convey meaning (see C++'s lambdas).

Now there's a subtlety here.  I mentioned that using the "wrong" language means you have to find tricks or workarounds.  This is true both for functional and imperative languages.  The more workarounds you have to use, the harder it turns out to be to optimize the code.  Functional languages often have very high standards for "pure" functions which capture their side effects explicitly.  This can often allow the compiler to make sweeping optimizations which were markedly hard to prove if you had written them in imperative form.  In theory the optimization can be applied in both cases, but it can be harder for a compiler to see the optimization if it is ill-fit for the language at hand.  Likewise, attempting to model highly imperative code in functional languages often call for strange tools like monads which can strain the optimizer as it tries to find the best way to evaluate everything.

As a case study, I worked with a language designed to be used by analysts, not coders.  Accordingly, it was unreasonable to expect them to learn a great deal about how to optimize their code (they needed to spend their brainpower analyzing, not coding!).  The compiler really needed to do it for them.  We actually found that a functional programming language was a better match for them.  They would often "call a function" ten thousand times or more, when the result never changed.  They could caching it once, but the mentality of caching did not fit well with the flow of their process, so they simply did not do so.  Remember, a language needs to work for your real customer, not your ideal customer.

Accordingly, we gave them a functional language with strict purity rules on the functions.  This gave us, as the developers making the language, great power to identify values which could be cached, and to invalidate those cached values as they changed.  The result was a language which, despite being "functional," thus further from the metal speeds, actually ran 1000x faster because our optimizer was able to see more opportunities for optimization, leveraging the strictness of pure functions.

Body:
Programming languages have two purposes.  The first is easy to see, "programming languages have to tell a computer what to do."  The second is more subtle: "programming languages have to allow a programmer to convey to the computer what they want it to do, efficiently."  In theory, one could always program in assembly (or even machine code), and tell a computer exactly what to do.  In practice, we choose other languages because they are better tools for expressing what we want the computer to do.

Even the most pure functional programming languages such as LISP and Haskel have a modicum of imperative language in that something tells the computer to evaluate one of the pure functions, and then do something to the state of the machine, such as print the result to the screen.  They push this all the way to the outer edge of the language, such that 99.9999999% of programming is done in a pure functional world, but that edge is always there, simply because the program has to run on a computer, and computers currently use imperative logic.

This is where the translation steps of compiling or interpretation come in.  We have to turn a program written into some language into something the computer can do, and the only hook we get from the computer is "the computer guarantees that, when your program is run, it will start executing instruction as at address XXXXX."  Thus, whether the language is C++, LISP, or even assembly, the code needs to be mapped into something which, when the computer starts executing at address XXXXX, the desired result occurs.

This translation step is where the speed differences of languages come into play, and where optimization plays a big part.  For example, everyone can look at the C++ statement int x = 1 + 2; and see that we want to run opcodes along the lines of (stack based pseudobytecode)

load-constant 1
load-constant 2
add
store-as x

And we might even optimize this, because we see that the constants can't change:

load-constant 3
store-as x

Now consider the equivalent lisp phrase (let x (+ 1 2)).  If I don't optimize, it looks exactly as inefficient as you think it should:

load-constant '+'  # yes, the + operator is handled as a constant function in LISP
load-constant 1
load-constant 2
call-function 2 # call a 2 argument function, +, on the two arguments, 1 and 2
store-as x

We have to explicitly call a function, which often costs an order of magnitude more than merely doing an addition.  It looks like functional languages have to be slow!  However, an optimizer can realize that + is a constant function that doesn't change within the scope of the program, so it can "inline" its behavior to get

load-constant 1
load-constant 2
add
store-as x

This looks familiar, we can even continue the optimization to get

load-constant 3
store-as x

So, for our extremely contrived example, functional programming literally runs as fast as imperative coding.  So what is the difference between them?  Why do we bother with functional programming?

As it turns out, the reason for functional programming is the second purpose of programming languages, to allow a programmer to convey meaning.  There are cases where functional programming is actually a more effective communication mechanism between programmer and computer.  This especially true in asynchronous situations, such as those that show up in GUIs.  In such cases, one is often forced to rely on tricks and workarounds to map such behaviors into imperative phrasings, while the equivalent functional phrasing flows naturally.  This isn't always the case (especially in the case of hardcore mathematics), but in an increasing number of cases, it's a more effective tool.  This is why many imperative languages are starting to add little fragments of functional programming to help them better convey meaning (see C++'s lambdas).

Now there's a subtlety here.  I mentioned that using the "wrong" language means you have to find tricks or workarounds.  This is true both for functional and imperative languages.  The more workarounds you have to use, the harder it turns out to be to optimize the code.  Functional languages often have very high standards for "pure" functions which capture their side effects explicitly.  This can often allow the compiler to make sweeping optimizations which were markedly hard to prove if you had written them in imperative form.  In theory the optimization can be applied in both cases, but it can be harder for a compiler to see the optimization if it is ill-fit for the language at hand.  Likewise, attempting to model highly imperative code in functional languages often call for strange tools like monads which can strain the optimizer as it tries to find the best way to evaluate everything.

As a case study, I worked with a language designed to be used by analysts, not coders.  Accordingly, it was unreasonable to expect them to learn a great deal about how to optimize their code (they needed to spend their brainpower analyzing, not coding!).  The compiler really needed to do it for them.  We actually found that a functional programming language was a better match for them.  They would often "call a function" ten thousand times or more, when the result never changed.  They could caching it once, but the mentality of caching did not fit well with the flow of their process, so they simply did not do so.  Remember, a language needs to work for your real customer, not your ideal customer.

Accordingly, we gave them a functional language with strict purity rules on the functions.  This gave us, as the developers making the language, great power to identify values which could be cached, and to invalidate those cached values as they changed.  The result was a language which, despite being "functional," thus further from the metal speeds, actually ran 1000x faster because our optimizer was able to see more opportunities for optimization, leveraging the strictness of pure functions.


答:
It sounds like you have more of a performance scaling problem rather than a classic 'stop waiting if it takes too long' scenario

eg, say my app notifies me when a goal is scored in a football match. Every X seconds it polls a server to see if a goal has been scored.

If the server is down or slow I can switch to a backup server, so I don't want to wait forever. But the backup is slower than the main server. so I don't want to switch unnecessary. Also I want to know about the goal as soon as possible after it happens.

If I poll every second, the sever will be overloaded and start responding slowly, delaying the news. but if I only poll every minute the server may be capable of responding much quicker.

Here a simple static timeout of X seconds is unhelpful. if its too short I will switch the the backup too often. If its too long, I will wait too long before switching. My app needs a dynamic shifting expectation value for how long it expects the server to take.

To get this I need to log how long each request takes and modify the apps behaviour according. ie switch to the backup, make more or fewer requests or in your case terminate process A

Title: How can I have a variable timeout value based on machine performance?

Body:
I have a similar problem as Criteria for selecting timeout value?. But my question is slight different.

Process A dependes on process B and has a timeout value of 5 seconds, sometimes process B might take longer to respond(e.g. slow machines), in this case process A will think process B is gone and will terminate.

We have a performance requirement, so the goal is to always respond on the least feasible time. This application runs on tablets, notebooks, desktops and even servers. In a scenario were the host machine performance can vary widely, how can we adjust the timeout taking into account machine performance?


问:
Event sourcing and REST
I came across Event Sourcing design and I would like to use in an application where a REST client is needed (RESTful to be precise). However I fail to connect these together as REST is quite CRUD-like and event sourcing is task based. I was wondering how can you designed the creation of commands based on requests to REST server. Consider this example:

With REST you can put a new state to the resource called File. In one request you can send new file name, you can change the parent folder and/or change owner of the file and so on.

How to construct the server so I can use event sourcing. I was thinking about these possibilities:

Determine on server which fields were changed and create appropriate commands (RenameFileCommand, MoveFileCommand, ChangeOwnerCommand, ...) and dispatch these individually. However in this setup, each of the command can fail leaving others out of transaction and thus out of "atomic" change to the resource.

Dispatch only one command (UpdateFileCommand) and in the command handler, more precisely in the aggregate, determine which fields were changed and send individual events instead (FileRenamedEvent, FileMovedEvent, OwnerChangedEvent, ...)

This one I don't like at all: In the request to the server I would specify in the headers which command to use, because the UI is still task based (but communication is done via REST). However it will fail in any other use of REST communication (e.g. in external apps) as they are not bound to change only the one field in one request. Also I bring quite a big coupling into the UI, REST, and ES-based backend.

Which one would you prefer or is there any better way to handle this?

Side note: app written in Java and Axon Framework for event-sourcing.

答:
Just now I ran into the following article, which encourages specifying the command names in the request to the server in the Content-Type header (while following 5 levels of media type).

In the article, they mention the RPC-style is bad for REST and suggest extending Content-Type to specify the command name:

One common approach is using RPC-style resources for example /api/InventoryItem/{id}/rename. While this seemingly removes the need for arbitrary verbs, it is against REST's resource-oriented presentation. We need to be reminded that a resource is a noun and HTTP verb is the verb/action and self-descriptive messages (one of the tenets of REST) are the vehicle to convey other axes of information and intent. In fact the command in the payload of the HTTP message should be enough to express any arbitrary action. However, relying on the body of the message has problems of its own since the body is usually delivered as a stream and buffering the body in its entirety before identifying action is not always possible nor wise. Here we present an approach based on level 4 (domain model) of 5LMT where the command type is presented as a parameter of the Content-Type header:

```<code>PUT /api/InventoryItem/4454c398-2fbb-4215-b986-fb7b54b62ac5 HTTP/1.1
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Content-Type:application/json;domain-model=RenameInventoryItemCommand`
</code>```

The article is here: http://www.infoq.com/articles/rest-api-on-cqrs

You can read more about 5 levels of media type here: http://byterot.blogspot.co.uk/2012/12/5-levels-of-media-type-rest-csds.html

Although they are exposing the domain events to the REST API, which I would consider a bad practise, I like the solution as it doesn't create a new "protocol" solely for CQRS, be it sending command names in the body or in extra header, and stays true to RESTful principles.

Title: Event sourcing and REST

Body:
Just now I ran into the following article, which encourages specifying the command names in the request to the server in the Content-Type header (while following 5 levels of media type).

In the article, they mention the RPC-style is bad for REST and suggest extending Content-Type to specify the command name:

One common approach is using RPC-style resources for example /api/InventoryItem/{id}/rename. While this seemingly removes the need for arbitrary verbs, it is against REST's resource-oriented presentation. We need to be reminded that a resource is a noun and HTTP verb is the verb/action and self-descriptive messages (one of the tenets of REST) are the vehicle to convey other axes of information and intent. In fact the command in the payload of the HTTP message should be enough to express any arbitrary action. However, relying on the body of the message has problems of its own since the body is usually delivered as a stream and buffering the body in its entirety before identifying action is not always possible nor wise. Here we present an approach based on level 4 (domain model) of 5LMT where the command type is presented as a parameter of the Content-Type header:

PUT /api/InventoryItem/4454c398-2fbb-4215-b986-fb7b54b62ac5 HTTP/1.1
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Content-Type:application/json;domain-model=RenameInventoryItemCommand`

The article is here: http://www.infoq.com/articles/rest-api-on-cqrs

You can read more about 5 levels of media type here: http://byterot.blogspot.co.uk/2012/12/5-levels-of-media-type-rest-csds.html

Although they are exposing the domain events to the REST API, which I would consider a bad practise, I like the solution as it doesn't create a new "protocol" solely for CQRS, be it sending command names in the body or in extra header, and stays true to RESTful principles.


问:
Cross-language Test-Driven Development
The short question: How do you follow Test-Driven Development on a project that spans multiple languages?

Specifically, I'm writing a web application that uses JavaScript and PHP, and I want to follow the TDD principles, but I'm not sure how to integrate them. Do I run separate test suites for the JS and PHP sections, and use mocks in the JS suite to emulate server responses? Is there a technique for unit testing both components in one run?

This is my first experience using Test-Driven Development, so any advice you can share on how to make it less daunting would be great. The reason I chose it is that as soon as I finished a prototype, the requirements changed, forcing me to change my design. I figured if I'm starting over, I'd like to write more extensible code with built-in regression testing from the start.

I'm writing my PHP tests in SimpleTest and my JavaScript tests in JsTestDriver. I'm used to object-oriented paradigms, so I've got a few classes in PHP, and I'm doing the something similar in JavaScript using prototypal inheritance. I've also started reading this book about TDD in Python and this one about TDD in JavaScript, but from all that I've seen, these don't describe testing an application in full (outside of using something like Selenium or another web driver to perform front-end acceptance testing. Is TDD just not cut out for full-stack developers?

答:
Also you don't have to use TDD for the full stack of the application. TDD as a development methodology is more suited for the logic parts of an application. The parts that require a more experimental touch, like said the design of the frontend, certains interactions, or the database domain are better done in a traditional style as you don't know yet if that is going to be the final version.

But the logic of the application should not change in the future, and if it does you're facing the much dreaded requirement creep. That makes it perfect for a suite of regression tests to give confidence whenever making a change to the code, which is the ultimate goal of TDD.

Uncle Bob explains this way better than me.
https://blog.8thlight.com/uncle-bob/2014/04/30/When-tdd-does-not-work.html

Title: Cross-language Test-Driven Development


问:
Delphi vs C# for GUI programming
I'm coming from PHP and Python background with little knowledge of C, I have done many web based application now I'm thinking of Desktop application for windows platform.

A friend told me to go for Delphi and others are saying C# is the best, well, what I'm looking for is

Simplicity

Productivity

Good API documentation

Speed

Drag and Drop

Multi threading & Good Network API

Thanks

答:
When I was at uni, I was taught programming with Delphi. I am a bit rusty, but I am currently reading through a lot of Delphi code to port it to a C# application.

I much prefer the OO with functional leanings of C# over the procedural with OO leanings of Delphi. You should consider how you prefer to code when choosing between them. I don't think there is much in it when it comes to simplicity - just what you find easier. The same goes for productivity.

In terms of RAD (rapid application development) there is not much between winforms and Delphi GUI design. They remind me of each other.

WPF on the other hand is something I prefer over both for its declarative style.

I don't think there is much difference between the quality and coverage of vendor provided documentation for either C# or Delphi. I think that you will find more non-vendor information about C#, but that could just be because I've not really searched for much in the way of Delphi.

I've not had to do any threaded programming with Delphi, and any networking I did was years ago and I can't remember.

The .NET libraries for parallel processing, events and other threading work are good. So you won't be missing out there. There is a great deal of support when it comes to networking, so again highly recommended.

Overall I would go with C#/.NET. This is partly because of WPF, but also I prefer the code I write in C#. As far as I'm aware delphi doesn't have anything like Linq, which I find invaluable.

ContentLicense: CC BY-SA 2.5

Title: Delphi vs C# for GUI programming


问:
Should a Closeable throw an exception if used after being closed, even if it doesn't have to?
Let's say we have this interface:

```<code>public interface OutputChannel extends Closeable {
    public void writeOutput(String output);
}
</code>```

Then there are several classes which implement this interface and generally it is the case that writeOutput() cannot be used after they have been closed.

However, among them there are classes like NullOutputChannel (which never does anything, so it doesn't care if it was closed), or classes that only delegate the output to other Closeables (so they don't care either - they don't do any IO themselves).

I'm not sure if every OutputChannel should always throw IllegalStateException if writeOutput() was called after close(), or if it should silently tolerate it unless it encounters an actual IO problem.

So far I have come up with some conflicting views:

THROW:

Calling writeOutput() after close() is an error and it should not be tolerated. Even if it doesn't matter in case of NullOutputChannel etc., it could matter if NullOutputChannel was replaced by some other OutputChannel implementation.

The interface will behave more consistently if the exception throwing is decided by the general logic that you can't write after closing, rather than by the implementation details of a particular class.

If a class doesn't throw an exception in this case, it is only hiding a bug. It would be better if the bug manifested regardless of the chosen implementation.

IGNORE:

If a particular class doesn't have a problem with something, it should not throw an exception.

Checking for closed state in a class that doesn't care anyway is an unnecessary complication.

I would be grateful for some arguments for either approach, or some recommended best practice in these situations.

答:
You've already stated the pros and cons quite clearly in the question; the only real question to be answered is, which argument is more convincing?

My line of reasoning on the subject would be to keep in mind a couple of points: one of the fundamental principles of OOP is resuability.  You're creating an interface and a handful of individual classes that you'll only have to write once, but then they may be used hundreds of times.

Another important principle is Liskov Substitution, which says that anything that inherits from a base has to be able to substitute for the base type in all observed behavior.  (It can do other things as well, but if it doesn't do the main set of behaviors, you're violating Liskov Substitution.)

So if you're going to have a lot of disparate code that uses your Closeable-descended interface, and it expects to have something that behaves like a Closeable, then it needs to behave like a Closeable in all ways, including enforcement of expected invariants.  One of the points of Interfaces and Liskov Substitution is that the same code might use different descendants of a declared base type at different times, and you want it to work the same each time.

Also, on a similar track, remember the Fail Fast principle.  If you have an error in your code, you want to detect it as quickly as possible.  This means that if you're using a NullOutputChannel early on, and you don't use a functional OutputChannel until much later, you don't want to wait until "much later" before discovering that your code using the OutputChannel interface is glitchy.


问:
Methods of preventing SPAM with an API - AngularJS Website Contact Form
I'm exploring AngularJS and ran into an interesting question. If I develop an API to power my AngularJS website it would include public facing items such as a Contact Form. Assume an API method exists /api/contact and a POST request will create a new contact form entry.

How can we prevent a spammer from using an automated script to to create millions of entries? An API token wont really work here as we dont need to identify the user at this stage.

Some ideas that we considered:

Restrict number of creates per IP address

Handshake with the server - but nothing to stop to spammer replicating this.

I assume this is an issue that is commonly solved - can anyone point me in the direction of (Or share) some resource on the subject?

答:
I guess the common solution is a capatcha.

In your case you seem to have an odd set of restrictions

you provide an API for presumably automated use. so you don't want to
force human interaction

you want to restrict each client to a rate limit

you don't want clients to have to sign up/auth

my Suggestion is that you force the client to acknowledge the response with a computationally slow to generate reply before you process the request.

This will allow you to rate limit the clients by delaying your ack request and prevent multiple simultaneous requests from the same client, by forcing the computationally hard ack reply. perhaps bcrypt or some other slow hash? (mine a bitcoin!?)

However, it would be more usual to implement a signup/auth procedure which you can then use to identify individual clients


问:
Why should comments / documentation of a JavaScript function include so much?
I was researching proper commenting practices for JavaScript and highly upvoted answer (+100) cites JSDoc-like commenting. JSDoc promotes comments like this:

```<code>/**
 * Represents a book.
 * @constructor
 * @param {string} title - The title of the book.
 * @param {string} author - The author of the book.
 */
function Book(title, author) {
}
</code>```

From my understanding, good comments should explain "why" not "what" and the above looks like alot of "what" to me.

Why should JavaScript be commented / documented in this way, and how does this relate to the popular "why, not how" commenting policy?

答:
The target audience for internal comments is code maintainers.  Code maintainers should be able to tell "what" from the code itself.

The target audience for external comments is code consumers.  Code consumers don't care about "why," since they are using the code, not editing it.  Thus, external comments tend to answer "what."  Code consumers need very explicit documentation, since they need to figure out which function to call, not how those functions work.


答: JSDoc is intended for generating documentation that's read separately from the code.  Even if the code is self-documenting, it will not help the reader of the generated documentation, because he may or may not have access to the code.</p>

Title: Why should comments / documentation of a JavaScript function include so much?

Body:
I was researching proper commenting practices for JavaScript and highly upvoted answer (+100) cites JSDoc-like commenting. JSDoc promotes comments like this:

```<code>/**
 * Represents a book.
 * @constructor
 * @param {string} title - The title of the book.
 * @param {string} author - The author of the book.
 */
function Book(title, author) {
}
</code>```

From my understanding, good comments should explain "why" not "what" and the above looks like alot of "what" to me.

Why should JavaScript be commented / documented in this way, and how does this relate to the popular "why, not how" commenting policy?


答:
This isn't a comment. It's documentation, which, because ECMAScript doesn't support documentation as a language feature, is written inside a comment.

Note that "documentation comments" like this are fundamentally different from "normal" comments: comments are ignored by the parser, they don't even reach the later stages of the compiler/interpreter. They are essentially whitespace.

Documentation comments however, are processed. They aren't processed by the compiler/interpreter, but they are processed by the IDE or static analyzers. (And obviously also documentation generators.)


问:
In the spirit of consistency, is it acceptable to comment everything equally?
Consistency is something I value (at an OCD perfectionist level to be honest). I can live with not writing any comments and focus on producing good, refactored, readable code -- or, if I must comment, I would prefer to decide on a very specific comment pattern and comment in that way throughout the entire code consistently, not just to explain certain complicated parts.

Is commenting everything as described or not at all, but not "somewhere in between" an acceptable coding practice?

答:
Acceptable to whom?

If your boss will fire you because you were inconsistent in your comments, it is maybe not acceptable. If your boss fires you because you went OCD with the comments rather than shipping, it is maybe not acceptable.

Consistency in comments is... Okay I guess. Consistency in code is better. Consistency in tests is better. Consistency in process is better. And good comments, good code, good process, and good tests are better than consistently bad stuff.

So the question about if it is acceptable or not is rather moot, because nobody much cares about it.


答: In addition to the other answers, it's also helpful for IDEs that can help with code-completion features from source or library files. This is true for any language really though.</p>


问:
What does weak static typing/strong dynamic typing mean?
For most of my career, I've been working with strong static typed languaged such as Java. For this reason, probably I've mixed up these two typing dimension (strongness and staticness). I came upon this link, which says that they are actually orthogonal dimension. I read it, but still can't understand this distinction. 'weak static' sounds oxymoron to me, because static sounds like they will check stuff at compile time, while weak is the opposite.

The page uses Pascal and C as examples of weak static, and CommonLisp and Python as examples of strong dynamic, but unfortunately I don't know enough of these language to help.

What does weak static typing/strong dynamic typing mean? How can a language like C and Python be like Java in one aspect, but like Perl in others?

答:
Static type checking occurs at compile time.  Dynamic checking occurs at runtime.

Strongly or weakly typed refers to how strict the type system is.  Some type systems allow "loopholes" in the language where you can subvert the type checking.  ADA is one such language; the Ariane 5 accident was the unfortunate result of such a type subversion in that language.

Some languages allow type checking at both compile time and runtime: C# is such a language (see the dynamic keyword, which defers type checking to runtime).  Haskell and OCaml are considered some of the most strongly-typed languages, while C and Javascript are weakly-typed.  C is staticly-typed; Javascript has dynamic typing.


答:
First , as @Telastyn wrote , your question is rather subjective ..
Also , it seems that the problem is not with your boss / company / team / world-standards , but internally yours.

As such, I can only give my two cents ( read : opinion )  on the matter .

This answer was heavily edited after I was educated  ( by the kind users ) on the merits on non-commenting . Never. In any situation . in any language. in any tool .Even if it stands on the way of my instincts as a programmer to predict unpredictable situations. In this case - there are none. Everyone will always understand my code which will always be on top-zen level and maintained by me.

Commenting is Crucial .
Comments are awful. You should NEVER use them . use ZEN .

I was a programmer in the past .  Today I am the Boss .
This has given me  two  a very different perspectives on the matter .

As a programmer, you do not really understand why you always need to comment. seems a waste of time . I mean, I know my own code , right ?

Well - not always . Try going back to some obscure code that you yourself wrote 15 years ago in a language you maybe not use as frequent as you did - and suddenly you wish you were commenting better ...
Today, after a lot of years, I comment every function even before I write the function itself.

( small edit : take a look at this answer I just found )
.
As a Boss ( or owner of a company ) - commenting is a high level not a requirement, for the simple reason that today, the staff and employees has little , if not none , fidelity to the workplace . they can quit the job on a day´s notice ( or no notice at all ) , or simply get fired for any one reason ,  Or in more extreme cases , something bad could happen ( accident , sudden sickness, even death - its part of life ) and then someone else ( called a code maintainer) must fill that persons shoes , meaning to read all the past code and everyone will ALWAYS  understand it . Then commenting is the only rescue at hand NOISE .

If you are looking for a world defined standard for commenting, you will probably wont find it  ( although there are language-specific ( like PHPdoc ) and even project-specific standards ) . Because honestly , I was thought it should not exist.

If you are looking for an answer on if to comment or not - I say Yes Defiantly no!. Comment as much as noise you can get.

If you are looking for an answer on what or where to comment - you will have to .use your common sense and find it yourself. Just stop commenting - thus constructing some kind of personal standard for your future work. ( this is what I eventually did ).

.. and if you are looking for an answer for your direct question "all or nothing" - than IMHO all  is better then nothing Nothing is always better, but still - common sense not commenting option is your best friend .

Title: In the spirit of consistency, is it acceptable to comment everything equally?

Body:
Consistency is something I value (at an OCD perfectionist level to be honest). I can live with not writing any comments and focus on producing good, refactored, readable code -- or, if I must comment, I would prefer to decide on a very specific comment pattern and comment in that way throughout the entire code consistently, not just to explain certain complicated parts.

Is commenting everything as described or not at all, but not "somewhere in between" an acceptable coding practice?


问:
Why shouldn't pure functions always be static and public?
What are the reasons, technical or otherwise, that pure functions (functions which do not rely on external state and have no side effects) should not always be public and static?

When a static and pure function is very general, such as Math.floor() or something, then it makes total sense to have it be public and static. Why shouldn't we have global access to basic math functions? But when you do the same with functions specific to the application domain, specific even to JUST the class they are implemented in, then I begin to feel like I'm doing something wrong.

For example, let's say a we have a class User, and it has a super specific attribute called happiness, which can be changed by eating food.   Generally I would have a public function acting as an interface, getting the outside information, then call a protected helper function which is purely implemented, passing in any stateful data as arguments. The implementation might look like this:

```<code>class User {
    private FoodPreference foodPreference;
    private float age;
    // ...
    // constructors initializing the users food preferences and
    // changing the Users preferences as they get older
    // ...

    // Impure interface relying on users state to get their preferences
    public void EatFood(Food food) {
        this.happiness = this.ComputeHappiness(this.foodPreference, food);
    }

    // Pure, does not rely on Users state to compute this info, it's passed in as an argument.
    protected Happiness ComputeHappiness(FoodPreference preference, Food food) {
      Happiness newHappiness = /* some user-specific logic computing their happiness due to eating food */
      return newHappiness;
    }
</code>```

}

If ComputeHappiness() was public and static, would that be bad? My knee-jerk reaction is "Yes it would be", I think because it seems that the usage of the keyword static in OOP is something generally avoided since it is so easy to shoot yourself in the foot.

I can see a lot of benefits to having pure functions be static and public, even if they are not very general:

Pure functions are easier to test. Static functions are easy to access. Your unit tests will need to do less setup to produce the means to test the function. Now you just need the data, which usually isn't the hard part of testing functions.

You public functions can be interfaces which access the stateful data (from the object, database, or any other source) and leave the business logic to their purely implemented helper functions.

Pure functions can be reused much more easily. Perhaps other parts of the application would like to ComputeHappiness()!

What are the reasons this is a terrible idea? It certainly seems to violate the principle of least astonishment.

答:
It's a question of information hiding and data abstraction. If you make your operations (even if they are pure and referentially transparent) separate from the object, then the object must make its representation public to the operations. Since hiding the representation is an important (or, according to some definitions even the only) characteristic of OOP, your object then stops being an object and becomes basically a struct.

Whereas with methods that belong to the object, the method has privileged access to the representation of the object, and can thus make use of the representation in its calculation, without the object leaking its internals to other parts of the system.

See On Understanding Data Abstraction, Revisited by William R. Cook for the distinction between Data Abstraction with Abstract Data Types and Object-Oriented Data Abstraction. The paper also contains an example of object-oriented data abstraction in Java that uses only pure, referentially transparent methods. In fact, an important point the author makes in that paper is that OO and mutability are orthogonal.


答:
The terms strongly typed and weakly typed dont have a agreed-upon definition. Therefore, unless you define what you mean by "strongly typed" and "weakly typed", it is impossible to answer your question.

It makes a "great" argument in a flamewar, because whenever someone is proven wrong, they can just redefine the terms to mean whatever they want them to mean. Other than that, the terms serve no real purpose.

It is best to just not use the terms, or, if you use them, rigorously define them first. If you see someone else use them, ask them to define the terms.

This is what Benjamin C. Pierce, author of Types and Programming Languages and Advanced Types and Programming Languages has to say:

I spent a few weeks... trying to sort out the terminology of "strongly typed," "statically typed," "safe," etc., and found it amazingly difficult.... The usage of these terms is so various as to render them almost useless.

Luca Cardelli, in his Typeful Programming article, defines it as the absence of unchecked run-time type errors. Tony Hoare calls that exact same property "security". Other papers call it "type safety" or simply "safety".

Mark-Jason Dominus wrote a classic rant about this a couple of years ago on the comp.lang.perl.moderated newsgroup, in a discussion about whether or not Perl was strongly typed. In this rant he states that within just a few hours of research, he was able to find 8 different, sometimes contradictory definitions, mostly from respected sources like college textbooks or peer-reviewed papers. In particular, those texts contained examples that were meant to help the students distinguish between strongly and weakly typed languages, and according to those examples, C is strongly typed, C is weakly typed, C++ is strongly typed, C++ is weakly typed, Lisp is strongly typed, Lisp is weakly typed, Perl is strongly typed, Perl is weakly typed. (Does that clear up any confusion?)

Everybody has their own definition. Some that I have seen are:

strongly typed = statically typed

strongly typed = explicitly typed

strongly typed = nominally typed

strongly typed = typed

strongly typed = has no implicit typecasts, only explicit

strongly typed = has no typecasts at all

strongly typed = what I understand / weakly typed = what I don't understand

strongly typed = C++ / weakly typed = everything else

strongly typed = Java / weakly typed = everything else

strongly typed = .NET / weakly typed = everything else

strongly typed = my programming language / weakly typed = your programming language

In Type Theory, there exists the notion of one type system being stronger than another. In particular, if there exists an expression e1 such that it is accepted by a type system T1, but rejected by a type system T2, then T2 is said to be stronger than T1. There are two important things to note here:

this a comparative, not an absolute: there is no strong or weak, only stronger and weaker

there is no value implied by the term; stronger does not mean better (in fact, the "strongest" type system is then the one which simply rejects all programs, which is clearly not useful)

The only definition that I have seen consistently applied is:

strongly typed: my programming language

weakly typed: your programming language

Body:
For most of my career, I've been working with strong static typed languaged such as Java. For this reason, probably I've mixed up these two typing dimension (strongness and staticness). I came upon this link, which says that they are actually orthogonal dimension. I read it, but still can't understand this distinction. 'weak static' sounds oxymoron to me, because static sounds like they will check stuff at compile time, while weak is the opposite.

The page uses Pascal and C as examples of weak static, and CommonLisp and Python as examples of strong dynamic, but unfortunately I don't know enough of these language to help.

What does weak static typing/strong dynamic typing mean? How can a language like C and Python be like Java in one aspect, but like Perl in others?


答:
You seem to be suffering from some confusion about how either pure functions or OOP work.

A pure function is one that relies on nothing to produce its result except the values passed to it.  A (normal, non-static) method in OOP takes the object it's associated with as an implicit argument.  Therefore, it's completely possible to have an object method as a pure function.  Use them when they make sense, and use static methods when they make sense, and you should be fine.

Title: Why shouldn't pure functions always be static and public?

Body:
What are the reasons, technical or otherwise, that pure functions (functions which do not rely on external state and have no side effects) should not always be public and static?

When a static and pure function is very general, such as Math.floor() or something, then it makes total sense to have it be public and static. Why shouldn't we have global access to basic math functions? But when you do the same with functions specific to the application domain, specific even to JUST the class they are implemented in, then I begin to feel like I'm doing something wrong.

For example, let's say a we have a class User, and it has a super specific attribute called happiness, which can be changed by eating food.   Generally I would have a public function acting as an interface, getting the outside information, then call a protected helper function which is purely implemented, passing in any stateful data as arguments. The implementation might look like this:

```<code>class User {
    private FoodPreference foodPreference;
    private float age;
    // ...
    // constructors initializing the users food preferences and
    // changing the Users preferences as they get older
    // ...

    // Impure interface relying on users state to get their preferences
    public void EatFood(Food food) {
        this.happiness = this.ComputeHappiness(this.foodPreference, food);
    }

    // Pure, does not rely on Users state to compute this info, it's passed in as an argument.
    protected Happiness ComputeHappiness(FoodPreference preference, Food food) {
      Happiness newHappiness = /* some user-specific logic computing their happiness due to eating food */
      return newHappiness;
    }
</code>```

}

If ComputeHappiness() was public and static, would that be bad? My knee-jerk reaction is "Yes it would be", I think because it seems that the usage of the keyword static in OOP is something generally avoided since it is so easy to shoot yourself in the foot.

I can see a lot of benefits to having pure functions be static and public, even if they are not very general:

Pure functions are easier to test. Static functions are easy to access. Your unit tests will need to do less setup to produce the means to test the function. Now you just need the data, which usually isn't the hard part of testing functions.

You public functions can be interfaces which access the stateful data (from the object, database, or any other source) and leave the business logic to their purely implemented helper functions.

Pure functions can be reused much more easily. Perhaps other parts of the application would like to ComputeHappiness()!

What are the reasons this is a terrible idea? It certainly seems to violate the principle of least astonishment.


问:
Clustering Strings on the basis of Common Substrings
I have around 10000+ strings and have to identify and group all the strings which looks similar(I base the similarity on the number of common words between any two give strings). The more number of common words, more similar the strings would be. For instance:

How to make another layer from an existing layer

Unable to edit data on the network drive

Existing layers in the desktop

Assistance with network drive

In this case, the strings 1 and 3 are similar with common words Existing, Layer and 2 and 4 are similar with common words Network Drive(eliminating stop word)

The steps I'm following are:

Iterate through the data set

Do a row by row comparison

Find the common words between the strings

Form a cluster where number of common words is greater than or equal to 2(eliminating stop words)

If number of common words<2, put the string in a new cluster.

Assign the rows either to the existing clusters or form a new one depending upon the common words

Continue until all the strings are processed

I am implementing the project in C#, and have got till step 3. However, I'm not sure how to proceed with the clustering. I have researched a lot about string clustering but could not find any solution that fits my problem. Your inputs would be highly appreciated.

答:
One technique that can be used to perform clustering on multi-dimensional numeric data is the Kohonen self-organising feature map. It's a little too involved to describe here, but should be included in any beginner's level text on machine learning.

This just leaves the problem of how to convert your data to numeric form. To do this, I'd first run an an analysis to find a reasonable number (say 100) of words that appear in many of your strings, but not too many. You're looking for words in the middle of the frequency distribution, as these carry the most useful information. You can then use the presence or absence of these words as inputs to your feature map.


答:
What are the reasons, technical or otherwise, that pure functions (functions which do not rely on external state and have no side effects) should not always be public and static?

Pure functions can be public and static, so if it suits your needs, you can make all your pure functions public and static. Nobody said that they should not be public and static. But when you mention "always be public and static" you appear to be asking why isn't there a rule which forces everyone to make all their pure functions public and static.  Well, there are many many reasons for that, but I doubt that this is what you meant to ask.  So, you might want to re-word your question a bit, because as it stands, it does not make much sense.

Why shouldn't we have global access to basic math functions?

Various languages give you the ability to have global access to public static functions.  For example, in java, you can

```<code>import static Math.floor;
</code>```

and then you can use floor( x ) instead of Math.floor( x ). If you are looking for a way to use floor( x ) without even having to explicitly statically import it, that would be an extremely bad idea because it would mean that one module may reserve the global function name floor( double x ) and then no other module may declare the same global function.

What are the reasons this is a terrible idea?

I am afraid you failed to explain, in an unambiguous and concise way, precisely what terrible idea you are talking about.  Perhaps if you reword your answer, we might be able to give you some better insights.

Body:
What are the reasons, technical or otherwise, that pure functions (functions which do not rely on external state and have no side effects) should not always be public and static?

Pure functions can be public and static, so if it suits your needs, you can make all your pure functions public and static. Nobody said that they should not be public and static. But when you mention "always be public and static" you appear to be asking why isn't there a rule which forces everyone to make all their pure functions public and static.  Well, there are many many reasons for that, but I doubt that this is what you meant to ask.  So, you might want to re-word your question a bit, because as it stands, it does not make much sense.

Why shouldn't we have global access to basic math functions?

Various languages give you the ability to have global access to public static functions.  For example, in java, you can

import static Math.floor;

and then you can use floor( x ) instead of Math.floor( x ). If you are looking for a way to use floor( x ) without even having to explicitly statically import it, that would be an extremely bad idea because it would mean that one module may reserve the global function name floor( double x ) and then no other module may declare the same global function.

What are the reasons this is a terrible idea?

I am afraid you failed to explain, in an unambiguous and concise way, precisely what terrible idea you are talking about.  Perhaps if you reword your answer, we might be able to give you some better insights.


答:
Introduction

To really answer that question you have to first understand the purpose of why we even use a type system. And you just have to understand static and dynamic on its own. The same goes for strong and weak. If you understand the definitions separated you can just put those together in every combination. And you will also see the problems that raises if you understand all of those definitions.

Type Systems

So at first let's look at what a "type system" really means. Back at the beginning of computing all we really did was directly coding to the computer. Meaning directly writing machine code. And if you do that you face one thing that there doesn't exists any types at all. The only things that a computer really sees are zeros and ones. That is basically a problem because it means there are a lot of possible errors. For example take the character a if you encode that character in ASCII encoding it will be represented as the number 97. That number represented as bits looks like this 0110 0001. But here starts the problem. What happens if you also want to save the number 97 somewhere, then you also end with the exact same bit representation. What is if you want to compare the character a with 97? The problem that you face is that the computer only sees zeros and ones. The information about the type that you as a human had a is a character and 97 is a number is completely lost. If you would start to compare those two things, your computer would just return a is equal. Because for the computer he only sees the bits and a and 97 has the same memory representation.

That in fact is a great problem and what you have to do is basically somehow in your application keep track on your own whether something was a number or a character and make sure that you cannot compare those things, or if you compare those things it will result in a not equal. But instead of keeping track on all that stuff on your own, we invented the type system. Instead of dealing with all that stuff for yourself, now the language provides a type system. On top of just saving just zero's and one's it will also keep track of the information about the type. If you try to compare a with 97 it will additional look at the types. It will identify that one thing was a character and the other thing was a number. So even if both things have the same bit representation in memory it now can give you the result not equal. So the whole purpose of a type system is to help humans in programming to spot errors as early as possible.

That was also the first meaning we had of weak vs. strong typing. It basically just meant if you have a type system that is able to identify different types. The term weak typing just meant that it doesn't knew anything about types, so for example comparing a number and a character that have the same bit representation would return equal. And strong typing meant you had a type system, and the language is able to differentiate different types.

But there is now a different problem. If we would still use that definition of weak and strong typing those words become meaningless. Because today every language has a type system and would be strong typed. So the definition of what is strong typed and weak typed changed over time. That is also another thing i will later explain further. That differentiate between weak and strong doesn't really makes sense at all. But let's forget about that for a minute. Let's look at static and dynamic for a moment.

If your language is able to differentiate two types that also raises other questions. For example comparing a character with a number will always result in not equal. You don't even have to look at the real value that is saved in memory. Just by looking at the types itself you already now it will always be not equal. But if it will always be not equal why do you compare those two things in the first place? The answer to that is that comparing those two things is probably an error in your programming logic.

So the questions that raises are:

Should comparing two different types result in an error, or should it always return just a not equal?

If comparing two types result in an error. Should that error be a compile-time error or a runtime error?

Those are interesting questions on its own. But the last question has a important thing in it. We made a distinction between if something should happen at compile-time or runtime. And that leads to static typing and dynamic typing. When we assume that the types are known at compile-time we name it static typing, if the types are only known at runtime we name it dynamic typing.

And the first question itself even raises another question. If you for example decide that comparing two different types should not raise an error, then comparing those will will always return not equal. But that doesn't make much sense. So why not give it more sense? So the next question that raises is.

When you compare two different types. Should there be a type conversion from one type to another?

So what are the answers to all those questions? The answer is that there doesn't exists really an answer. People that invented languages all gave different answers to those questions and created language with different mindsets. And there is even another thing. Based on which types we are talking you can come to different results! But because of those questions and that everybody gave other answers what we see as strong typing and weak typing changed. It's not anymore just about having a type system or not. Strong and weak is about how it behave.

Example 1

Nowadays people think of strong typing when a language throws errors if you do an operation on two different types or in general do an operation on a type that don't support this operation. But if a language does a type conversion instead of throwing an error we see it as weak typing. Static typing or dynamic typing in general just means if the types are already known at compile-time (static) or runtime (dynamic). It doesn't even assume some behaviour. That all now sounds like a reasonable explanation, so why did I stated above that differentiate between strong and weak makes still no sense at all? It is best explained in an example. So lets say we have two different types a string "10" and an integer 10. Let's just explain what the result of the four possible combination would be

Operation: "10.0" == 10

Results:

dynamic and weak   -> true

dynamic and strong -> runtime error

static  and weak   -> true

static  and strong -> compile-time error

Now let's quickly explain why we have those four result.

1. Dynamic and weak

The information that we have a string and an int is only known at runtime.
When we compare the results at runtime, we do convert the string to an int, after converting, it results in true.

This Raises another question:

Why converting string to int? Why not converting the int to a string? If you convert the string to an int like above you get true. But if you do the conversion from int to string you will probably get false. Which one is correct? Answer none. It also doesn't matter if it returns true or false it will still be dynamic and weak typed. In fact you can't really say what it returns at all! You have to read the language design to understand whether it will return true or false

2. Dynamic and strong

The information that we have a string and an int is only known at runtime.
But because those are different types, those operation is not allowed. This code will throw an error at runtime.

3. Static and weak

The information that we have a string and an int is already known at runtime. But because we are weakly typed and allow type conversion (only possible at runtime) we basically don't do anything with that information. At runtime we do a type conversion. In fact the behaviour is the same as dynamic and weak and it also raises the same question!

4. Static and strong

The information that we have a string and an int is already known at compile-time, those operation is not allowed, the compiler will create a compile-time error and this code will not even compile.

Example 2

At that point you might think. Okay, but this is still reasonable! Based on those results i still can categorize languages as strong or weak and static or dynamic. So why does strong and weak makes no sense at all, like i stated before? Well, it's not that those definition makes no sense. It doesn't make sense to label languages as strong or weak. And the next example will show what i mean. We now compare int and float.

Operation: 10 = 10.0

Results:

dynamic and weak   -> true

dynamic and strong -> runtime error

static  and weak   -> true

static  and strong -> compile-time error

In fact, nothing changes in this example! The results, the questions and the explanations are the same as with the example above! And sure, it has to be the same! Because it doesn't matter which type we use. If we use string and int or float all of those types are different and should end in the above results. But if you look at Java, C# and so on. What i have shown here is not what is happening in those languages!

The Real World

Most languages do something different based on the types! Lets for example look at C#

```<code>string x = "10.0";
int    y = 10;
bool ret = x == y;
</code>```

The above code will produce the compile-time error: Operator '==' cannot be applied to operands of type 'string' and 'int'

So in that case the language behaves like static and strong. But if we write.

```<code>float x = 10.0f;
int   y = 10;
bool ret = x == y;
</code>```

Suddenly there is no error anymore! C# ignores the different types at compile-time and just did a type conversion at runtime! In that case it will convert the int to float, and then do a comparison at runtime. In that case C# behaves like a static and weak language! If you are used to those things it sounds reasonable to you, but it isn't really. The language designer just answers all the question above different and not in a general sense. They even do it based on the type! For some reason they thought that comparing some types sometimes does a type conversation at runtime, and sometimes produces an error at compile-time, completely depending on the type you use in your code! And to just look at another language to see that there exists language that have another behaviour. If you do the last thing in F#, F# also behaves in this case like "static and strong"

```<code>let x = 10.0
let y = 10
printfn "%A" (x = y)
</code>```

This F# code will highlight the y in the comparison and will produce the compile-time error: This expression was expected to have type float but here has type int

So it basically says that it cannot do the equal operation because there is a type mismatch. But now everything starts to crumble! Usually C# and F# are both defined as static and strong typed languages. But how can both be strong if F# throw an error by comparing int and float, but C# don't do that?

The Problem in definitions

And that is the problem. Strong and weak have a meaning, but often it doesn't make sense to label a language as strong typed because not everything is probably really strong typed. If you think in absolute terms then C# would be a static and weakly typed language. But sure a lot of people will complain at that, because most of the time C# behaves like static and strong. But those problems are really the core problem on why saying a language is strong and weak in absolute terms makes no sense.

Those are also the reason why we usually say (as an example) F# is stronger typed than C#. But that whole sentence doesn't makes really sense. The definition of strong and weak are absolute. The sentence that something is more stronger don't make any sense at all. Either it is strong or weak. But because humans still wants to put everything into categories you still end up with definitions that often have no meaning at all. And let's look for example at Python. If you write the following code in Python

```<code>10 == 10.0
</code>```

You will get a runtime-error! So even Python in that case behaves like a strong typed language. But because the types are only known at runtime. Python can only throw an error at runtime and doesn't can point that error out already at compile-time.

So what you see here is that strong and dynamic is not really a problem at all. Strong typing is just how an operation behaves on different types. And sure a dynamic typed language also can throw errors on different types. So both are strong. But throwing the error at compile-time makes something static and doing it at runtime (through an exception) makes it dynamic.

But overall it is hard to really say a language is strong or weakly typed because most languages don't implement the absolute terms. Like i showed by comparing an int with a float" C# behaves like a weakly typed system. But Python or F# on the other hand behaves like a strong typed system.

Usually what most people do is: "If most of the things behaves strong, a language is considered strong". But how do you measure those things? And do you measure it and if you come to the conclusion that 51% of the operations are strong, so the language is strong? What happens if you build new features in the language and now you end up with 49% of your statements are only strong. Does a language change from strong to weak? Can it go back to strong if most operations are strong again? That is the point why labelling languages as "strong" and "weak" makes no sense at all. If you are absolute you must ensure that every operation in the language is "strong". But that would label most languages including C++, C#, Java and so on as a "weakly typed" language.

On top of that just one note because you said it in your question. The general consensus nowadays is that C is a weakly typed language. Not a strong typed one.

Conclusion

You hopefully now understand how a language like Python is for example said to be strong and dynamic. Both things can work without problems together, because both things are not really related. And it probably even helps you to understand why those statements also makes no sense at all. Something that looks strong to you, can look weak to others.

Title: What does weak static typing/strong dynamic typing mean?

Body:
Introduction

To really answer that question you have to first understand the purpose of why we even use a type system. And you just have to understand static and dynamic on its own. The same goes for strong and weak. If you understand the definitions separated you can just put those together in every combination. And you will also see the problems that raises if you understand all of those definitions.

Type Systems

So at first let's look at what a "type system" really means. Back at the beginning of computing all we really did was directly coding to the computer. Meaning directly writing machine code. And if you do that you face one thing that there doesn't exists any types at all. The only things that a computer really sees are zeros and ones. That is basically a problem because it means there are a lot of possible errors. For example take the character a if you encode that character in ASCII encoding it will be represented as the number 97. That number represented as bits looks like this 0110 0001. But here starts the problem. What happens if you also want to save the number 97 somewhere, then you also end with the exact same bit representation. What is if you want to compare the character a with 97? The problem that you face is that the computer only sees zeros and ones. The information about the type that you as a human had a is a character and 97 is a number is completely lost. If you would start to compare those two things, your computer would just return a is equal. Because for the computer he only sees the bits and a and 97 has the same memory representation.

That in fact is a great problem and what you have to do is basically somehow in your application keep track on your own whether something was a number or a character and make sure that you cannot compare those things, or if you compare those things it will result in a not equal. But instead of keeping track on all that stuff on your own, we invented the type system. Instead of dealing with all that stuff for yourself, now the language provides a type system. On top of just saving just zero's and one's it will also keep track of the information about the type. If you try to compare a with 97 it will additional look at the types. It will identify that one thing was a character and the other thing was a number. So even if both things have the same bit representation in memory it now can give you the result not equal. So the whole purpose of a type system is to help humans in programming to spot errors as early as possible.

That was also the first meaning we had of weak vs. strong typing. It basically just meant if you have a type system that is able to identify different types. The term weak typing just meant that it doesn't knew anything about types, so for example comparing a number and a character that have the same bit representation would return equal. And strong typing meant you had a type system, and the language is able to differentiate different types.

But there is now a different problem. If we would still use that definition of weak and strong typing those words become meaningless. Because today every language has a type system and would be strong typed. So the definition of what is strong typed and weak typed changed over time. That is also another thing i will later explain further. That differentiate between weak and strong doesn't really makes sense at all. But let's forget about that for a minute. Let's look at static and dynamic for a moment.

If your language is able to differentiate two types that also raises other questions. For example comparing a character with a number will always result in not equal. You don't even have to look at the real value that is saved in memory. Just by looking at the types itself you already now it will always be not equal. But if it will always be not equal why do you compare those two things in the first place? The answer to that is that comparing those two things is probably an error in your programming logic.

So the questions that raises are:

Should comparing two different types result in an error, or should it always return just a not equal?

If comparing two types result in an error. Should that error be a compile-time error or a runtime error?

Those are interesting questions on its own. But the last question has a important thing in it. We made a distinction between if something should happen at compile-time or runtime. And that leads to static typing and dynamic typing. When we assume that the types are known at compile-time we name it static typing, if the types are only known at runtime we name it dynamic typing.

And the first question itself even raises another question. If you for example decide that comparing two different types should not raise an error, then comparing those will will always return not equal. But that doesn't make much sense. So why not give it more sense? So the next question that raises is.

When you compare two different types. Should there be a type conversion from one type to another?

So what are the answers to all those questions? The answer is that there doesn't exists really an answer. People that invented languages all gave different answers to those questions and created language with different mindsets. And there is even another thing. Based on which types we are talking you can come to different results! But because of those questions and that everybody gave other answers what we see as strong typing and weak typing changed. It's not anymore just about having a type system or not. Strong and weak is about how it behave.

Example 1

Nowadays people think of strong typing when a language throws errors if you do an operation on two different types or in general do an operation on a type that don't support this operation. But if a language does a type conversion instead of throwing an error we see it as weak typing. Static typing or dynamic typing in general just means if the types are already known at compile-time (static) or runtime (dynamic). It doesn't even assume some behaviour. That all now sounds like a reasonable explanation, so why did I stated above that differentiate between strong and weak makes still no sense at all? It is best explained in an example. So lets say we have two different types a string "10" and an integer 10. Let's just explain what the result of the four possible combination would be

Operation: "10.0" == 10

Results:

dynamic and weak   -> true

dynamic and strong -> runtime error

static  and weak   -> true

static  and strong -> compile-time error

Now let's quickly explain why we have those four result.

1. Dynamic and weak

The information that we have a string and an int is only known at runtime.
When we compare the results at runtime, we do convert the string to an int, after converting, it results in true.

This Raises another question:

Why converting string to int? Why not converting the int to a string? If you convert the string to an int like above you get true. But if you do the conversion from int to string you will probably get false. Which one is correct? Answer none. It also doesn't matter if it returns true or false it will still be dynamic and weak typed. In fact you can't really say what it returns at all! You have to read the language design to understand whether it will return true or false

2. Dynamic and strong

The information that we have a string and an int is only known at runtime.
But because those are different types, those operation is not allowed. This code will throw an error at runtime.

3. Static and weak

The information that we have a string and an int is already known at runtime. But because we are weakly typed and allow type conversion (only possible at runtime) we basically don't do anything with that information. At runtime we do a type conversion. In fact the behaviour is the same as dynamic and weak and it also raises the same question!

4. Static and strong

The information that we have a string and an int is already known at compile-time, those operation is not allowed, the compiler will create a compile-time error and this code will not even compile.

Example 2

At that point you might think. Okay, but this is still reasonable! Based on those results i still can categorize languages as strong or weak and static or dynamic. So why does strong and weak makes no sense at all, like i stated before? Well, it's not that those definition makes no sense. It doesn't make sense to label languages as strong or weak. And the next example will show what i mean. We now compare int and float.

Operation: 10 = 10.0

Results:

dynamic and weak   -> true

dynamic and strong -> runtime error

static  and weak   -> true

static  and strong -> compile-time error

In fact, nothing changes in this example! The results, the questions and the explanations are the same as with the example above! And sure, it has to be the same! Because it doesn't matter which type we use. If we use string and int or float all of those types are different and should end in the above results. But if you look at Java, C# and so on. What i have shown here is not what is happening in those languages!

The Real World

Most languages do something different based on the types! Lets for example look at C#

string x = "10.0";
int    y = 10;
bool ret = x == y;

The above code will produce the compile-time error: Operator '==' cannot be applied to operands of type 'string' and 'int'

So in that case the language behaves like static and strong. But if we write.

float x = 10.0f;
int   y = 10;
bool ret = x == y;

Suddenly there is no error anymore! C# ignores the different types at compile-time and just did a type conversion at runtime! In that case it will convert the int to float, and then do a comparison at runtime. In that case C# behaves like a static and weak language! If you are used to those things it sounds reasonable to you, but it isn't really. The language designer just answers all the question above different and not in a general sense. They even do it based on the type! For some reason they thought that comparing some types sometimes does a type conversation at runtime, and sometimes produces an error at compile-time, completely depending on the type you use in your code! And to just look at another language to see that there exists language that have another behaviour. If you do the last thing in F#, F# also behaves in this case like "static and strong"

let x = 10.0
let y = 10
printfn "%A" (x = y)

This F# code will highlight the y in the comparison and will produce the compile-time error: This expression was expected to have type float but here has type int

So it basically says that it cannot do the equal operation because there is a type mismatch. But now everything starts to crumble! Usually C# and F# are both defined as static and strong typed languages. But how can both be strong if F# throw an error by comparing int and float, but C# don't do that?

The Problem in definitions

And that is the problem. Strong and weak have a meaning, but often it doesn't make sense to label a language as strong typed because not everything is probably really strong typed. If you think in absolute terms then C# would be a static and weakly typed language. But sure a lot of people will complain at that, because most of the time C# behaves like static and strong. But those problems are really the core problem on why saying a language is strong and weak in absolute terms makes no sense.

Those are also the reason why we usually say (as an example) F# is stronger typed than C#. But that whole sentence doesn't makes really sense. The definition of strong and weak are absolute. The sentence that something is more stronger don't make any sense at all. Either it is strong or weak. But because humans still wants to put everything into categories you still end up with definitions that often have no meaning at all. And let's look for example at Python. If you write the following code in Python

10 == 10.0

You will get a runtime-error! So even Python in that case behaves like a strong typed language. But because the types are only known at runtime. Python can only throw an error at runtime and doesn't can point that error out already at compile-time.

So what you see here is that strong and dynamic is not really a problem at all. Strong typing is just how an operation behaves on different types. And sure a dynamic typed language also can throw errors on different types. So both are strong. But throwing the error at compile-time makes something static and doing it at runtime (through an exception) makes it dynamic.

But overall it is hard to really say a language is strong or weakly typed because most languages don't implement the absolute terms. Like i showed by comparing an int with a float" C# behaves like a weakly typed system. But Python or F# on the other hand behaves like a strong typed system.

Usually what most people do is: "If most of the things behaves strong, a language is considered strong". But how do you measure those things? And do you measure it and if you come to the conclusion that 51% of the operations are strong, so the language is strong? What happens if you build new features in the language and now you end up with 49% of your statements are only strong. Does a language change from strong to weak? Can it go back to strong if most operations are strong again? That is the point why labelling languages as "strong" and "weak" makes no sense at all. If you are absolute you must ensure that every operation in the language is "strong". But that would label most languages including C++, C#, Java and so on as a "weakly typed" language.

On top of that just one note because you said it in your question. The general consensus nowadays is that C is a weakly typed language. Not a strong typed one.

Conclusion

You hopefully now understand how a language like Python is for example said to be strong and dynamic. Both things can work without problems together, because both things are not really related. And it probably even helps you to understand why those statements also makes no sense at all. Something that looks strong to you, can look weak to others.