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

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

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

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

Both types of assertion messages could be replaced by comments.

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

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

答:
Users should never see assertion errors (uncaught exception in
  general) and therefore the assertion message does not need to describe
  what went wrong.

In a lot of contexts, assertions are best used for spotting bugs (programmer errors) -- things that should never happen. They're ideally caught in internal testing before they reach the hands of the user (and often serve that purpose of spotting more issues upfront during internal testing instead of leaking the issues to the users). They're different from exceptional control flow which is typically the result of an external error outside of the programmer's control (trying to load a corrupt file, e.g.) and not actually a bug.

In the unlikely (but not always impossible) event that they can and do end up reaching the user, it should be obvious what kind of assertion failure message looks less horrid to an ordinary user.

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

Maybe it'd help to run into more assertion failures?

As an example, I might run a debug build of an application in a team environment after acquiring new hardware and drivers and run into an assertion failure like:

"Failed to allocate vertex buffer object!".

Aha! Instantly I know the problem is in the GPU code. That might not even be my responsibility, it might be Fred's code. Now I can just bounce the issue to Fred without even studying his source code.

If I'm in control of the code, it still tends to give me a lot of information about what happened at a glance which can be quite soothing.

The alternative with comments is to dig into the source code, to the exact line of code and source file in which the assertion failed, and then read the comments, with an assertion failure message like:

Assertion failure in some_path/something/some_source.ext: 119: assert(success).

And even that little moment of suspense where you now dig into that cited source file and go to the specified line number to try to figure out what the hell happened can be quite stressful, especially since assertions are never supposed to fail (but still do sometimes anyway, making them really unpleasant surprises).

In general it's a lot more stressful to me if I enter my apartment with the lights off and people just start yelling "RARRRRRGH!" at the top of their lungs before singing happy birthday. It's far less stressful if they skip that part and just start singing happy birthday. "Phew, that's why they surprised me!"

I'd say it's quite a stress reliever at the very least to see more information relating to why an assertion failed immediately in the same sense without digging into the source file where it occurred after getting that jolting surprise.

In the same sense, if your code fails to compile, you don't want to have to go look up a specific line number of an external file containing documentation to get even a remotely human description of why the compilation failed. It's far more relaxing to know the issue sooner and get at least a little bit more information about why this unanticipated failure occurred as quickly as possible since it'll leave you in a pretty foul mood otherwise. Imagine if compilation errors showed you a hex dump followed by a citation of a specific line number of an external document file through which you can look up the cause of the error.

For fail messages, I'd say the most soothing information is often contextual information giving you a good clue as to where the failure occurred (from a high-level standpoint that doesn't require looking at a specified line number of a specified source file) and not merely why it occurred, since that's typically the first gut reaction when encountering an annoying assertion failure ("Where the hell did that happen?" which can sometimes be an even more immediate concern than why it happened).

Title: Purpose of assertion messages


问:
What is the most efficient way to implement a RESTful client app?
I am working on a web application for ranking some products based on some factors.

The user send a search query to 5 restful webservices which by their turn send a response in a JSON format and sometimes in an XML format (responses are not structured the same way, since webservices are different) . I choosed to reformat everything to a special json structure so I can use it .

My current problem is that I don't know which way should I implement this app, which is basically a REST client interfering with other web services .

The Server Approach :

The first way I had in mind is to use a Server side implementation (using python and flask) to send an HTTP request and recieve a response, "ReEncode" everything into a structured json format and send it back to the client which will render it .

Here are the steps of things should work using this approach :

Client send a request to my server containing the search query

My server will reformat the request to create an HTTP request for each web services

The server send the request to these RESTful services and get back an HTTP response from each server .

The server decode those responses to a special data structure I made, then it applies all the ranking and processing logic to it .

The server re-encode everything to json format and send it back to the clients .

The client browser reparse and render the json response !

The Client Side Approach:

The seconde way to create this app is to do all the HTTP communication,data processing,parsing and rendering on a Client side, sure nothing here is really client side, since the app will have to communicate with webservices.

The steps for this approach are as following :

Client type the search keywords (the search Query)

Browser clients create an http request (using the the search Query and API keys) and send it directly to the web services .

Client browser decode the response (json/xml formatted) and creates native objects that I need to use .

Process the decoded data (ranking,filtering...)

Re encode everything to a structured json format

Render everything .

This approach will use only JS and some frameworks .

The Question : Which way is more efficient and quick to set up?

Thing to consider :

I have a limited knowledge of python and js.

This is a part time project .

I need to finish it in less than a month .

That's my first web application (but not my first programming project, I've made softwares and games before )

答:
The client-side approach will have the least development time, because you only need to develop one layer (the client). If you would follow the server-side approach, you would have to develop the client and the server. Maybe the number of lines of code would not differ very much, but with the client-side approach you will only have to deal with one program and one programming language. Debugging will be easier, also because there is only one thread.

If I understand you correctly, you are not concerned with the long-term impact of your choice, so I don't consider that in my answer.

ContentLicense: CC BY-SA 3.0


问:
How does C# remove duplicate instances of static data of constructed types?
Unlike Java, C# does not share static data among entire generic type, but per each constructed type (i.e. Array<int>, Array<string> and so on). Creating those instances does not seem a problem, but if I am not mistaken removing duplicate instances could be a problem (similar case was a problem for C++).

Thus my question -- how does C# remove duplicate instances of static data of constructed types?

答:
It does not.

Static variables are lazily created/initialized on or before first use (practically, on first use, but if I remember correctly the standard doesn't require that). Since there is only one (unless threadlocal), the runtime only makes one.


问:
How can we be certain that the lower components of computer programming like compilers, assemblers, machine instructions, etc. are flawless?
Since we are becoming more and more reliant on computing, including very critical tasks of day-to-day life, I was just wondering how those vital components are tested.

More technically, how are the compilers and assemblers tested? (I suppose this relates to the halting problem!!)

答:
To show that the underlying systems are flawless you either

a) Need to proof they are flawless

Mathematical proof

Only realistically possible for trivial programs

b) Make an exhaustive test

Only possible for trivial programs and some simple programs

As soon as a timing element enters the test it is not possible to make an
exhaustive test as time can be indefinitely divided.

Beyond the trivial programs the possible execution options explode exponentially.

In software testing the exhaustive test is only used in unit testing of some simple functions.

Example:
You want to test a 8 character utf-8 input to some field, you make the choice to cut the input at 8 times the maximum length 6 of utf-8 in bytes which gives 8*6=48 bytes to actually have a finite amounts of possibilities.

You could now think you only need to test the 1,112,064 valid code points of each of the 8 character, ie. 1,112,064^8 (say 10^48) tests (which is already unlikely be possible), but you actually have to test each value of each of the 48 bytes or 256^48 which is around 10^120 which is the same complexity as chess compared to the total number of atoms in the universe of roughly 10^80.

Instead you can use, in increasing order of effort and each test should cover all the previous:

a) test a good and a bad sample.

b) code coverage, ie. try to test every line of code, which is relative simple for most code. Now you can wonder what the last 1% of the code you can't test is there ... bugs, dead code, hardware exceptions etc.

c) path coverage, all outcomes of all branches in all combinations are tested. Now you know why the test department hates you when your functions contains more than 10 conditions. Also you wonder why the last 1% can't be tested ... some branches are depended on the previous branches.

d) data test, test a number of sample with border value, common problematic values and magic numbers, zero, -1, 1, min +/-1, max +/-1, 42, rnd values. If this doesn't give you path coverage you know you haven't caught all the values in your analysis.

If you already do this you should be ready for ISTQB foundation exam.


问:
Should a RESTful API be able to return files, or just a location
This has been puzzling me for a while.

For example, we have a REST API that provides basic content to a system, consuming and producing JSON. At this endpoint it produces a URL to a picture and a description, and is found like thus: //localhost/myApi/pictures/1

```<code>{
    id: 1,
    description: "This is a pretty picture of a daisy",
    URL: <OUR URL>
}
</code>```

Now the OUR_URL should this point to a location on the API for example //localhost/myApi/files/pictures/1 which returns a JPG (the application behind the API reads the physical content of the file and then streams it back to the client). This is obviously different to the rest of the API which is producing JSON responses and there will be overhead from the reading and streaming of the actual file.

Alternatively should OUR_URL point to a URL outside the scope of the REST service, so //localhost/files/pictures/1.jpg where it reads the file directly.

So the question is:

Should a RESTful API be able to return files, or just a location?

答:
A RESTful service should provide resources to the users of the API. Resources can have various formats, which ranges from JSON or XML to JPEG and HTML.

There is not even a requirement, or even expectation, that a single API serves only resources of a single format. There is nothing wrong with serving a JSON document on the URI /myApi/pictures/1 and a JPEG file form the URI /myApi/files/pictures/1.

In a more extreme case, it is even possible to serve both the JSON description and the JPEG file from the same URL, depending on the format that the requester asks for.


答:
One problem you'll have in just returning URIs is that a plain old file server can't do security. So if you need to do any sort of limitation on who can access a file, then you're going to need to be able to return it in the REST API directly (or not, if the user does not have rights, the file is not in the correct state, etc.).

Otherwise, returning the plain old URI and letting that go to a dedicated CDN has a lot of benefits around provisioning, simplicity, and scalability - assuming that's all you need to do.

Body:
This has been puzzling me for a while.

For example, we have a REST API that provides basic content to a system, consuming and producing JSON. At this endpoint it produces a URL to a picture and a description, and is found like thus: //localhost/myApi/pictures/1

```<code>{
    id: 1,
    description: "This is a pretty picture of a daisy",
    URL: <OUR URL>
}
</code>```

Now the OUR_URL should this point to a location on the API for example //localhost/myApi/files/pictures/1 which returns a JPG (the application behind the API reads the physical content of the file and then streams it back to the client). This is obviously different to the rest of the API which is producing JSON responses and there will be overhead from the reading and streaming of the actual file.

Alternatively should OUR_URL point to a URL outside the scope of the REST service, so //localhost/files/pictures/1.jpg where it reads the file directly.

So the question is:

Should a RESTful API be able to return files, or just a location?


问:
In a byte, each additional bit doubles the representable states, but does it double memory?
A friend asked me whether adding a single bit more memory doubles the amount of memory you have, as the bit doubles the amount of representable states.

My brain got stuck thinking about it.

Doubling the amount of bits doubles the amount of states we can simultaneously represent.

Am I performing a category error. What does it mean to double memory?

答:
It is a linear increase in memory and an exponential increase in representational state.

Each additional bit is an additional multiplicand of 2 in the number of possible values, thus moving to the next power of 2.

```<code>0 (2^1 values: 2)
00 (2^2 values: 4)
000 (2^3 values: 8)
0000 (2^4 values: 16)
00000 (2^5 values: 32)
</code>```

Doubling memory usually means doubling the number of memory addresses that an application uses, or doubling the amount of RAM used. It doesn't mean doubling the number of possible values.

Calculating the number of possible values that a piece of memory can represent is easy: 2^n where n is the number of bits in that piece of memory.

The number of possible values in a 32 int variable is 2^32 = 4,294,967,296 possible values. To "double" that memory is to use a 64 bit long, which has 2^64 values: 1.8446744e+19.

Body:
It is a linear increase in memory and an exponential increase in representational state.

Each additional bit is an additional multiplicand of 2 in the number of possible values, thus moving to the next power of 2.

0 (2^1 values: 2)
00 (2^2 values: 4)
000 (2^3 values: 8)
0000 (2^4 values: 16)
00000 (2^5 values: 32)

Doubling memory usually means doubling the number of memory addresses that an application uses, or doubling the amount of RAM used. It doesn't mean doubling the number of possible values.

Calculating the number of possible values that a piece of memory can represent is easy: 2^n where n is the number of bits in that piece of memory.

The number of possible values in a 32 int variable is 2^32 = 4,294,967,296 possible values. To "double" that memory is to use a 64 bit long, which has 2^64 values: 1.8446744e+19.


问:
Question regarding the names of OrderedDict and defaultdict functions in Python
While reading Python Cookbook I came across these two lines:

```<code>    from collections import OrderedDict
    from collections import defaultdict
</code>```

Now see the naming conventions of the functions in these lines. The first one has CamelCase and the second one has all small caps.

Why are these two named in different style?

I have researched about it on the Internet and frankly I've not found what I was looking for.

答: In Python, builtin types are named in lowercase (str, int, dict), while custom types (the classes you write yourself) use camel case. Extra types that are included in the standard library until 2.6 are named as if they were builtin types. Later inclusions (2.7 and 3.*) are named as if they were custom types. I don't know why the change, but they kept the old names for the existing types because of backwards compatibility.


答:
It doubles the amount of memory locations you can address.  Perhaps that's where you are getting confused.  This is why computers are now mostly 64-bit.  In a 32-bit system, the memory was bounded at 4GB.  With a 64-bit addresses we can use much much more.

If I have a 1 bit memory, adding one bit doubles my memory.  If i have a 2 bit memory, adding a bit only adds 50%.  That's the other (less useful) way to answer it.

Title: In a byte, each additional bit doubles the representable states, but does it double memory?

Body:
A friend asked me whether adding a single bit more memory doubles the amount of memory you have, as the bit doubles the amount of representable states.

My brain got stuck thinking about it.

Doubling the amount of bits doubles the amount of states we can simultaneously represent.

Am I performing a category error. What does it mean to double memory?


问:
How do you organize API endpoint contracts
Where trying to improve the "confidence" we have in our inter-service communication.

Background:
"Contracts" has been a matter of sharing a piece of code that defines an interface to implement, but over the years, the shared code changed, and a lot of different implementations (soap, msmq, rest etc.) sprouted up, which could all be said to implement the same interface, but in no way plays well together, whithout mapping, which caused a forest of "mapping" microservices to be implemented, which again, appears in different version. Development and Operations are both suffering from this.

Intention: I would like to define contracts for the endpoints on the outside, using something like Swagger or API blueprint. With swagger i can compare the swagger.json "contract" with the swagger.json for the service claiming to implement it, and with API blueprint, theres "dredd". For MSMQ based transports, we'll need some other approach, but i think contracts for the structure inside the messages could/should be conformed to for the same reasons as the http-endpoints.

The details about how to verify is not the question - the question is: How would you organize these contracts? Should we have an internal repository of contracts that can never be changed, but only occur in new versions, and then have the verification-process be told which contracts are (supposedly) implemented? Said contract-repo should be read-accessible by our verification-process, and to our (and external) developers...

Any inputs regarding the problems described in the background is appreciated, maybe I'm looking the wrong way for a solution?

答:
The simplest solution IMO would be to utilize Pull Requests and good automated test coverage. It is a paradigm shift for those who are not used it but the the benefits are undeniable.

Github has some good docs: https://help.github.com/articles/creating-a-pull-request/ as does BitBucket: https://www.atlassian.com/git/tutorials/making-a-pull-request/

PRs only work when the entire team is on board. When a new PR is submitted, all developers except those on the critical path should stop what they are doing and take a few minutes to review the PR and leave comments like: this code will break the current contract for the Xyz method, please revisit or looks good. Many developers will simply leave a +1 if they think the code should be merged. Once you get enough eyes and approvals on the code it can be merged into the development branch.

In addition I would definitely make sure the team maintains good automated tests.

If you don't use git, Github or BitBucket and are unable or unwilling to change...

You could approach this in a couple different ways:

An internal system: This would generate and serve up API/Endpoint documentation based on method signatures and comments. You could use an automated tool to generate the documentation in HTML format. The problem with this is that the developers can easily change the contracts (method signatures) and commit that code which breaks things. The benefit would be virtually zero maintenance and a readable/searchable interface for developers to discover existing endpoint contracts.

An external system: This sounds more like what you want. You could do this in several different ways. One way would be to use a documentation tool like Yard to generate the current baseline docs, then assign the task of modifying them whenever a contract needs to change. Doing it this way would allow you to setup a separate (external) web stack as a service. Another way would be to build a separate app that models the functionality you desire. It would have Klass and Method models. The disadvantage would be that someone would have to maintain it. The advantage would be that developers could not easily change the contracts, or at all if you restrict access to the code.

Based on your use cases above, I would tend to go with a separate app. You could have a maintenance interface for a Team Lead or Admin to change a contract and version of the API/Endpoint. You could also have a read-only interface for developers to lookup things.

Workflow:

Bug arrives at developers desk.

Developer finds the root of the problem in a particular method.

Developer looks up the method on the external contract site and discovers that the return value needs to change which will break the contract.

Developer brings the discovery to the Team Lead or change control board

Team Lead assigns developer to also modify the code that will break due to the change, accordingly

Developer writes code to fix the bug (and hopefully automated tests)

At this point the developer should be running a full regression test suite to make sure none of the new code has broken anything unexpected.

Developer commits the (tested) bug fix


问:
Testing using mocking, must I mock all dependencies too?
I have the following method to test:

```<code>public List<MarkId> getMarkIdList(ICar carDoc) {

    ICourseCar courseCarDoc = courseCarRep.get(carDoc);

    List<MarkWag> markWagList = courseCarDoc.getMarks();

    List<Integer> markIdList = new ArrayList<>();

    for (MarkWag markWag : markWagList)
        markIdList.add(markWag.getMarkId());

    List<ICourseMark> courseMarkDocList = courseMarkRep.getList(markIdList);

    List<MarkId> markIds = new ArrayList<>();

    for (ICourseMark courseMark : courseMarkDocList)
        markIds.add( new MarkId(courseMark.getMarkDescriptor()));

    return markIds;
}
</code>```

This is the unit test I created:

```<code>@RunWith(PowerMockRunner.class)
@SpringApplicationCourseuration(classes=SpringConf.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@PowerMockIgnore({"javax.management.*"})
public class CourseCarTest {

    @Mock private CourseCarRepImpl courseCarRep;
    @Mock private CourseMarkRepImpl courseMarkRep;
    @Mock private CourseCarDoc courseCat;
    @Mock private ICourseCar courseCarDoc;
    @Mock MarkWag markWag;
    List<MarkWag> markWagList = new ArrayList<>();
    @Mock  ICourseMark courseMark;
    List<ICourseMark> courseMarkDocList = new ArrayList<>();
    @Mock ICar carDoc;

    @InjectMocks
    @Autowired
    @Qualifier("CourseCarBO")
    private CourseCarBO courseCarBo;

    @Before
    public void setup() throws Exception {

        markWagList.add(markWag);
        courseMarkDocList.add(courseMark);

        whenNew(CourseCarRepImpl.class).withAnyArguments().thenReturn(courseCarRep);
        whenNew(CourseMarkRepImpl.class).withAnyArguments().thenReturn(courseMarkRep);
        when(courseCarRep.get(anyInt())).thenReturn(courseCarDoc);
        when(courseCarDoc.getMarks()).thenReturn(markWagList);
        when(markWag.getMarkId()).thenReturn(1);
        when(courseMarkRep.getList(anyList())).thenReturn(courseMarkDocList);
        when(courseMark.getMarkDescriptor()).thenReturn(1);
    }

    @Test
    public void testGetMarkIdList() {

        courseCarBo.getMarkIdList(1);

        verify(courseCarRep).get(anyInt());
    }
}
</code>```

My intention was to have an hybrid approach, both mocking some objects and injecting others with Spring. However I noticed that as I mock one of the objects, I have to mock the others that follow as they depend on each other. So it looks to me like it's not really possible to have an hybrid approach.

Can you spot anything wrong in the approach used in this unit test?

When I have to mock everything, it looks to me like if I'm not testing anything.

Is there a better way? Or my approach is correct, and mocking everything is the way to go?

答:
The code under test is not really making anything easier for you. If you could reorganize that code you would find it much easier to test. Otherwise you are stuck with these overly complicated tests that jump through all the hoops to get from ICar to MarkId.

It is hard to make any reorganization recommendations with only one function given. It looks like your function is asking for a car when it really needs a List to get you your List. This forces your function to look through different Objects to get what it needs. The easier more testable approach is to ask for the parameters you need upfront and work from there. This will cut all the lookup code out and make your tests much easier to write.

Breaking the code down into smaller pieces will make  your code rely on multiple tests to prove that it is working instead of one overly complicated hard to maintain master test which does everything.

OwnerDisplayName: umhelp


答:
It appears that your friend has wandered into terminology confusion based on reusing the same term for multiple purposes.

If I have 8 bits of memory, I have 8 bits of memory, nothing more.  They can store one byte, which represents any one of 256 possible states.  If you add one more bit of memory, it doubles the number of possible states, but it can still only hold one such state.

However, to represent all of those 8-bit states at the same time, I would need 256 bytes.  When you have a system that uses 8-bit memory addressing, (or, more commonly these days, 32-bit or 64-bit memory addressing,) it means that you use an 8-bit number to represent a location in memory, and you can therefore have up to 256 possible memory locations available to your addressing scheme.  (Which is why no one uses such a small memory addressing system: you'd run out of addresses too quickly.  They use 32- or 64-bit systems, which is something very different from having only 32 or 64 bits of memory.)

When people say they have a 64-bit system, that's usually what it means: their system uses 64-bit values for memory addressing, giving their system the potential to support 2^64 bytes of memory.  So far, no computer has anywhere near that much actual memory available; it's only in the last few years that we've broken past the 32-bit limit, which is 4 GB.  The 64-bit limit is the square of that, approximately 16 billion GB.


问:
Should you ever mix scalar and list contexts anyway?
I have decided to learn Perl as my next language and I am currently reading about the scalar and list contexts, although this question is not specifically Perl-related, I will just put it in a Perl context (hah, get it?!)

So, the basic idea is that operators expect either a scalar or a list value, and if they get an argument that is of a different type than the one they are expecting, they will convert it to the appropriate context.

A couple of examples of the correct contexts being used:

# Scalar context
$first_number = 2;
$second_number = 3;
say 3+2; # This obviously prints 5

# List context
@array = qw (one two three);
@array = reverse @array;
say @array; # Prints threetwoone
```

<p>Now, if you mix contexts, you can get something like this:</p>

<pre class="lang-perl prettyprint-override"><code>$first_number = 2;
@array = qw (one two three);
$result = 2 + @array;
say $result; # This prints 5
</code>```

This is because using an array in a mathematical operation returns the length of the array instead.

Now, the question is: why would you ever want to do this unless you are an evil person and you want to make people reading your code miserable? Would it be too mainstream to use something like 2 + $#array instead?

In general, is it good programming practice to let the language take care of this type of scenario? Wouldn't it be better if the programmer took care of the variables and prepared data so that all operators received the correct argument type in the first place?

答:
$#array is (well, historically was - this variable has been deprecated in 5.12.0) impacted by the value of the $[ (see also $ARRAY_BASE in the perldoc perlvar documentation) and can cause the straightforward use of $#array + 1 to give invalid or unexpected results.

In some cases identifying what context a sub call has been made in (void, scalar, or array) can allow the sub to optimize the work it needs to do (if this optimization should be done or not is left as an argument for the code review).

For example, an iterator might be able to reset itself in the case of void context ($iterator->()), return the next item in scalar context (my $item = $iterator->()), or return the remaining items in array context (my @items = $iterator->()).

I have glossed over some parts of what bdf stated above so as not to duplicate his fine explanation.


问:
Is it acceptable for child classes to "break" parent class functionality?
One of the devs that works with me is following the Open/Closed Principle to add functionality to a Model by extending from our framework ORM.

```<code>class BaseModel extends ORM {
   ...
}
</code>```

All our models are now inheriting BaseModel, and this model works well in the context of our application.

```<code>class Product extends BaseModel {
  ...
}
</code>```

The problem comes when we tried to use the models as if they where extending directly from the ORM, use some of the most basic functionality:

```<code>$product = Product::factory();
$product->name = 'foo';
$product->price = 9.99;
$product->save();
</code>```

This code should have worked well but it failed because now the factory method requires a list of parameters.

I think that as long as the models works well within the context of our product we are good; but I also have mixed feelings about not supporting some of the basic core functionality of the parent class.

Thoughts?

答: The Liskov substitution principle restricts the behavior of instance methods in subclasses. It does not say anything about class methods like Product::factory.

OwnerDisplayName: Onema


问:
Interactive review of data in modal before inserting in db
I'm looking for a conceptual approach to a problem.

I'm building a web app that imports data from a source I don't control. The data quality is pretty high, but occasionally, the data does not make sense.  So I want to expose the exceptions (based on data rules) to users in a modal so that they can accept the funky data or change it before committing.

The app has been developed so far to behave like this:

while importing data, transactions are validated

transactions that do not validate are accumulated in a php  array (aka "exceptions_arr")

in some cases intelligence in the code proposes a solution to "bad" data fields (based on related data) and adds these suggestions to the "exception" record (but does not replace the original imported data)

then before completing the import, the exception records (and proposed fixes) are exposed to the user in a modal, one at a time

for each record, the user decides: skip it, accept the original data or edit the record and save it (which will, of course, be validated again for security reasons)

Goal:

Create a user experience IN THE MODAL: display an exception, submit the user's decision and/or edits, record that data on the backend, send a confirming message, then serve up the next exception by replacing the body of the modal. Bonus if the underlying page is updated (with some counter stats) based on the decisions made.

Question: how to do this?

It's the looping through the exceptions that I'm having trouble with. My approach so far has been to:
a) set and display the modal with an empty structure (done, no issues)
b) create the tbody of the table with the first exception data (done, no issues)
c) capture the appropriate data (none, old, proposed/edited) when the user submits his/her decision (done, no issues)

Current approach:

Currently I am POSTing the user's decision data to the host page via ajax, and handling the resulting user decision/POST just fine - once.  The problem is that this POST back to the page that launched the modal blows away the accumulated exception_arr.

I have searched how to loop through the data one record at a time and halt the process when each exception is found (and pop open a fresh modal and collect the user's decision), but alas jquery/javascript/php code isn't easily halted and resumed. When the user decision is POSTed, the launching page still restarts (from the beginning).

Is using SESSION storage a good approach?  Read all exceptions into the DOM and then process?

答:
In my experience the most stable solution for this scenario is to still persist the failing records rather than keeping them in memory or in the session. What if the user gets distracted in the middle and then closes their browser and goes home? What if the server crashes or you need to restart? Then you loose all the records currently being processed.

So, I would persist the error records anyway. Depending on your data, you can stick them into the same tables as any other records and just flag them for review. Alternatively, you can store them into a separate set of tables or just as a file to the file system.

Then your screen can just ask the database for the next failing record for that user and display that record. Once the record gets handled it gets deleted and inserted properly.

An additional benefit to this is that this keeps your web server stateless. Which means you can set-up clustering and don't need to worry which of your web-servers the user is accessing.


答:
You should begin by moving from procedural programming, which your code currently is, to OOP.

"I have objects," you may protest, but in fact your objects do not encapsulate anything. In a true OO world, your code should look like this:

```<code>public List<MarkId> getMarkIdList(ICar carDoc)
{
    return courseCarRep.get(carDoc).getCourseMarkIdsAsList();
}
</code>```

The get() method of courseCarRep returns a CourseCar object, which already has everything it needs within it and the getCourseMarkIdsAsList() is a public method the CourseCar class provides to hide the more complicated logic behind it (which is taking its list of CourseMarks and returning only their identifications).

Which may bring up a question: Why do I need the getMarkIdList(ICar) method in the first place?

So how do I unit test the current getMarkIdList method?

Simple answer: you do not.

More elaborate answer: The procedure you are trying to test seems to be so high in your application layer it is no longer considered a single unit and therefore should not be tested using unit tests.

If you want to test that the method works, use integration testing. If you want to focus on unit testing, test the following objects and highlighted methods instead:

courseCarRep::get

courseCarDoc::getMarks

courseMarkRep::getList

courseMark::getMarkDescriptor

If you test, that those methods work under all conditions, you can be pretty sure, your procedure will work as well.

Trust. Your. Tests.

What should I (generally) really mock, when doing unit tests?

You should only mock the behaviour of objects which are necessary for the test to pass. Everything else should be replaced by a dummy or null (if possible).

Null values are a great indicator that something is unused. If I go through a unit test and see someone pass a null instead of an object, I safely assume that specific variable has nothing to do with the test itself, it is not part of it, and even if I replace the null object with an actual instance, the test results cannot change.

Also try to remove the new operator from your business logic. Either replace it by factories, if you feel like you really need to create something, or use dependency injection.

Title: Testing using mocking, must I mock all dependencies too?

Body:
I have the following method to test:

```<code>public List<MarkId> getMarkIdList(ICar carDoc) {

    ICourseCar courseCarDoc = courseCarRep.get(carDoc);

    List<MarkWag> markWagList = courseCarDoc.getMarks();

    List<Integer> markIdList = new ArrayList<>();

    for (MarkWag markWag : markWagList)
        markIdList.add(markWag.getMarkId());

    List<ICourseMark> courseMarkDocList = courseMarkRep.getList(markIdList);

    List<MarkId> markIds = new ArrayList<>();

    for (ICourseMark courseMark : courseMarkDocList)
        markIds.add( new MarkId(courseMark.getMarkDescriptor()));

    return markIds;
}
</code>```

This is the unit test I created:

```<code>@RunWith(PowerMockRunner.class)
@SpringApplicationCourseuration(classes=SpringConf.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@PowerMockIgnore({"javax.management.*"})
public class CourseCarTest {

    @Mock private CourseCarRepImpl courseCarRep;
    @Mock private CourseMarkRepImpl courseMarkRep;
    @Mock private CourseCarDoc courseCat;
    @Mock private ICourseCar courseCarDoc;
    @Mock MarkWag markWag;
    List<MarkWag> markWagList = new ArrayList<>();
    @Mock  ICourseMark courseMark;
    List<ICourseMark> courseMarkDocList = new ArrayList<>();
    @Mock ICar carDoc;

    @InjectMocks
    @Autowired
    @Qualifier("CourseCarBO")
    private CourseCarBO courseCarBo;

    @Before
    public void setup() throws Exception {

        markWagList.add(markWag);
        courseMarkDocList.add(courseMark);

        whenNew(CourseCarRepImpl.class).withAnyArguments().thenReturn(courseCarRep);
        whenNew(CourseMarkRepImpl.class).withAnyArguments().thenReturn(courseMarkRep);
        when(courseCarRep.get(anyInt())).thenReturn(courseCarDoc);
        when(courseCarDoc.getMarks()).thenReturn(markWagList);
        when(markWag.getMarkId()).thenReturn(1);
        when(courseMarkRep.getList(anyList())).thenReturn(courseMarkDocList);
        when(courseMark.getMarkDescriptor()).thenReturn(1);
    }

    @Test
    public void testGetMarkIdList() {

        courseCarBo.getMarkIdList(1);

        verify(courseCarRep).get(anyInt());
    }
}
</code>```

My intention was to have an hybrid approach, both mocking some objects and injecting others with Spring. However I noticed that as I mock one of the objects, I have to mock the others that follow as they depend on each other. So it looks to me like it's not really possible to have an hybrid approach.

Can you spot anything wrong in the approach used in this unit test?

When I have to mock everything, it looks to me like if I'm not testing anything.

Is there a better way? Or my approach is correct, and mocking everything is the way to go?

Body:
You should begin by moving from procedural programming, which your code currently is, to OOP.

"I have objects," you may protest, but in fact your objects do not encapsulate anything. In a true OO world, your code should look like this:

public List<MarkId> getMarkIdList(ICar carDoc)
{
    return courseCarRep.get(carDoc).getCourseMarkIdsAsList();
}

The get() method of courseCarRep returns a CourseCar object, which already has everything it needs within it and the getCourseMarkIdsAsList() is a public method the CourseCar class provides to hide the more complicated logic behind it (which is taking its list of CourseMarks and returning only their identifications).

Which may bring up a question: Why do I need the getMarkIdList(ICar) method in the first place?

So how do I unit test the current getMarkIdList method?

Simple answer: you do not.

More elaborate answer: The procedure you are trying to test seems to be so high in your application layer it is no longer considered a single unit and therefore should not be tested using unit tests.

If you want to test that the method works, use integration testing. If you want to focus on unit testing, test the following objects and highlighted methods instead:

courseCarRep::get

courseCarDoc::getMarks

courseMarkRep::getList

courseMark::getMarkDescriptor

If you test, that those methods work under all conditions, you can be pretty sure, your procedure will work as well.

Trust. Your. Tests.

What should I (generally) really mock, when doing unit tests?

You should only mock the behaviour of objects which are necessary for the test to pass. Everything else should be replaced by a dummy or null (if possible).

Null values are a great indicator that something is unused. If I go through a unit test and see someone pass a null instead of an object, I safely assume that specific variable has nothing to do with the test itself, it is not part of it, and even if I replace the null object with an actual instance, the test results cannot change.

Also try to remove the new operator from your business logic. Either replace it by factories, if you feel like you really need to create something, or use dependency injection.


问:
python - differences between reusable code vs. code for solving specific tasks
Reusable code (ex. libraries and frameworks) and code written to solve a specific task and not meant to be reused as a general tool (for example, code being used only by my 6 person team in a private repository) differ greatly in purpose, so I imagine there could be vastly different strategies, best practices, advice, etc. for each.

In Python, what are the biggest differences between these two types of coding?

Possible Examples: My team ends up writing long functions and we don’t have many classes, which I think makes sense because the code is not meant to be reused by external programmers but rather only to complete a known task. But on the other hand, when I read Python libraries on Github they use plenty of classes, and in talks about writing reusable code in Python they encourage very short methods and functions.

答:
My team ends up writing long functions and we don’t have many classes, which I think makes sense because the code is not meant to be reused by external programmers but rather only to complete a known task.

You may be misunderstanding the purpose of classes and short functions.

Classes are a way of managing complexity. By packaging a group of related state and functionality together, and by creating methods that do things with that state (so that callers can tell a class instance to do something, instead of callers having to directly manipulate all of the necessary state themselves), you can encapsulate details and abstract away some of a problem's complexity.

A function lets you attach a name to a piece of behavior.  Code reuse is one benefit of functions, but attaching a name to a particular piece of code and having a structure to indicate what are the inputs, local state, and outputs of that code is of great benefit, even if you only ever call that function once.

In other words, using classes and short functions to structure your code and manage complexity is generally better design, even if the code doesn't need to be reused. You mentioned that your software only needs to complete a known task, but in my experience, even completing a known task often requires going back and revisiting the code, as bugs are found or as the task changes or as new, related tasks are added. I suspect that, if your single-task code used more, shorter functions and the occasional class, you'll find it easier to write, easier to understand, and easier to revisit.

Now, obviously, software development is all about trade-offs. Some design activities (such as some of the heavier OO techniques) may be worth the cost for heavily reused library code but not for single-use application code. Other design activities (such as trying to design for reuse before you actually have a need for reuse) are downright misguided. Other techniques, though, such as writing more, shorter functions, take very little effort once you've learned and practiced them, and I'd recommend them for almost any programming.

TL;DR: Short functions and good OO classes are good design. Whether the code is a reusable library or a single-use private application may affect which design criteria predominate and how design trade-offs are made, but good design is good design regardless.


问:
Bin sorting problem - Please help categorize
I have a problem I am developing a solution for and currently I solve it with a brute force solution that checks all possibilities. It works for small numbers of bins but I'd like to work with a reasonable speed for increasing numbers, however the algorithm I use (brute force) increases in computing time in a factorial manner related to the number of bins. In other words it gets way too slow pretty quickly after about 6 or 7 bins. I'd like to classify the problem to see if it is NP-Complete, NP-Hard or other so I know where to look in attempting to optimize.

The basic problem is this.

You have a number of points n and you have weights for these points. The points also have an ordering such that points in a bin must be consecutive. You must place these into a total of a maximum of k bins. The bins contain an estimate for the set of points placed in it and the total error of the absolute value of difference in the points and the estimate must be minimized. The goal is to find how to place these points in the bins to have the minimal total error.

Thanks!

答:
This problem can be solved exactly in polynomial time by using dynamic programming.  Let E[i,b] be the smallest possible error on bins b, b+1, ..., k when those bins contain items i, i+1, ..., n and no others. Observe that we wish to calculate E[1,1], which we'll do by tabulating all values E[i,b] for 1 ≤ i ≤ n and 1 ≤ b ≤ k.

I'm going to write c[b] for the capacity of the b'th bin, w[i] for the weight of the i'th item and w[i,j] for w[i] + ... + w[j].

First, observe that, for any i, E[i,k] = |w[i,n] - c[k]|, because that is the only possible error from putting all of items i through n in bin k.  To calculate E[i,b] for some b < k, observe that we either put items i, ..., j (for some j ≥ i) in bin b and items j+1, ..., n in bins b+1, ..., k; or we put all of items i, ..., n in bins b+1, ..., k.  Therefore,

E[i,b] = min ({E[i,b+1]} ∪ {|w[i,j] - c[b]| + E[j+1,b+1] : i < j ≤ n}

Since each E[i,b] only depends on values E[i',b'] for i' > i and b' > b, we can just compute them in descending order of b and i.  So, we can compute E[1,1] in time something like O(n2k).  Since the input contains the n weights and k costs, the input has length at least nk, so this is a true polynomial time algorithm (as distinct from the pseudopolynomial algorithms you usually get for bin packing problems).


问:
Inferring programmatically terminals and non-terminals in context-free grammars?
I'm trying to compute the FIRST and FOLLOW sets of a CFG (using Python).

To do this I need to recognise terminals and non-terminals. I can (as a human) read them, but I was wondering if there was computational logic for inferring terminals and non-terminals, if one's given only the grammar.

It sounds like one'd need to construct the parse tree and then label terminals and non-terminals? A terminal is a node that has no childs.

One could also use the definition of "terminals" and "non-terminals":

Terminals

A terminal is a symbol which does not appear on the left-hand side of any production.

Nonterminals

Nonterminals are the non-leaf nodes in a parse tree.

Or perhaps non-terminals are also all of those that don't fit into the definition of terminals.

http://web.cs.wpi.edu/~kal/PLT/PLT2.1.2b.html

答:
This should be fairly straight-forward. Assuming a grammar like:

```<code>expr:   ID | STR | NUM | list
list:   ( seq )
seq:       | expr seq
</code>```

You can collect the symbols in each production (ID, STR, NUM, list, (, seq, ), expr, and nothing) and then pull out the production symbols themselves (expr, list, seq). This gives you two sets, the terminals and non-terminals (and nothing, which you may want or not depending on your needs).

Body:
This should be fairly straight-forward. Assuming a grammar like:

expr:   ID | STR | NUM | list
list:   ( seq )
seq:       | expr seq

You can collect the symbols in each production (ID, STR, NUM, list, (, seq, ), expr, and nothing) and then pull out the production symbols themselves (expr, list, seq). This gives you two sets, the terminals and non-terminals (and nothing, which you may want or not depending on your needs).


问:
Are a class's methods a type of closure?
Per MDN

A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time that the closure was created.

Based on this statement is it acceptable to call methods in a class with access to global variables a type of closure?

It seems as though that description meets the requirements, as a method is of course a function for a class instance, and it has access to the class variables which are in a sense local to the method.

答:
Yes, but global variables have nothing to do with it.

A closure is a function that encloses state from an outer scope.  This enclosed state is persistent, and more than one function can enclose the same set of state data.

An object, on the other hand, is a set of state variables with functions associated with it that (if encapsulation is being used) have privileged access to that state.

In other words, an object is a closure and a closure is an object.  They're two different ways of looking at the same basic concept: state and associated functions bound together.  The only difference is how you look at it.  A closure emphasizes the functions a lot more, while an object tends to put more emphasis on the data, but the two are really the same thing.  In fact, object-oriented languages almost always implement closures by having the compiler transform them into special object classes, and functional languages tend to implement objects by wrapping multiple closures around the same set of state data.


问:
Technology like SignalR but client side
I would like to program a software that will heavily utilize client side development (JavaScript), and I want to communicate with the server. Is there a way similar to SignalR where I can keep communicating with the server to get new updates if any?

Something similar to LinkedIn where when there is a new update, it will show you that there is 1 or 2 updates available, so you can click to see them.

I know I can use setTimeOut and keep checking with the server, but is it the right way?

答: What you are looking for is probably Websockets.  That will let you maintain a connection with the server, and send & receive data.  Its very easy to implement on the client side.  </p>

Title: Technology like SignalR but client side


问:
In C++, when should I use final in virtual method declaration?
I know that final keyword is used to prevent virtual method from being overriden by derived classes. However, I can't find any useful example when I should really use final keyword with virtual method. Even more, it feels like usage of final with virtual methods is a bad smell since it disallows programmers to extend class in future.

My question is next:

Is there any useful case when I really should use final in virtual method declaration?

答:
It's often useful from a design perspective to be able to mark things as unchanging. In the same way the const provides compiler guards and indicates that a state should not change, final can be used to indicate that behavior should not change any further down the inheritance hierarchy.

Example

Consider a video game where vehicles take the player from one location to another. All vehicles should check to make sure they are traveling to a valid location prior to departure (making sure the base at the location is not destroyed, e.g.). We can start off using the non-virtual interface idiom (NVI) to guarantee that this check is made regardless of the vehicle.

```<code>class Vehicle
{
public:
    virtual ~Vehicle {}

    bool transport(const Location& location)
    {
        // Mandatory check performed for all vehicle types. We could potentially
        // throw or assert here instead of returning true/false depending on the
        // exceptional level of the behavior (whether it is a truly exceptional
        // control flow resulting from external input errors or whether it's
        // simply a bug for the assert approach).
        if (valid_location(location))
            return travel_to(location);

        // If the location is not valid, no vehicle type can go there.
        return false;
    }

private:
    // Overridden by vehicle types. Note that private access here
    // does not prevent derived, nonfriends from being able to override
    // this function.
    virtual bool travel_to(const Location& location) = 0;
};
</code>```

Now let's say we have flying vehicles in our game, and something that all flying vehicles require and have in common is that they must go through a safety inspection check inside the hangar prior to take-off.

Here we can use final to guarantee that all flying vehicles will go through such an inspection and also communicate this design requirement of flying vehicles.

```<code>class FlyingVehicle: public Vehicle
{
private:
    bool travel_to(const Location& location) final
    {
        // Mandatory check performed for all flying vehicle types.
        if (safety_inspection())
            return fly_to(location);

        // If the safety inspection fails for a flying vehicle,
        // it will not be allowed to fly to the location.
        return false;
    }

    // Overridden by flying vehicle types.
    virtual void safety_inspection() const = 0;
    virtual void fly_to(const Location& location) = 0;
};
</code>```

By using final in this way, we are effectively sort of extending the flexibility of the non-virtual interface idiom to provide uniform behavior down the inheritance hierarchy (even as an afterthought, countering the fragile base class problem) to virtual functions themselves. Furthermore, we buy ourselves wiggle room to make central changes that affect all flying vehicle types as an afterthought without modifying each and every flying vehicle implementation that exists.

This is one such example of using final. There are contexts you will encounter where it simply doesn't make sense for a virtual member function to be overridden any further -- to do so might lead to a brittle design and a violation of your design requirements.

That's where final is useful from a design/architectural perspective.

It's also useful from an optimizer's perspective since it provides the optimizer this design information that allows it to devirtualize virtual function calls (eliminating the dynamic dispatch overhead, and often more significantly, eliminating an optimization barrier between caller and callee).

Question

From the comments:

Why would final and virtual ever be used at the same time?

It doesn't make sense for a base class at the root of a hierarchy to declare a function as both virtual and final. That seems quite silly to me, as it would make both compiler and human reader have to jump through unnecessary hoops which can be avoided by simply avoiding virtual outright in such a case. However, subclasses inherit virtual member functions like so:

```<code>struct Foo
{
   virtual ~Foo() {}
   virtual void f() = 0;
};

struct Bar: Foo
{
   /*implicitly virtual*/ void f() final {...}
};
</code>```

In this case, whether or not Bar::f explicitly uses the virtual keyword, Bar::f is a virtual function. The virtual keyword then becomes optional in this case. So it might make sense for Bar::f to be specified as final, even though it is a virtual function (final can only be used for virtual functions).

And some people may prefer, stylistically, to explicitly indicate that Bar::f is virtual, like so:

```<code>struct Bar: Foo
{
   virtual void f() final {...}
};
</code>```

To me it's kind of redundant to use both virtual and final specifiers for the same function in this context (likewise virtual and override), but it's a matter of style in this case. Some people might find that virtual communicates something valuable here, much like using extern for function declarations with external linkage (even though it's optional lacking other linkage qualifiers).

Body:
It's often useful from a design perspective to be able to mark things as unchanging. In the same way the const provides compiler guards and indicates that a state should not change, final can be used to indicate that behavior should not change any further down the inheritance hierarchy.

Example

Consider a video game where vehicles take the player from one location to another. All vehicles should check to make sure they are traveling to a valid location prior to departure (making sure the base at the location is not destroyed, e.g.). We can start off using the non-virtual interface idiom (NVI) to guarantee that this check is made regardless of the vehicle.

class Vehicle
{
public:
    virtual ~Vehicle {}

    bool transport(const Location& location)
    {
        // Mandatory check performed for all vehicle types. We could potentially
        // throw or assert here instead of returning true/false depending on the
        // exceptional level of the behavior (whether it is a truly exceptional
        // control flow resulting from external input errors or whether it's
        // simply a bug for the assert approach).
        if (valid_location(location))
            return travel_to(location);

        // If the location is not valid, no vehicle type can go there.
        return false;
    }

private:
    // Overridden by vehicle types. Note that private access here
    // does not prevent derived, nonfriends from being able to override
    // this function.
    virtual bool travel_to(const Location& location) = 0;
};

Now let's say we have flying vehicles in our game, and something that all flying vehicles require and have in common is that they must go through a safety inspection check inside the hangar prior to take-off.

Here we can use final to guarantee that all flying vehicles will go through such an inspection and also communicate this design requirement of flying vehicles.

class FlyingVehicle: public Vehicle
{
private:
    bool travel_to(const Location& location) final
    {
        // Mandatory check performed for all flying vehicle types.
        if (safety_inspection())
            return fly_to(location);

        // If the safety inspection fails for a flying vehicle,
        // it will not be allowed to fly to the location.
        return false;
    }

    // Overridden by flying vehicle types.
    virtual void safety_inspection() const = 0;
    virtual void fly_to(const Location& location) = 0;
};

By using final in this way, we are effectively sort of extending the flexibility of the non-virtual interface idiom to provide uniform behavior down the inheritance hierarchy (even as an afterthought, countering the fragile base class problem) to virtual functions themselves. Furthermore, we buy ourselves wiggle room to make central changes that affect all flying vehicle types as an afterthought without modifying each and every flying vehicle implementation that exists.

This is one such example of using final. There are contexts you will encounter where it simply doesn't make sense for a virtual member function to be overridden any further -- to do so might lead to a brittle design and a violation of your design requirements.

That's where final is useful from a design/architectural perspective.

It's also useful from an optimizer's perspective since it provides the optimizer this design information that allows it to devirtualize virtual function calls (eliminating the dynamic dispatch overhead, and often more significantly, eliminating an optimization barrier between caller and callee).

Question

From the comments:

Why would final and virtual ever be used at the same time?

It doesn't make sense for a base class at the root of a hierarchy to declare a function as both virtual and final. That seems quite silly to me, as it would make both compiler and human reader have to jump through unnecessary hoops which can be avoided by simply avoiding virtual outright in such a case. However, subclasses inherit virtual member functions like so:

struct Foo
{
   virtual ~Foo() {}
   virtual void f() = 0;
};

struct Bar: Foo
{
   /*implicitly virtual*/ void f() final {...}
};

In this case, whether or not Bar::f explicitly uses the virtual keyword, Bar::f is a virtual function. The virtual keyword then becomes optional in this case. So it might make sense for Bar::f to be specified as final, even though it is a virtual function (final can only be used for virtual functions).

And some people may prefer, stylistically, to explicitly indicate that Bar::f is virtual, like so:

struct Bar: Foo
{
   virtual void f() final {...}
};

To me it's kind of redundant to use both virtual and final specifiers for the same function in this context (likewise virtual and override), but it's a matter of style in this case. Some people might find that virtual communicates something valuable here, much like using extern for function declarations with external linkage (even though it's optional lacking other linkage qualifiers).


答:
Okay, first things first. SignalR is not a server-side-only technology. It also lives on the client. That's its selling point. It abstracts the heavy lifting of damn-near-real-time communication between client and server. Wasn't sure if that was clear given the question title.

With that out of the way, if you're interested in how SignalR works, then yes, one of its approaches is to send an occasional request to the server to see if anything's changed. That's called ajax long polling. It's not SignalR's first strategy because, well, it kinda stinks. Just think of all the things that could go wrong. Not to mention it's not a real-time two-way update since the server can't initiate a change. SignalR prefers to use Websockets if they're available.

They call it a fallback strategy. SignalR tries an HTML5 technology like WebSockets. If that's not available, it falls back to one of the old Comet tricks. Pretty smart, really.

SignalR is definitely not the only game in town. Other options span from cool projects like Meteor (Meteor is a lot more than real-time client/server communication, it's pretty huge) to more focused projects like socket.io. Keep in mind that since bidirectional communication requires both a client and server, each project uses different server technology. Since you mention SignalR, I'm going to guess you're using (or are considering) a Microsoft technology. In that case, you have fewer options.

If what you're really asking is how to implement bespoke bidirectional client/server communication, then start with WebSockets (tutorial). If you have many users, you'll probably find that some of them are using older tech that doesn't support WebSockets (or maybe you're using older server tech that doesn't support it). In that case, take a look at Comet (tutorial). By the time you get all of that done (or imagine the time it would take), SignalR might look better to you.

Title: Technology like SignalR but client side

Body:
I would like to program a software that will heavily utilize client side development (JavaScript), and I want to communicate with the server. Is there a way similar to SignalR where I can keep communicating with the server to get new updates if any?

Something similar to LinkedIn where when there is a new update, it will show you that there is 1 or 2 updates available, so you can click to see them.

I know I can use setTimeOut and keep checking with the server, but is it the right way?


问:
When NOT to use virtual destructors?
I believed I searched many times about virtual destructors, most mention the purpose of virtual destructors, and why you need virtual destructors. Also I think in most cases destructors need to be virtual.

Then the question is: Why doesn't c++ set all destructors virtual by default? or in other questions:

When do I NOT need to use virtual destructors?

In which case I should NOT use virtual destructors?

What is the cost of using virtual destructors if I use it even if it is not needed?

答:
What is the cost of using virtual destructors if I use it even if it is not needed?

The cost of introducing any virtual function to a class (inherited or part of the class definition) is a possibly very steep (or not depending on the object) initial cost of a virtual pointer stored per object, like so:

```<code>struct Integer
{
    virtual ~Integer() {}
    int value;
};
</code>```

In this case, the memory cost is relatively enormous. The actual memory size of a class instance will now often look like this on 64-bit architectures:

```<code>struct Integer
{
    // 8 byte vptr overhead
    int value; // 4 bytes
    // typically 4 more bytes of padding for alignment of vptr
};
</code>```

The total is 16 bytes for this Integer class as opposed to a mere 4 bytes. If we stored a million of these in an array, we end up with 16 megabytes of memory usage: twice the size of the typical 8 MB L3 CPU cache, and iterating through such an array repeatedly can be many times slower than the 4 megabyte equivalent without the virtual pointer as a result of additional cache misses and page faults.

This virtual pointer cost per object, however, doesn't increase with more virtual functions. You can have 100 virtual member functions in a class and the overhead per instance would still be a single virtual pointer.

The virtual pointer is typically the more immediate concern from an overhead standpoint. However, in addition to a virtual pointer per instance is a per-class cost. Each class with virtual functions generates a vtable in memory which stores addresses to the functions it should actually call (virtual/dynamic dispatch) when a virtual function call is made. The vptr stored per instance then points to this class-specific vtable. This overhead is usually a lesser concern, but it might inflate your binary size and add a bit of runtime cost if this overhead was paid needlessly for a thousand classes in a complex codebase, e.g. This vtable side of the cost does actually increase proportionally with more and more virtual functions in the mix.

Java developers working in performance-critical areas understand this kind of overhead very well (though often described in the context of boxing), since a Java user-defined type implicitly inherits from a central object base class and all functions in Java are implicitly virtual (overridable) in nature unless marked otherwise. As a result, a Java Integer likewise tends to require 16 bytes of memory on 64-bit platforms as a result of this vptr-style metadata associated per instance, and it's typically impossible in Java to wrap something like a single int into a class without paying a runtime performance cost for it.

Then the question is: Why doesn't c++ set all destructors virtual by default?

C++ really favors performance with a "pay as you go" kind of mindset and also still a lot of bare-metal hardware-driven designs inherited from C. It doesn't want to needlessly include the overhead required for vtable generation and dynamic dispatch for every single class/instance involved. If performance isn't one of the key reasons you are using a language like C++, you might benefit more from other programming languages out there as a lot of the C++ language is less safe and more difficult than it ideally could be with performance often being the key reason to favor such a design.

When do I NOT need to use virtual destructors?

Quite often. If a class is not designed to be inherited, then it doesn't need a virtual destructor and would only end up paying a possibly large overhead for something it doesn't need. Likewise, even if a class is designed to be inherited but you never delete subtype instances through a base pointer, then it also does not require a virtual destructor. In that case, a safe practice is to define a protected nonvirtual destructor, like so:

```<code>class BaseClass
{
protected:
    // Disallow deleting/destroying subclass objects through `BaseClass*`.
    ~BaseClass() {}
};
</code>```

In which case I should NOT use virtual destructors?

It's actually easier to cover when you should use virtual destructors. Quite often far more classes in your codebase will not be designed for inheritance.

std::vector, for example, is not designed to be inherited and typically should not be inherited (very shaky design), as that will then be prone to this base pointer deletion issue (std::vector deliberately avoids a virtual destructor) in addition to clumsy object slicing issues if your derived class adds any new state.

In general a class that's inherited should either have a public virtual destructor or a protected, nonvirtual one. From C++ Coding Standards, chapter 50:

50. Make base class destructors public and virtual, or protected and nonvirtual. To delete, or not to delete; that is the question: If deletion through a pointer to a base Base should be allowed, then Base's destructor must be public and virtual. Otherwise, it should be protected and nonvirtual.

One of the things C++ tends to kind of implicitly emphasize (because designs tend to get really brittle and awkward and possibly even unsafe otherwise) is the idea that inheritance is not a mechanism designed to be used as an afterthought. It's an extensibility mechanism with polymorphism in mind, but one which requires foresight as to where extensibility is needed. As a result, your base classes should be designed as roots of an inheritance hierarchy upfront, and not something you inherit from later as an afterthought without any such foresight in advance.

In those cases where you simply want to inherit to reuse existing code, composition is often strongly encouraged (Composite Reuse Principle).

OwnerDisplayName: amuse

Title: When NOT to use virtual destructors?

Body:
What is the cost of using virtual destructors if I use it even if it is not needed?

The cost of introducing any virtual function to a class (inherited or part of the class definition) is a possibly very steep (or not depending on the object) initial cost of a virtual pointer stored per object, like so:

struct Integer
{
    virtual ~Integer() {}
    int value;
};

In this case, the memory cost is relatively enormous. The actual memory size of a class instance will now often look like this on 64-bit architectures:

struct Integer
{
    // 8 byte vptr overhead
    int value; // 4 bytes
    // typically 4 more bytes of padding for alignment of vptr
};

The total is 16 bytes for this Integer class as opposed to a mere 4 bytes. If we stored a million of these in an array, we end up with 16 megabytes of memory usage: twice the size of the typical 8 MB L3 CPU cache, and iterating through such an array repeatedly can be many times slower than the 4 megabyte equivalent without the virtual pointer as a result of additional cache misses and page faults.

This virtual pointer cost per object, however, doesn't increase with more virtual functions. You can have 100 virtual member functions in a class and the overhead per instance would still be a single virtual pointer.

The virtual pointer is typically the more immediate concern from an overhead standpoint. However, in addition to a virtual pointer per instance is a per-class cost. Each class with virtual functions generates a vtable in memory which stores addresses to the functions it should actually call (virtual/dynamic dispatch) when a virtual function call is made. The vptr stored per instance then points to this class-specific vtable. This overhead is usually a lesser concern, but it might inflate your binary size and add a bit of runtime cost if this overhead was paid needlessly for a thousand classes in a complex codebase, e.g. This vtable side of the cost does actually increase proportionally with more and more virtual functions in the mix.

Java developers working in performance-critical areas understand this kind of overhead very well (though often described in the context of boxing), since a Java user-defined type implicitly inherits from a central object base class and all functions in Java are implicitly virtual (overridable) in nature unless marked otherwise. As a result, a Java Integer likewise tends to require 16 bytes of memory on 64-bit platforms as a result of this vptr-style metadata associated per instance, and it's typically impossible in Java to wrap something like a single int into a class without paying a runtime performance cost for it.

Then the question is: Why doesn't c++ set all destructors virtual by default?

C++ really favors performance with a "pay as you go" kind of mindset and also still a lot of bare-metal hardware-driven designs inherited from C. It doesn't want to needlessly include the overhead required for vtable generation and dynamic dispatch for every single class/instance involved. If performance isn't one of the key reasons you are using a language like C++, you might benefit more from other programming languages out there as a lot of the C++ language is less safe and more difficult than it ideally could be with performance often being the key reason to favor such a design.

When do I NOT need to use virtual destructors?

Quite often. If a class is not designed to be inherited, then it doesn't need a virtual destructor and would only end up paying a possibly large overhead for something it doesn't need. Likewise, even if a class is designed to be inherited but you never delete subtype instances through a base pointer, then it also does not require a virtual destructor. In that case, a safe practice is to define a protected nonvirtual destructor, like so:

class BaseClass
{
protected:
    // Disallow deleting/destroying subclass objects through `BaseClass*`.
    ~BaseClass() {}
};

In which case I should NOT use virtual destructors?

It's actually easier to cover when you should use virtual destructors. Quite often far more classes in your codebase will not be designed for inheritance.

std::vector, for example, is not designed to be inherited and typically should not be inherited (very shaky design), as that will then be prone to this base pointer deletion issue (std::vector deliberately avoids a virtual destructor) in addition to clumsy object slicing issues if your derived class adds any new state.

In general a class that's inherited should either have a public virtual destructor or a protected, nonvirtual one. From C++ Coding Standards, chapter 50:

50. Make base class destructors public and virtual, or protected and nonvirtual. To delete, or not to delete; that is the question: If deletion through a pointer to a base Base should be allowed, then Base's destructor must be public and virtual. Otherwise, it should be protected and nonvirtual.

One of the things C++ tends to kind of implicitly emphasize (because designs tend to get really brittle and awkward and possibly even unsafe otherwise) is the idea that inheritance is not a mechanism designed to be used as an afterthought. It's an extensibility mechanism with polymorphism in mind, but one which requires foresight as to where extensibility is needed. As a result, your base classes should be designed as roots of an inheritance hierarchy upfront, and not something you inherit from later as an afterthought without any such foresight in advance.

In those cases where you simply want to inherit to reuse existing code, composition is often strongly encouraged (Composite Reuse Principle).


问:
Is object pooling a deprecated technique?
I am very familiar with the concept of object pooling and I always try to use it as much as possible.

Additionally I always thought that object pooling is the standard norm as I have observed that Java itself as well as the other frameworks use pooling as much as possible.

Recently though I read something that was completely new (and counter-intuitive?) to me.

That pooling actually makes program performance worse especially in concurrent applications, and it is advisable to instantiate new objects instead, since in newer JVMs, instantiation of an object is really fast.

I read this in the book: Java Concurrency in Practice

Now I am starting to think if I am missunderstanding something here since the first part of the book adviced to use Executors that reuse Threads instead of creating new instances.

So has object pooling become deprecated nowadays?

答:
That pooling actually makes program performance worse especially in
  concurrent applications, and it is advisable to instantiate new
  objects instead, since in newer JVMs, instantiation of an object is
  really fast.

Depends on the context.


问:
Pass request as argument to service client vs. pass service client as argument to request
I need a design recommendation: I have a class that send a http request via another class WebServiceHandler()
I am hesitating between the following two implementations, which one to choose?which one is more accurate from OO point of view?

First implementation:

```<code>/* WebServiceHandler class is charged on sending http requests and getting responses */
public class WebServiceHandler()
{
    public boolean sendRequest(String method)
    {
        /*send a http request, get a response*/
    }
}

/* Step is modeling one request execution, on the main program I can have multiple steps to get a scenario like: connect to the server, send a get request, etc */
public class Step()
{
    private boolean result=false;
    private WebServiceHandler handler;

    public Step (WebServiceHandler handler)
    {
        this.handler= handler;
    }

    private void execute()
    {
        result = handler.sendRequest(this.httpMethod);
        /*this.httpMethod can be GET Http method for example*/
    }
}

public class Main
{
    public static void main(String[] args)
    {
        handler= new WebServiceHandler();
        step= new Step(handler);
        step.execute();
    }
}
</code>```

Second Implementation:

```<code>public class WebServiceHandler()
{
    public boolean sendRequest(String method)
    {
        /*send a http request, get a   response*/
    }

    public void executeStep(Step step)
    {
        result=sendRequest(step.getMethod());
        step.setResult(result);
    }
}

public class Step()
{
    private boolean result=false;

    setResult(String result){/*setter*/}
}

public class Main
{
    public static void main(String[] args)
    {
        handler = new WebServiceHandler();
        step = new Step();
        handler.executeStep(step);
    }
}
</code>```

答:
Given your description of the classes Step and WebServiceHandler, the Step class depends on the WebServiceHandler to be able to do its job, but not the other way around.

This makes that it should be possible to have/create a WebServiceHandler without having a Step instance.

Given how the direction of your dependencies lies, the first design option is the better one of the two.

To make it easier to test your code without needing access to a live web service, I would advise you to make an interface (IWebServiceHandler) for the WebServiceHandler. This interface is what the Step class should depend on. That way you can swap out the real WebServiceHandler for a dummy version while testing the Step class.


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

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

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

I actually have three questions regarding this approach:

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

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

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

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

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

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

Thanks again.
I do appreciate the feedback.

答:
Unfortunately, I am not sure what your first question really means, therefore am unable to answer that, but I can help you with the rest.

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

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

What you should ask yourself is why are you dealing with invalid objects in the first place so that they require validation after they are created?

There are two situations why this could happen:

you do not trust the variables which are used when an object is created

you do not trust the objects themselves, you do not believe, that what they are doing with their data is perfect

Both of these cases are bad, but the second one is much worse.

The first case can and does happen, when you use variables, which the user has control over. Ie. he can input anything he want. This is something you really have no control over, so you need to make sure to check all options before creating an object.

The second case happens when, even though you model a class, you do not trust the class does what it is supposed to do. Do you perhaps expose too much of its internal structure, giving the programmer too many posibilities on how to operate on the object, perhaps having simple getters and setters, instead of actual methods?

I said the second case is worse. The reason why it is worse is because you do not trust your own domain. And if you cannot trust it, then who?

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

DTO is a very simple and stupid object which consists only from getters and setters and glues small chunks of seemingly related information together to make one larger structure, so the data requests may be reduced.

Martin Fowler provides a simple example of a DTO object.

Domain model is an object containing your business logic. It is an object which should have no methods starting with the prefix set, it should follow the Tell, Don't ask principle, etc. The domain is the core of your application, the domain objects make sure, everything works well, they throw domain exceptions on invalid operations to make sure, they are always in a valid state.

The Tell, Don't ask principle provides encapsulation. It turns this:

```<code>if (personObject.GetSex() == "Male") { ... }
</code>```

into this:

```<code>if (personObject.IsMale()) { ... }
</code>```

The programmer using a Person class no longer cares, how the Sex property is represented, if it is a string, an enum or a boolean. The only thing it cares about is the Person::IsMale : boolean method.

Domain model summary: It is an object containing data which are directly tied to it (no persistence logic is allowed, the object has to deal only with its own data) and encapsulates operations to make sure once created, it will never find itself in an invalid state.

Body:
Unfortunately, I am not sure what your first question really means, therefore am unable to answer that, but I can help you with the rest.

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

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

What you should ask yourself is why are you dealing with invalid objects in the first place so that they require validation after they are created?

There are two situations why this could happen:

you do not trust the variables which are used when an object is created

you do not trust the objects themselves, you do not believe, that what they are doing with their data is perfect

Both of these cases are bad, but the second one is much worse.

The first case can and does happen, when you use variables, which the user has control over. Ie. he can input anything he want. This is something you really have no control over, so you need to make sure to check all options before creating an object.

The second case happens when, even though you model a class, you do not trust the class does what it is supposed to do. Do you perhaps expose too much of its internal structure, giving the programmer too many posibilities on how to operate on the object, perhaps having simple getters and setters, instead of actual methods?

I said the second case is worse. The reason why it is worse is because you do not trust your own domain. And if you cannot trust it, then who?

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

DTO is a very simple and stupid object which consists only from getters and setters and glues small chunks of seemingly related information together to make one larger structure, so the data requests may be reduced.

Martin Fowler provides a simple example of a DTO object.

Domain model is an object containing your business logic. It is an object which should have no methods starting with the prefix set, it should follow the Tell, Don't ask principle, etc. The domain is the core of your application, the domain objects make sure, everything works well, they throw domain exceptions on invalid operations to make sure, they are always in a valid state.

The Tell, Don't ask principle provides encapsulation. It turns this:

if (personObject.GetSex() == "Male") { ... }

into this:

if (personObject.IsMale()) { ... }

The programmer using a Person class no longer cares, how the Sex property is represented, if it is a string, an enum or a boolean. The only thing it cares about is the Person::IsMale : boolean method.

Domain model summary: It is an object containing data which are directly tied to it (no persistence logic is allowed, the object has to deal only with its own data) and encapsulates operations to make sure once created, it will never find itself in an invalid state.


问:
Is there a design pattern to remove the need to check for flags?
I'm going to save some string payload in the database. I have two global configurations:

encryption

compression

These can be enabled or disabled using the configuration in a way that either only one of them is enabled, both are enabled or both are disabled.

My current implementation is this:

```<code>if (encryptionEnable && !compressEnable) {
    encrypt(data);
} else if (!encryptionEnable && compressEnable) {
    compress(data);
} else if (encryptionEnable && compressEnable) {
    encrypt(compress(data));
} else {
  data;
}
</code>```

I'm thinking about the Decorator pattern. Is it the right choice, or is there perhaps a better alternative?

答:
The only problem I see with your current code is the risk of combinatorial explosion as you add more settings, which can be easily be mitigated by structuring the code more like this:

```<code>if(compressEnable){
  data = compress(data);
}
if(encryptionEnable) {
  data = encrypt(data);
}
return data;
</code>```

I'm not aware of any "design pattern" or "idiom" that this could be considered an example of.

Body:
The only problem I see with your current code is the risk of combinatorial explosion as you add more settings, which can be easily be mitigated by structuring the code more like this:

if(compressEnable){
  data = compress(data);
}
if(encryptionEnable) {
  data = encrypt(data);
}
return data;

I'm not aware of any "design pattern" or "idiom" that this could be considered an example of.