问:
Is there a stricter strtoull() in any ubiquitous C library?
I want a function that will interpret a string as a strictly unsigned integer, failing when the string overflows, represents a negative number, or does not represent a number.

strtoull() does set errno to ERANGE on overflow or EINVAL for a string that does not begin with a number, but accepts negative numbers as valid.

strtoumax() is the same as strtoull()

atoll() and strtonum() are ruled out because they are strictly for signed integers.

sscanf() sets errno to ERANGE on overflow and stops processing the string if it does not begin with a number (reflected in sscanf's return value), but also accepts negative numbers as valid.

Is there another option that I'm missing?

答:
There are no out-of-the-box solutions that fit your requirements, but it is easy enough to write such a function yourself, using strtoull or strtoll as basis.

For negative numbers, either you can check for the minus sign beforehand, or you can convert to a signed number first and report an error for negative values.

For numbers followed by other characters, you can check that the endp pointer that you pass to strto(u)ll points to the end of the string.


问:
Data model - inheritance
I just started working on a project where I am trying to implement some backend logic which includes creating a data model for the given problem. Here is a problem I came across and I am curious what approach would be more suitable for tackling it.

Model:
There are various users in the system with different rights and structures but there is a very simple inheritance between them.

There is a basic user that can browse and view some data, psot comments etc. Than, there is a member who can do everything the user can + something more and they share the basic data structures + member has its own. And there is a producer which is again just an extension of member.

Each user can (but does not have to) be a member and each member can (but does not have to) be a producer.

1) My current idea:

Create table user and tables member and producer which would reference each other using user's id. There would be 0 to 1 relationship between these tables:

```<code>USER {
id
username
email etc..
}

MEMBER {
userid
some_member_attributes
}

PRODUCER {
userid
some_producer_attributes
}
</code>```

The advantage is, that it would save me a lot of NULL values in a single table and it feels somehow natural to me. The disadvatage is that I would have to query three different tables every time I would like to get some data from a producer.

2) The other possibility is implementing this as a one table with attributes isMember and isProducer. But again, this will result in a lot of NULL values since most of the users wont be producers. And its not very typical to have many 0 to 1 relationships in one model, I think...

What do you suggest? I hope its not an off-topic here, I am just trying to get this right so I wont have to reimplement is a dozen times in future. Thanks for any tips!

答:
Your data model seems a tad insufficient. Someone logged in can no doubt be a user today, a member next week and a producer next year. This suggests that inheritance is the wrong way to go. You need to have a logged in user table, linked to a secondary table that hands out producer and member rights over a defined time period. </p>

<p>Peter Coad has done some excellent work in this field -try a Google search on his name. </p>

ContentLicense: CC BY-SA 3.0

Title: Data model - inheritance

Body:
Your data model seems a tad insufficient. Someone logged in can no doubt be a user today, a member next week and a producer next year. This suggests that inheritance is the wrong way to go. You need to have a logged in user table, linked to a secondary table that hands out producer and member rights over a defined time period.

Peter Coad has done some excellent work in this field -try a Google search on his name.


问:
When is a number a magic number?
Over the last couple of months I have been diving into coding standard IfSQ. As a part of this IfSQ standard, a rule is to not use Magic Numbers. While I don't have a problem with building this rule into checks as FxCop or StyleCop, I am confused as to what actually IS a Magic Number.

According to Wikipedia there are 3 explanations of magic numbers:

A constant numerical or text value used to identify a file format or protocol;

Distinctive unique values that are unlikely to be mistaken for other meanings (e.g., Globally Unique Identifiers);

Unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants.

I am focussing on the third meaning. But this is also where I am stuck. Seeing as I am trying to build this in a FxCop rule; the check has to be automated. But what am I supposed flag as magic number?

The IfSQ standard explains the following as magic numbers: Numeric literals (other than 0 or 1) have been embedded directly into the source code. For example "34" or "86400".

But this doesn't sound good to me at all. This would mean I'd have to flag every single occurence of a number other than 0 and 1. Numbers like 24 (hours), 60 (minutes) and 100 (percentage) are, in their correct context, no magic numbers; in my eyes that is.

Because this is will be an automated check, looking from things in a contextual way isn't really possible.

Based on this I have the following questions:

How should I define a magic number?

Is it possible to define magic numbers without context?

Should I skip certain statements when checking for magic numbers?

答:
I've struggled with this definition as well, in my case with CheckStyle.

A particular issue is in the Spring validation framework, where error strings are looked up in a .properties file. CheckStyle complains when I write something like

addError("error.invalid.email.address");

If this is the only place that string is used, I struggle to see what the alternative adds:

private static final String ERROR_INVALID_EMAIL_ADDRESS = "error.invalid.email.address";

.. 200 lines of code here...

addError(ERROR_INVALID_EMAIL_ADDRESS);

Others I'm sure will have differing views...

Title: When is a number a magic number?


答:
Most tools I know of, which support detection and reporting of magic number usages specifically only address statements. You are quite correct that eliminating all numbers from the source code is kind of pointless.

Who - with a sane mind - would read the number of hours a day has from a configuration file? Of course, there is a good reason to just use the 24, however there is no good reason to use it within a statement that is not part of a constant declaration. Compare the following two occurrences of 24:

```<code>private final int NUMBER_OF_HOURS_PER_DAY = 24;
...
return NUMBER_OF_HOURS_PER_DAY * days;
</code>```

versus:

```<code>return 24 * days;
</code>```

The second example above would typically be flagged as using a magic number, whereas the first one would not. The main difference comes from the fact, that a second usage within the code makes the difference clear: in the first example, you would simply refer to NUMBER_OF_HOURS_PER_DAY again and should your constant change at any time, you are sure that it's updated everywhere at once. In the second example you would just write 24 again, which increases the effect of the magic number problem.

Additionally, the constants can be named appropriately, so you get more meaning from it than from a simple magic number, which may not appear magical to you (because you know that a day has 24 hours), but may appear indeed quite magical to someone else. What if the factor was not 24, but 7? Is that any less magical? and does it even have something to do with the number of days in a week?

Either way, the net effect is that numbers (other than 0 and 1) should be defined via constants and you should not flag those occurrences as magic numbers. Numbers within statements, that are not used at a constant declaration site, should be flagged though.

Border cases: What to do with something like final int HOURS = 20 + 4;? and what about final int CONSTANT = OTHER_CONSTANT * 4 ? Should the 4 be flagged as magic number or not? In my experience, the different tools differ at least in these border cases. Some are very strict and do not allow numbers in expressions that are larger than the constant itself (i.e., no addition/multiplication/etc.). Others are a bit more relaxed and accept it as a usage for defining the constant.

Title: When is a number a magic number?

Body:
Over the last couple of months I have been diving into coding standard IfSQ. As a part of this IfSQ standard, a rule is to not use Magic Numbers. While I don't have a problem with building this rule into checks as FxCop or StyleCop, I am confused as to what actually IS a Magic Number.

According to Wikipedia there are 3 explanations of magic numbers:

A constant numerical or text value used to identify a file format or protocol;

Distinctive unique values that are unlikely to be mistaken for other meanings (e.g., Globally Unique Identifiers);

Unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants.

I am focussing on the third meaning. But this is also where I am stuck. Seeing as I am trying to build this in a FxCop rule; the check has to be automated. But what am I supposed flag as magic number?

The IfSQ standard explains the following as magic numbers: Numeric literals (other than 0 or 1) have been embedded directly into the source code. For example "34" or "86400".

But this doesn't sound good to me at all. This would mean I'd have to flag every single occurence of a number other than 0 and 1. Numbers like 24 (hours), 60 (minutes) and 100 (percentage) are, in their correct context, no magic numbers; in my eyes that is.

Because this is will be an automated check, looking from things in a contextual way isn't really possible.

Based on this I have the following questions:

How should I define a magic number?

Is it possible to define magic numbers without context?

Should I skip certain statements when checking for magic numbers?

Body:
Most tools I know of, which support detection and reporting of magic number usages specifically only address statements. You are quite correct that eliminating all numbers from the source code is kind of pointless.

Who - with a sane mind - would read the number of hours a day has from a configuration file? Of course, there is a good reason to just use the 24, however there is no good reason to use it within a statement that is not part of a constant declaration. Compare the following two occurrences of 24:

private final int NUMBER_OF_HOURS_PER_DAY = 24;
...
return NUMBER_OF_HOURS_PER_DAY * days;

versus:

return 24 * days;

The second example above would typically be flagged as using a magic number, whereas the first one would not. The main difference comes from the fact, that a second usage within the code makes the difference clear: in the first example, you would simply refer to NUMBER_OF_HOURS_PER_DAY again and should your constant change at any time, you are sure that it's updated everywhere at once. In the second example you would just write 24 again, which increases the effect of the magic number problem.

Additionally, the constants can be named appropriately, so you get more meaning from it than from a simple magic number, which may not appear magical to you (because you know that a day has 24 hours), but may appear indeed quite magical to someone else. What if the factor was not 24, but 7? Is that any less magical? and does it even have something to do with the number of days in a week?

Either way, the net effect is that numbers (other than 0 and 1) should be defined via constants and you should not flag those occurrences as magic numbers. Numbers within statements, that are not used at a constant declaration site, should be flagged though.

Border cases: What to do with something like final int HOURS = 20 + 4;? and what about final int CONSTANT = OTHER_CONSTANT * 4 ? Should the 4 be flagged as magic number or not? In my experience, the different tools differ at least in these border cases. Some are very strict and do not allow numbers in expressions that are larger than the constant itself (i.e., no addition/multiplication/etc.). Others are a bit more relaxed and accept it as a usage for defining the constant.


答:
Just to extend a bit on Frank's answer, take the following:

```<code>private final int NUMBER_OF_HOURS_PER_DAY = 24;
private final int FRAMES_PER_SECOND = 24;
...
return NUMBER_OF_HOURS_PER_DAY * days;
...
return FRAMES_PER_SECOND * seconds;
</code>```

Now compare that to:

```<code>return 24 * days;
...
return 24 * seconds;
</code>```

If you consider that one of the most important aspect of code quality is how it conveys intentions, then the later of the above is a disaster.

Title: When is a number a magic number?

Body:
Just to extend a bit on Frank's answer, take the following:

private final int NUMBER_OF_HOURS_PER_DAY = 24;
private final int FRAMES_PER_SECOND = 24;
...
return NUMBER_OF_HOURS_PER_DAY * days;
...
return FRAMES_PER_SECOND * seconds;

Now compare that to:

return 24 * days;
...
return 24 * seconds;

If you consider that one of the most important aspect of code quality is how it conveys intentions, then the later of the above is a disaster.


问:
What is Object Services class purpose?
I'm reading a book on TDD: (btw this question has nothing to to with TDD)

link to the book on amazon

Author often mentions/uses Service Classes

For example we would have a Person Object
Person would would have:

  - a "regular" class for deifining the entity Person

  - a data access class (lets say we have a db for data persistance) using
    for example a repository patter PersonRepository

  - a "service" class (PersonServices) PersonServices as author himself explains:

A PersonService class serves as the business domain class that works with Person objects from a standpoint of enforcing business rules and using Person in business work fl ows.

My question would be is that a way to go with your classes? In the past I would put everything from Person class and PersonServices into one class.
What type of functionality would go into Servieces classes for my objects?

I'm not sure if I understand the quote above (maybe I'm missing the point?)

答: A typical business rule about Person objects is that they must have a unique identifier (e.g. email address, employee code...). Right there you have something that the Person class can't enforce on its own: each Person only knows its own identifier, but to enforce the rule you need access to all existing Persons. That is why you need another class with a broader scope than just representing one person, e.g. a Service class (and you can also see how having a Repository class would be useful to write the Service class).

Title: What is Object Services class purpose?


问:
Design of active or passive class domain
Sorry if my (simplified) example is too broad.

Given this model (written in C#):

```<code>class Ball
{
}
</code>```

Let's assume that a ball can be launched.

To implement this feature, I can define something like:

```<code>class Ball
{
    void Launch();
}
</code>```

or something like:

```<code>class BallLauncher
{
    void Launch(Ball ball);
}
</code>```

In which situations is better use first approach and which the second one?

In fact, this example tries to simplify an actual real underlying model. In that model, I need to upload files (Package) to a repository.

Then, I don't know if the repository should upload (physical copy) a package (files) to itself or it is the package who should upload itself to a repository.

答:
Basic example: launch a ball

Analyzing business logic helps. Can the ball possibly launch itself? Probably not. It's just a ball, and can't move by itself. This means that you'll create a BallLauncher in order to launch it.

What would Ball class contain? Mostly properties of the object, such as radius, color and texture.

Two objects example: launch a rocket

A Rocket may be launched itself, or may require a launcher. Sometimes, looking at the logic, it may not be obvious where to put the method. A rocket is not passive, but may need a launcher. A launcher is required to launch a rocket, but the rocket participates in the launching as well.

When the logic is not obvious, here's a hint: implement the Launch method and watch how Rocket and Launcher are used.

Example:

class Rocket
{
    public void Launch()
    {
        this.ControlTower.RequestTakeoff().WhenAuthorized(launcher =>
        {
            launcher.Prepare();
            if (launcher.Status == LauncherStatus.ReadyForLaunch)
            {
                launcher.Launch();
                launcher.PrepareNewRocket();
            }
            else
            {
                throw new BrokenLauncherException();
            }
        });
    }
}
```

<p>over-relies on <code>Launcher</code> and should be moved to <code>Launcher</code> class. On the other hand:</p>

<pre class="lang-cs prettyprint-override"><code>class Launcher
{
    public void Launch(Rocket rocket)
    {
        rocket.Ignite();
        rocket.IncreasePressureTo(Rocket.RecommendedPressureOnLaunch);
        rocket.PrepareForTakeoff();
        if (rocket.IsReady)
        {
            this.Release();
            rocket.Takeoff();
        }
        else
        {
            rocket.CancelTakeoff();
            rocket.Engines.ShutDownEmergency();
            throw new BrokenRocketException();
        }
    }
}
</code>```

is illustrative of a method which finds itself in a wrong class: it should be moved to Rocket.

Three objects example: package, repository, uploader

In the same way, if you have a Package and a Repository:

Should the package be uploaded to a repository,

Should a repository upload a package to itself,

Or should there be an Uploader which deals with packages and repositories through Upload(package, repository)?

Again, business logic prevails, and as in the previous example, watching how Package and Repository are used inside the method may help.

If Upload over-relies on Package, this may be a hint that it should be Package.Upload.

If Upload calls the methods from Repository practically all the time, move it to Repository.

If Upload has a logic which simply doesn't fit in Package or Repository, this is a good opportunity for creating an Uploader.

Body:
Basic example: launch a ball

Analyzing business logic helps. Can the ball possibly launch itself? Probably not. It's just a ball, and can't move by itself. This means that you'll create a BallLauncher in order to launch it.

What would Ball class contain? Mostly properties of the object, such as radius, color and texture.

Two objects example: launch a rocket

A Rocket may be launched itself, or may require a launcher. Sometimes, looking at the logic, it may not be obvious where to put the method. A rocket is not passive, but may need a launcher. A launcher is required to launch a rocket, but the rocket participates in the launching as well.

When the logic is not obvious, here's a hint: implement the Launch method and watch how Rocket and Launcher are used.

Example:

class Rocket
{
    public void Launch()
    {
        this.ControlTower.RequestTakeoff().WhenAuthorized(launcher =>
        {
            launcher.Prepare();
            if (launcher.Status == LauncherStatus.ReadyForLaunch)
            {
                launcher.Launch();
                launcher.PrepareNewRocket();
            }
            else
            {
                throw new BrokenLauncherException();
            }
        });
    }
}

over-relies on Launcher and should be moved to Launcher class. On the other hand:

class Launcher
{
    public void Launch(Rocket rocket)
    {
        rocket.Ignite();
        rocket.IncreasePressureTo(Rocket.RecommendedPressureOnLaunch);
        rocket.PrepareForTakeoff();
        if (rocket.IsReady)
        {
            this.Release();
            rocket.Takeoff();
        }
        else
        {
            rocket.CancelTakeoff();
            rocket.Engines.ShutDownEmergency();
            throw new BrokenRocketException();
        }
    }
}

is illustrative of a method which finds itself in a wrong class: it should be moved to Rocket.

Three objects example: package, repository, uploader

In the same way, if you have a Package and a Repository:

Should the package be uploaded to a repository,

Should a repository upload a package to itself,

Or should there be an Uploader which deals with packages and repositories through Upload(package, repository)?

Again, business logic prevails, and as in the previous example, watching how Package and Repository are used inside the method may help.

If Upload over-relies on Package, this may be a hint that it should be Package.Upload.

If Upload calls the methods from Repository practically all the time, move it to Repository.

If Upload has a logic which simply doesn't fit in Package or Repository, this is a good opportunity for creating an Uploader.


问:
Do VMs use one stack for everything?
Most VMs have a "call stack" to keep track of where to return from each function that was called. This is often simply regarded as "the stack".

However often a stack is needed for operations that aren't related to function calling, such as performing arithmetic. My question is: is the same stack (i.e. the call stack) used also for these kinds of operations? Or do operations such as performing arithmetic use a different stack?

(I'm talking about most VMs).

答:
Most VM's mimic the most common CPU architectures in this and use only a single stack for temporary values, intermediate results, function arguments, function return values and return addresses.

This is generally easiest, because you only need one administration of where the stack is located and how much space there is.

With only one stack, you also have only two data structures that can dynamically grow (the stack and the heap), which are conveniently arranged such that there is no need to determine beforehand how large each of them will be. The can start at opposite ends of the (available) address space and grow towards each other. They will only meet if the address space is exhausted.

With two or more stacks, that arrangement isn't possible, so you need to guess how much memory each will need.

Title: Do VMs use one stack for everything?


答:
Your preferred answer has a name in the literature.  Look up Class Table Inheritance.  The single table solution also has a name.  Look up Single Table Inheritance

Which one is better depends on the use case.

In your answer, you have also made use of a technique known as Shared Primary Key

Shared Primary Key can be very useful in combination with Class Table Inheritance.  It enforces the 1-to-1 nature of the subclass/class relationship, and it provide keys for simple and fast joins.

If coding the joins becomes a nuisance, code the joins in views.  You can even code a view that is the union of all the subclass views, and gives the appearance of a single table inheritance,  with all those nasty NULLs in there.

I'm only validating what you already came up with on your own.  But it might be useful to know that others have thought the same way.

Title: Data model - inheritance

Body:
I just started working on a project where I am trying to implement some backend logic which includes creating a data model for the given problem. Here is a problem I came across and I am curious what approach would be more suitable for tackling it.

Model:
There are various users in the system with different rights and structures but there is a very simple inheritance between them.

There is a basic user that can browse and view some data, psot comments etc. Than, there is a member who can do everything the user can + something more and they share the basic data structures + member has its own. And there is a producer which is again just an extension of member.

Each user can (but does not have to) be a member and each member can (but does not have to) be a producer.

1) My current idea:

Create table user and tables member and producer which would reference each other using user's id. There would be 0 to 1 relationship between these tables:

```<code>USER {
id
username
email etc..
}

MEMBER {
userid
some_member_attributes
}

PRODUCER {
userid
some_producer_attributes
}
</code>```

The advantage is, that it would save me a lot of NULL values in a single table and it feels somehow natural to me. The disadvatage is that I would have to query three different tables every time I would like to get some data from a producer.

2) The other possibility is implementing this as a one table with attributes isMember and isProducer. But again, this will result in a lot of NULL values since most of the users wont be producers. And its not very typical to have many 0 to 1 relationships in one model, I think...

What do you suggest? I hope its not an off-topic here, I am just trying to get this right so I wont have to reimplement is a dozen times in future. Thanks for any tips!


问:
Why doesn't the HTML\DOM specification allow hyperlinks to set an accept header?
The purpose of the Accept header from the client is to tell the server what kind of data it will accept as a response to its request. We can set this header in asynchronous HTTP calls in Javascript, but not in HTML.

For example, consider a link such as Get as CSV. If an attribute like accept="text/csv" were allowed, and the browser interpreted that to send an Accept: text/csv header with that request, the server could respond to the semantics of the request. Without it, we might create a link such as Get as CSV, and the server must respond to the arbitrary query string parameter instead.

What are the reasons, both technical and historical, behind the HTML\DOM specification not allowing the setting of an Accept header through markup?

答:
Because the headers are not part of the URL. The URL should identify the resource, on it's own, and should do it uniquely. The Accept (and the more useful Accept-Encoding) headers should not affect semantics of the request. They should indicate capabilities of the client so the server can format the response accordingly.

If you do a HTTP call from JavaScript, your JavaScript code is the client and so it gets to set headers. But for HTML link the browser is the client and therefore it gets to choose.

If you want to provide CSV to a user, the linked resource should generally be in a fixed format. Imagine the user does

Copy Link Address

$ wget PasteEnter

That's a legitimate thing for them to do for various reasons. And because the link promised them CSV, that's what they'll expect. But the wget won't get any other attribute of the link. Only the URL. So the information should be encoded in the URL.

In fact there are not many uses for Accept header, because most resources just have their format and don't make much sense in another. The Accept-Encoding is useful; if the client says Accept-Encoding: gzip,deflate it means the client can do transparent decompression. But about the only use I could think of for Accept is image and video formats e.g. to provide alternate for browsers that don't support say image/svg+xml or video/webm. Except browsers don't seem to actually advertise which media formats they support, so it does not work. And HTML chose to implement different, slightly more flexible mechanism anyway. And few other kinds of data have several widely implemented alternate formats to choose from.


答:
From an OO perspective, if Launch() implies mutating the Ball's internal state, I would tend to prefer the first design.

One good practice in OO is the Tell, Don't Ask principle :

you should endeavor to tell objects what you want them to do; do not
  ask them questions about their state, make a decision, and then tell
  them what to do

Chances are that Launch(Ball ball) will ask stuff from the Ball and then act based on this, changing its state, while Ball.Launch() will keep everything nicely encapsulated in it.

The case where I see a Launch(Ball ball) signature making sense is if you want to delegate the instantiation of a Ball to external code and then inject that Ball into the Launcher as a method-wide dependency. But the Launcher would still probably need to call something like Ball.Launch() anyway.

Title: Design of active or passive class domain

Body:
Sorry if my (simplified) example is too broad.

Given this model (written in C#):

```<code>class Ball
{
}
</code>```

Let's assume that a ball can be launched.

To implement this feature, I can define something like:

```<code>class Ball
{
    void Launch();
}
</code>```

or something like:

```<code>class BallLauncher
{
    void Launch(Ball ball);
}
</code>```

In which situations is better use first approach and which the second one?

In fact, this example tries to simplify an actual real underlying model. In that model, I need to upload files (Package) to a repository.

Then, I don't know if the repository should upload (physical copy) a package (files) to itself or it is the package who should upload itself to a repository.


问:
IS C++ a cross-platform language?
If I create a game in C++ on a mac using a library which is the same for both windows and osx, will the game be playable on both windows and os x or it will only work in os x because I done it in Xcode?

Is SDL a great library to do your first game after learning the basics and syntax of C++ (I found syntax  to be close to Java)?

答: As long as you stay away from low-level (i.e. platform specific) operations and platform-specific system calls (i.e. only call lib functions in your cross-platform lib) you should be fine. There may be some minor compiler issues requiring you to modify a bit of syntax here and there (porting code is rarely a matter of copy-and-recompile, there are usually one or two minor wrinkles to iron out) but that should be trivial.</p>

Title: IS C++ a cross-platform language?


答:
This depends entirely on the VM.

The JVM has a single stack for everything. (More precisely: a single stack per thread for everything.)

The Dalvik VM is register-based, it only has a call stack, all data is held in registers.

The Parrot VM has no stack at all: it is register-based, i.e. all data is held in registers, and its control flow is based on continuations, so it doesn't have a call stack either.

There are also VMs which conceptually have a stack but actually allocate all stackframes as regular objects on the heap. So, from the point of the instruction set, there is a stack, but in the actual implementation, there isn't. (The JVM specification, for example, allows this. There is nothing in there, which forces you to have a single contiguous area of memory for your stack. In fact, the spec explicitly mentions that they do not specify such level of detail and even mentions allocating stack frames on the heap as an example.)

Many Smalltalk and Lisp VMs have a "spaghetti stack", which is required to support call/cc, since this can conceptually "fork" the call stack.

Forth has two stacks: a return address stack for control flow and a data stack. Both stacks can be freely manipulated by the programmer.

Title: Do VMs use one stack for everything?

Body:
Most VMs have a "call stack" to keep track of where to return from each function that was called. This is often simply regarded as "the stack".

However often a stack is needed for operations that aren't related to function calling, such as performing arithmetic. My question is: is the same stack (i.e. the call stack) used also for these kinds of operations? Or do operations such as performing arithmetic use a different stack?

(I'm talking about most VMs).


答:
You are describing two separate problems. One is that the string should be in a specific form, namely all digits (but you didn't specify whether to permit leading and trailing spaces). The second is that the range should not overflow. There is no readily available function that provides exactly this combination.

The first requirement is best satisfied by testing (or parsing) the string before decoding it. In most languages I would use a regular expression. In C++ you can use library functions. In C you write loops and test characters.

The second requirement is actually quite tricky. You can include overflow testing in your decode function but testing against MAXUINT or something similar needs some careful coding. A simple solution is to decode as a double and then test the range before casting to uint.

In summary, when you have requirements as specific as this you normally finish up writing your own functions, perhaps basing it on available "free" source code. Over the 30 years I've been writing C code I've probably written this function or similar about 5 or 6 times. It gets easier with practice!

Title: Is there a stricter strtoull() in any ubiquitous C library?

Body:
I want a function that will interpret a string as a strictly unsigned integer, failing when the string overflows, represents a negative number, or does not represent a number.

strtoull() does set errno to ERANGE on overflow or EINVAL for a string that does not begin with a number, but accepts negative numbers as valid.

strtoumax() is the same as strtoull()

atoll() and strtonum() are ruled out because they are strictly for signed integers.

sscanf() sets errno to ERANGE on overflow and stops processing the string if it does not begin with a number (reflected in sscanf's return value), but also accepts negative numbers as valid.

Is there another option that I'm missing?


答:
Yes, C++ is a cross-platform language in the sense that there exist compilers for many platforms.

Not all features/versions/libraries are implemented in every compiler or available on all platforms, so in that sense: No, C++ is not a cross-platform language.

Now to your implicit question: "Can I develop a game with SDL for graphics and sound abstraction on Mac OS X and compile the game for Windows?"

Yes, that is in fact possible, provided you are sticking to a defined subset of features and libraries that are available on both platforms. Using MXE, you can compile your Windows version on Linux/BSD/Mac OS X for Windows, and MXE includes SDL.

Title: IS C++ a cross-platform language?

Body:
If I create a game in C++ on a mac using a library which is the same for both windows and osx, will the game be playable on both windows and os x or it will only work in os x because I done it in Xcode?

Is SDL a great library to do your first game after learning the basics and syntax of C++ (I found syntax  to be close to Java)?


问:
I don't understand the arguments against operator overloading
I just read one of Joel's articles in which he says:

In general, I have to admit that I’m a little bit scared of language features that hide things. When you see the code

```<code>i = j * 5;
</code>```

… in C you know, at least, that j is being multiplied by five and the results stored in i.

But if you see that same snippet of code in C++, you don’t know anything. Nothing. The only way to know what’s really happening in C++ is to find out what types i and j are, something which might be declared somewhere altogether else. That’s because j might be of a type that has operator* overloaded and it does something terribly witty when you try to multiply it.

(Emphasis mine.) Scared of language features that hide things? How can you be scared of that? Isn't hiding things (also known as abstraction) one of the key ideas of object-oriented programming? Everytime you call a method a.foo(b), you don't have any idea what that might do. You have to find out what types a and b are, something which might be declared somewhere  altogether else. So should we do away with object-oriented programming, because it hides too much things from the programmer?

And how is j * 5 any different from j.multiply(5), which you might have to write in a language that does not support operator overloading? Again, you would have to find out the type of j and peek inside the multiply method, because lo and behold, j might be of a type that has a multiply method that does something terribly witty.

"Muahaha, I'm an evil programmer that names a method multiply, but what it actually does is totally obscure and non-intuitive and has absolutely nothing to do whatsoever with multiplying things." Is that a scenario we must take into consideration when designing a programming language? Then we have to abandon identifiers from programming languages on the grounds that they might be misleading!

If you want to know what a method does, you can either glance at the documentation or peek inside the implementation. Operator overloading is just syntactic sugar, and I don't see how it changes the game at all.

Please enlighten me.

答:
I suspect it has something to do with breaking expectations. I've you're used to C++, you're used to operator behavior not being dictated entirely by the language, and you won't be surprised when an operator does something odd. If you're used to languages that don't have that feature, and then see C++ code, you bring along the expectations from those other languages, and may be nastily surprised when you discover that an overloaded operator does something funky.

Personally I think there's a difference. When you can change the behavior of the language's built-in syntax, it becomes more opaque to reason about. Languages that don't allow meta-programming are syntactically less powerful, but conceptually simpler to understand.

ContentLicense: CC BY-SA 2.5


答:
C++ is a multi-platform language in the sense that the source code can often be successfully compiled for multiple, distinct, platforms. The binaries you create are generally not portable between platforms.

When targeting multiple platforms, you need to take care that you stay away from platform-specific and compiler-specific code. Also all third-party libraries you use should be documented to support all relevant targets.

Title: IS C++ a cross-platform language?


答:
I don't really think of C++ as being "cross-platform" because you have to compile a different version for each platform.  Sure, there's a compiler for every platform, but that doesn't mean it's as simple as "port code then hit the compile button".  It's not remotely that simple.

If you want to do indie game programming, you probably don't want to reinvent the wheel: there are already free licence physics engines built upon game engines built upon graphics renderers.  Why try to build all that on your own?

I recommend JMonkeyEngine.  I don't think you need C++ or DirectX to make fast graphics games anymore unless you are trying for cutting-edge games like Skyrim; and even then you could still do most of the work in Java and add patches from other languages.

EDIT: Also, if you understand "basics and syntax of C++" this is not an indication that you understand C++ as well as you understand Java.  C++ has a large number of nuances to it.  Like, if you declare and assign a variable on one line vs. two lines this may change whether an overloaded assignment operator vs. a copy constructor gets called.  For this reason, C++ programmers usually need to know a lot more about the language than Java programmers in order to program safely in the language.

None of this is dissing C++, but you need to know what to expect if you want to use it.  Also, if you use DirectX rather than OpenGL, and if you want to do it on your own without using an open-license rendering engine, then god help you.

Title: IS C++ a cross-platform language?


答: Yes. C++ is a cross-platform programming language. You can compile C++ code in many platforms, there exist compilers for most of the platforms. Having said that, the code you write should be cross-platform, you should keep yourself away from platform-dependent features, if you want your code to be platform-independent. For example, you should not use COM if you want to be able to compiler your code on MAC or Linux. And otherwise C++ and the libraries like STL, boost are available from any platform.</p>

Title: IS C++ a cross-platform language?


问:
When to use the whiteboard pattern versus direct calling
I'm creating the architecture for a new embedded project. The system has some inputs that go to wildly different outputs. The whiteboard pattern is very useful for this (see Listeners Considered Harmful: The "Whiteboard" Pattern), as it decouples the input component from the output components (a 1-to-N relationship).

However, I'm struggling with the N-to-1 relationship (where one output gets data from wildly different inputs). Should I use the whiteboard pattern there? And what about the 1-to-1 relationship?

Advantages that I see of the whiteboard pattern:

separate deployment and testing of sources and listeners.

the whiteboard (EventAdmin in the OSGi world) can be monitored separately.

there is no build-time dependency.

Disadvantages that I see:

there is no compile-time check on the events (if someone makes a typo in the event topic or the data, you're screwed).

overhead of the whiteboard (I've done measurements, and it's significant on our platform).

I'm not quite sure how to balance these trade-offs.

答:
After discussing this with a colleague, and some more thought, I came to the conclusion that it depends on the nature of the dependency.

The whiteboard pattern completely decouples sources and listeners. The overhead (in processing time and absence of compiler checks) is warranted if:

the listeners of an event are completely unrelated to the source (i.e. in another part of the system)

sources and listeners should have the ability to be restarted separately

either the source or the listener is created by another company (as strings are easier to exchange than objects)

Note that none of these criteria mention how many N there are in the relationship.


问:
Should the commit history be used to convey critical information to developers?
During a meeting regarding the rollback of a third-party SDK from the latest version it was noted that the our developers already flagged in the commit history that the latest version should not be used.

Some developers argued that this was a bad practice and it should have instead been noted either in the source file (i.e. // Don't upgrade SDK Version x.y.z, see ticket 1234) or in a project level README file. Others argued that since the commit history is part of the project documentation it is an acceptable location for such information since we should all be reading it anyway.

Should the commit history be used to convey critical information to other developers or should such information be duplicated to another location such as a project README or comments in the relevant source file?

答:
I'm not sure how your team communicates but I believe the most effective way to say this is to first send and email to the team's email group, marked as "URGENT" with the body saying

Guys, we can't use SDK v x.y.z because it causes the Foo buffer to overflow and the Bar service will crash. Stick with version x.y.y

That's what we've done here and it's the most reliable way to get the message out there. If you really want to be fussy (and if your email system allows it), request a "read receipt" on the email.

Once you've told the whole team, more detailed documentation should be put into a team wiki. This will vary, depending on how you structure your documentation. If you have a section specifically for your applications Dependencies and Requirements, that would be a good place to add it.

An additional place to document this sort of problem might be in the source code itself, although that might not always work. If SDK version ... is only referenced in one or two obvious places, you could include a note about not upgrading.

The file history in source control can be very long, and depending on the developers, could have several entries per day. Someone who's been out on vacation for a week might not have time to read a week's worth of commit history. The README file is a better place as it's a little more central and people might be more inclined to read it, but you can't ensure that everyone will actually read the README. Well, I suppose they might if they see it's been changed...


答:
Something like this should have been put in the commit comments, but it will benefit from being in other places as well.

Whoever makes the decision to upgrade, needs to have the facts. That person may not live in source control. What if someone would have read about this problem on SO and never put it into the code base?

There needs to be some sort of document about this third-party SDK.

What problem does it solve?

Why was this particular one chosen?

What considerations need to be made as far as: versions, upgrades, testing, etc.

Who makes this decision?

You have a case where something like this made its way into the version control, and you should recommend everyone use this information as much as possible. Only your team can decide where someone is going to do a search in any documentation, source control, or bug tracker to get as much information as possible on the subject. Otherwise, you'll forget, someone will do it anyway, and you'll be lucky if it jogs someone's memory and quickly roll it back again.

Title: Should the commit history be used to convey critical information to developers?

Body:
During a meeting regarding the rollback of a third-party SDK from the latest version it was noted that the our developers already flagged in the commit history that the latest version should not be used.

Some developers argued that this was a bad practice and it should have instead been noted either in the source file (i.e. // Don't upgrade SDK Version x.y.z, see ticket 1234) or in a project level README file. Others argued that since the commit history is part of the project documentation it is an acceptable location for such information since we should all be reading it anyway.

Should the commit history be used to convey critical information to other developers or should such information be duplicated to another location such as a project README or comments in the relevant source file?


问:
Haskell syntax for type definitions: why the equality sign?
I am a bit confused by the choice of Haskell syntax for type definitions, like in

data Foo = Bar
```

<p>Namely: does the equality sign here really mean an equality in some subtle sense, or is it just a random notation choice?</p>

<p>For example, in</p>

<pre class="lang-haskell prettyprint-override"><code>foo x y = bar y x
</code>```

the equality is really an equality: if this line is present, foo a b and bar b a can be used more or less interchangeably in the program.  However, data Foo and Bar probably cannot be used interchangeably after data Foo = Bar.

Whenever i resume my attempts to learn Haskell, i am a bit confused by this IMO counter-intuitive syntax and need to look up the documentation to recall the formats of the LHS and the RHS.  Are there any alternative syntaxes for type definitions by any chance?

答: Foo is a type, Bar is a value. It doesn't make sense to speak of exchanging them. Rather, the equality sign expresses that type Foo consists of precisely those values on the right; no more and no less.</p>


答:
If I was going to look at upgrading to a newer version of a third party SDK, the last place I'd look is in the history of the source control system.

If your product is using version 2.0 of an SDK and someone is interested in upgrading to 3.0, I don't think it's reasonable to think that they should look backwards in time in your source control system to find out that it's not a good idea.

Here, we have a team wiki that has a handful of pages with interesting info that every developer reads (coding conventions, how to set up a development environment to build the product, what third party stuff you need to install, etc).  This is the sort of place that would be appropriate for a warning against upgrading a third party library.


答:
Critical and non-intuitive pieces of information should be documented where people will be looking when considering the information.

For the teams and projects I've worked on, I would commit the roll-back with the comment about why the new version failed. I would add a backlog story to re-try the upgrade if the new version get's fixed. I would add comments to the build system/build scripts where the library is linked.

The roll-back will provide future developers with context when looking into the project's history. The backlog story keeps the need for this upgrade as an active part of the project. The build system comments are right where the changes will need to be when the library is finally updated.

I would not comment it in the code and I would not add it to a README. Developers thinking about trying the upgrade will not be looking at these pieces. If you do add it there, then when the issue with the library is eventually fixed and an upgrade is done, you will need to remove it. This step is often forgotten: resulting in notes that are counter productive to the project.

If your project has a different setup or a different flow, then your answer may be different. I think the key is to put the information right were the developer will see it when doing the work for the upgrade. That way, if the time is not right for the upgrade, the developer will see it and stop, and when the time is right the developer will see it and remove the note so it won't confuse future developers.


答:
You're right that data Foo (or even Foo) and Bar can't be used interchangeably in Haskell code, but one might argue that type definitions, such as

```<code>data List a = Nil | Cons a (List a)
</code>```

can be transformed into an "equation" of the form List(a) = 1 + a * List(a). And you can then start playing with it as if it were an algebraic expression: the equation can be rewritten as List(a) = 1 / (1-a), from which List(a) = 1 + a + a*a + a*a*a + .... See the paper Seven trees in one for a spectacular application, or this SO question for lots more.

This is all very nice of course, but it's not going to help you read data declarations better!

For that, you could consider using Generalized Algebraic Datatypes, aka GADTs. One feature of those is that the types of the constructors are explicitly spelled out, making it clear what each constructor's name is, what types of arguments it takes and what the result type is. And it doesn't use that pesky = sign :-)

Your example would be written as:

```<code>data Foo where
    Bar :: Foo
</code>```

the List example I gave above would be:

```<code>data List a where
    Nil :: List a
    Cons :: a -> List a -> List a
</code>```

and an equivalent of the on-purpose confusingly named data X = X X X | Y would be:

```<code>data X where
    X :: X -> X -> X
    Y :: X
</code>```

GADTs, however, are not standard Haskell: they're a GHC extension, and a pretty recent one (so there might still be some bugs), but for your purpose of having an alternate type definition syntax I think they fit the bill just fine.

Title: Haskell syntax for type definitions: why the equality sign?

Body:
I am a bit confused by the choice of Haskell syntax for type definitions, like in

data Foo = Bar
```

<p>Namely: does the equality sign here really mean an equality in some subtle sense, or is it just a random notation choice?</p>

<p>For example, in</p>

<pre class="lang-haskell prettyprint-override"><code>foo x y = bar y x
</code>```

the equality is really an equality: if this line is present, foo a b and bar b a can be used more or less interchangeably in the program.  However, data Foo and Bar probably cannot be used interchangeably after data Foo = Bar.

Whenever i resume my attempts to learn Haskell, i am a bit confused by this IMO counter-intuitive syntax and need to look up the documentation to recall the formats of the LHS and the RHS.  Are there any alternative syntaxes for type definitions by any chance?

Body:
You're right that data Foo (or even Foo) and Bar can't be used interchangeably in Haskell code, but one might argue that type definitions, such as

data List a = Nil | Cons a (List a)

can be transformed into an "equation" of the form List(a) = 1 + a * List(a). And you can then start playing with it as if it were an algebraic expression: the equation can be rewritten as List(a) = 1 / (1-a), from which List(a) = 1 + a + a*a + a*a*a + .... See the paper Seven trees in one for a spectacular application, or this SO question for lots more.

This is all very nice of course, but it's not going to help you read data declarations better!

For that, you could consider using Generalized Algebraic Datatypes, aka GADTs. One feature of those is that the types of the constructors are explicitly spelled out, making it clear what each constructor's name is, what types of arguments it takes and what the result type is. And it doesn't use that pesky = sign :-)

Your example would be written as:

data Foo where
    Bar :: Foo

the List example I gave above would be:

data List a where
    Nil :: List a
    Cons :: a -> List a -> List a

and an equivalent of the on-purpose confusingly named data X = X X X | Y would be:

data X where
    X :: X -> X -> X
    Y :: X

GADTs, however, are not standard Haskell: they're a GHC extension, and a pretty recent one (so there might still be some bugs), but for your purpose of having an alternate type definition syntax I think they fit the bill just fine.


答:
Because the Accept: header is intended to indicate what types of documents the user's browser is able to handle correctly, and this is not information that you, as the author of the web page, have.

Specifically, the reason the HTTP protocol provides an Accept: header is to allow selecting an appropriate file type when the same document is available in more than one form.  Let's suppose I am linking to an image, for instance;  my browser may be able to display JPEG, or Tiff images, but might not have the capability to display a RAW image.  The browser would indicate this by sending the following headers with an image request:

```<code>Accept: image/jpeg,image/tiff
</code>```

Now, if the server is able to serve a given image as RAW or as TIFF, it would respond with a TIFF version of the image (and set the Content-Type: header to indicate the type it chose).

What would it mean for the author of the web page to override the choices the browser sends?  If I were to add a hypothetical accept="image/raw" attribute, the browser would still not be able to display a raw image -- but the server would send it.

Title: Why doesn't the HTML\DOM specification allow hyperlinks to set an accept header?

Body:
The purpose of the Accept header from the client is to tell the server what kind of data it will accept as a response to its request. We can set this header in asynchronous HTTP calls in Javascript, but not in HTML.

For example, consider a link such as Get as CSV. If an attribute like accept="text/csv" were allowed, and the browser interpreted that to send an Accept: text/csv header with that request, the server could respond to the semantics of the request. Without it, we might create a link such as Get as CSV, and the server must respond to the arbitrary query string parameter instead.

What are the reasons, both technical and historical, behind the HTML\DOM specification not allowing the setting of an Accept header through markup?

Body:
Because the Accept: header is intended to indicate what types of documents the user's browser is able to handle correctly, and this is not information that you, as the author of the web page, have.

Specifically, the reason the HTTP protocol provides an Accept: header is to allow selecting an appropriate file type when the same document is available in more than one form.  Let's suppose I am linking to an image, for instance;  my browser may be able to display JPEG, or Tiff images, but might not have the capability to display a RAW image.  The browser would indicate this by sending the following headers with an image request:

Accept: image/jpeg,image/tiff

Now, if the server is able to serve a given image as RAW or as TIFF, it would respond with a TIFF version of the image (and set the Content-Type: header to indicate the type it chose).

What would it mean for the author of the web page to override the choices the browser sends?  If I were to add a hypothetical accept="image/raw" attribute, the browser would still not be able to display a raw image -- but the server would send it.


问:
Filtering a List
I will try to simplify my problem. Let say I have a collection (more specifically a List) with different types of elements, for explanation purpose let say we have objects "Person" with different age of birth and an ID. I will represent a person like this: {<id>,<year>}

At some point, I want to get a sub list of all the persons born on 1988 and 1989, and if there is no persons born on that years, I want all the persons born in 1990:

```<code>[{1,1988},{2,1988},{3,1982},{4,1995},{5,1989},{6,1989},{7,1990}] ==>
[{1,1988},{2,1988},{5,1989},{6,1989}]

[{1,1990},{2,1981},{3,1983},{4,1993},{5,1981},{6,1989},{7,1990}] ==>
[{6,1989}]

[{1,1990},{2,1981},{3,1983},{4,1993},{5,1981},{6,1985},{7,1990}] ==>
[{1,1990},{7,1990}]
</code>```

Option 0

At first I though about using the filter method on the apache commons library, but this wouldn't work as I would need to know about all the element on the list to decide if a particular element goes on the sub list or not, so I ruled this option out.

Option 1

Then, the simplest way I can see to do this is loop through the list looking for elements that match the first condition (1988 or 1989), and then, if I can't find any, loop again to look for elements that match the second condition (1900). But I don't like this because you have to loop through the list more than once.

Option 2

The other option I can think about is to loop through the list only once, and to have two different sub list, one with the elements that match the first condition and another with the elements that match the second condition. At the end, if the first sub list is empty, we return the second sub list.

Which one of these two is better (more efficient)?

Which would you use and why?

Do you think there is a better solution than these?

答:
Here are the relevant considerations that would influence what I'd do.

Is this method time-critical? If not, forget considerations about which is faster. Looping over a data structure is rarely more expensive than the actual processing you are doing on the data.

If it is time-critical, which is faster in an experiment? Guessing which alternative is faster is almost always useless - if it's worth doing micro-optimization, it's worth doing empirically. Yes, that means coding both and throwing one of the solutions away. That's life.

Overall, the one that's the easiest to read while still satisfying the requirements is better than anything else. If the library you are using supports complex filtering, maybe with a user-defined filter callback, write a complex callback, give it a meaningful name and then solve the original problem in one line. You can't get more readable than that. Otherwise, it's worth trying it out with pseudocode: one alternative has an extra if and another loop that's executed only conditionally; the other has a more complicated loop body and a small if that returns one list if the other is empty. That sounds a bit closer to the original problem statement "if there are no persons born in those years, I want all the persons born in 1990", so it might be better. But again you should look at both and then decide which is preferable.

Title: Filtering a List


问:
Good practice for returns in Python
I was recently working on some prototype code in Python. The code worked great, then I realized that I needed a little more feedback from one of my functions so I changed the return statement from

```<code>return x
</code>```

to

```<code>return (x,y)
</code>```

Then going back to refactor existing code I realized that unless I search for invocation of this function across entire of the code base I won't know of any problems until run-time (and if this is some marginal case) barely ever and risking the program crashing due to uncaught exception resulting in operations on mismatched types. I contrast this with statically typed languages, where at compile time I get told about all places where the return doesn't mismatches expected type.

So I was wondering whether there is some conventional wisdom associated with the return types in Python to avoid this grepping through code nonsense.

P.S> Obviously better design patterns would solve this problem or not using duck typed language, but sometimes one comes across a case when you got to change the return type.

答:
PyCharm (the community version is FOSS) will do a pretty good job of finding all calls to your function (Alt-F7), so you can easily see how it's called. Of course, being a dynamic language it can't untangle truly horrible code, but your use case should be fine.

Another mechanism which may fit your case better (since returning two things is a common way for code to smell of missing objects) is to return an object with two attributes.

Title: Good practice for returns in Python


答:
It should be in the commit history but it should not only be in the commit history, imagine for a moment you hire a new developer.  Do you expect that new developer to read every commit message for the past 10 years of your project because a couple of them will be critical to understanding your code base?

Second say the situation but not the code changes, are you going to make "documentation" commits so that you can add commit messages along the lines of "commit message from revision 5432 is now incorrect, here is the current situation."


答:
It should be noted in the commit history but the absolute best place to put the notice is in the same place you define the dependency. If you have for example a maven .pom file that declares your artifact dependencies, I'd do something like:

Directly above your <dependency> line.

Issue #123 would include details about how it crashes, the version you updated to that caused the crashes, and it probably should then get added to your backlog again for revisiting later - it's possible that there's a yet again newer version that fixes the issue. Either automatically by editing the ticket, or manually yourself, it will email the team to let them know about the current issue now, and by being in the tracker it lets people find it again later.

The reason to put it with the dependency declaration is because whoever wants to change the version will see it at the moment they want to change it and understand why they shouldn't.

I wouldn't comment in the source code because I can easily picture a situation where someone runs a check on your dependencies and starts upgrading them. They should not need to scour the codebase for every TODO comment to do that.

Linking to the issue ticket lets a curious developer know how it failed and potentially revisit it later. Without that, it might become fairly static and never be updated again.

Body:
It should be noted in the commit history but the absolute best place to put the notice is in the same place you define the dependency. If you have for example a maven .pom file that declares your artifact dependencies, I'd do something like:

<!-- Do not change the SDK version because it causes Foo crashes. For more detail see Issue #123 -->

Directly above your <dependency> line.

Issue #123 would include details about how it crashes, the version you updated to that caused the crashes, and it probably should then get added to your backlog again for revisiting later - it's possible that there's a yet again newer version that fixes the issue. Either automatically by editing the ticket, or manually yourself, it will email the team to let them know about the current issue now, and by being in the tracker it lets people find it again later.

The reason to put it with the dependency declaration is because whoever wants to change the version will see it at the moment they want to change it and understand why they shouldn't.

I wouldn't comment in the source code because I can easily picture a situation where someone runs a check on your dependencies and starts upgrading them. They should not need to scour the codebase for every TODO comment to do that.

Linking to the issue ticket lets a curious developer know how it failed and potentially revisit it later. Without that, it might become fairly static and never be updated again.


答:
I somewhat agree.

If you write multiply(j,5), j could be of a scalar or matrix type, making multiply() more or less complex, depending on what j is. However, if you abandon the idea of overloading altogether, then the function would have to be named multiply_scalar() or multiply_matrix() which would make it obvious what's happening underneath.

There's code where many of us would prefer it one way and there's code where most of us would prefer it the other way. Most of the code, however, falls into thew middle ground between those two extremes. What you prefer there depends on your background and personal preferences.

Title: I don't understand the arguments against operator overloading

Body:
I just read one of Joel's articles in which he says:

In general, I have to admit that I’m a little bit scared of language features that hide things. When you see the code

```<code>i = j * 5;
</code>```

… in C you know, at least, that j is being multiplied by five and the results stored in i.

But if you see that same snippet of code in C++, you don’t know anything. Nothing. The only way to know what’s really happening in C++ is to find out what types i and j are, something which might be declared somewhere altogether else. That’s because j might be of a type that has operator* overloaded and it does something terribly witty when you try to multiply it.

(Emphasis mine.) Scared of language features that hide things? How can you be scared of that? Isn't hiding things (also known as abstraction) one of the key ideas of object-oriented programming? Everytime you call a method a.foo(b), you don't have any idea what that might do. You have to find out what types a and b are, something which might be declared somewhere  altogether else. So should we do away with object-oriented programming, because it hides too much things from the programmer?

And how is j * 5 any different from j.multiply(5), which you might have to write in a language that does not support operator overloading? Again, you would have to find out the type of j and peek inside the multiply method, because lo and behold, j might be of a type that has a multiply method that does something terribly witty.

"Muahaha, I'm an evil programmer that names a method multiply, but what it actually does is totally obscure and non-intuitive and has absolutely nothing to do whatsoever with multiplying things." Is that a scenario we must take into consideration when designing a programming language? Then we have to abandon identifiers from programming languages on the grounds that they might be misleading!

If you want to know what a method does, you can either glance at the documentation or peek inside the implementation. Operator overloading is just syntactic sugar, and I don't see how it changes the game at all.

Please enlighten me.


答:
The Reason is really quite simple..

Browser

The Accepts header is saying to the server i accept and know how to display this type of file / file content....

Javascript

Why you can change the header on sending a request it in javascript is you could well have created a way to accept this new content type say you encrypted something and sent it as file type encrypted/myencryption your javascript could well know how to decrypt it so it can accept that type of content so it should tell the server it can accept that content

Anchor links

Are nothing more than telling the browser to obtain the file in the href and render it so if the browser can't understand it it was try to parse it and show a download prompt for the file. some servers get around this by just setting the type to text/plain and then the browser will just show the text of the file.

Body:
The Reason is really quite simple..

Browser

The Accepts header is saying to the server i accept and know how to display this type of file / file content....

Javascript

Why you can change the header on sending a request it in javascript is you could well have created a way to accept this new content type say you encrypted something and sent it as file type encrypted/myencryption your javascript could well know how to decrypt it so it can accept that type of content so it should tell the server it can accept that content

Anchor links <a></a>

Are nothing more than telling the browser to obtain the file in the href and render it so if the browser can't understand it it was try to parse it and show a download prompt for the file. some servers get around this by just setting the type to text/plain and then the browser will just show the text of the file.


问:
Why was the first compiler written before the first interpreter?
The first compiler was written by Grace Hopper in 1952 while the Lisp interpreter was written in 1958 by John McCarthy's student Steve Russell. Writing a compiler seems like a much harder problem than an interpreter. If that is so, why was the first compiler written six-years before the first interpreter?</p>

答:
Because interpreters need compilers in order to work.

The above statement isn't really true. Strictly speaking, you can make an interpreter without ever using or otherwise interacting with a compiler. But the results of doing this wouldn't wouldn't look very much like what I think you mean by those terms.

In the strict sense, compilers and interpreters do entirely different things. A compiler reads text from some source, and transforms it into some other format: assembly language, machine code, another high-level language, a data structure, or whatever else. An interpreter, meanwhile, takes in a data structure of some kind, and performs instructions based on it.

What we tend to think of as a "compiler" nowadays is actually a compiler that has been paired with a code generator: a program that takes in data from some source, and outputs code in some format based on what it sees. That's a fairly intuitive use for compilers, and it was one of the first things compilers were created for. But if you look at it another way, this seems very similar to what an interpreter does. It always outputs code instead of performing more general operations, but the principle is the same.

If we look at it from the other side, an interpreter needs to get its data from somewhere. This is just data, so you can build it up in the same ways you'd build up any other kind of data. Since we're talking about interpretation, it seems natural that you could build your data based on instructions in a text file. But to do that, you'd need something to read in the text and create your data structure, and that's a compiler. It's hooked up to the interpreter instead of to a code generator, but it's a compiler all the same.

That's why compilers were written first. The idea of interpreting data structures wasn't new even when compilers were conceived, but compilers were the "missing link" that let programmers build those structures out of text.


答:
My first thought is to either sort the list or keep it in sorted order. This way, you know while you're traversing it once you pass the first condition, you're on the second condition. You can also have early termination once you've passed both the first and second conditions.

I'm assuming that this is a stripped down example though, and you might be doing this on more than one property.

So, the second way I'd do it is to have one list. Add items form condition 1 to the front of the list, add items from condition 2 to the end of the list. Keep a counter of how many items matched condition 1. If the counter is greater than 0, return the first part of the list, if it's 0, then return the list as is.

Title: Filtering a List

Body:
I will try to simplify my problem. Let say I have a collection (more specifically a List) with different types of elements, for explanation purpose let say we have objects "Person" with different age of birth and an ID. I will represent a person like this: {<id>,<year>}

At some point, I want to get a sub list of all the persons born on 1988 and 1989, and if there is no persons born on that years, I want all the persons born in 1990:

```<code>[{1,1988},{2,1988},{3,1982},{4,1995},{5,1989},{6,1989},{7,1990}] ==>
[{1,1988},{2,1988},{5,1989},{6,1989}]

[{1,1990},{2,1981},{3,1983},{4,1993},{5,1981},{6,1989},{7,1990}] ==>
[{6,1989}]

[{1,1990},{2,1981},{3,1983},{4,1993},{5,1981},{6,1985},{7,1990}] ==>
[{1,1990},{7,1990}]
</code>```

Option 0

At first I though about using the filter method on the apache commons library, but this wouldn't work as I would need to know about all the element on the list to decide if a particular element goes on the sub list or not, so I ruled this option out.

Option 1

Then, the simplest way I can see to do this is loop through the list looking for elements that match the first condition (1988 or 1989), and then, if I can't find any, loop again to look for elements that match the second condition (1900). But I don't like this because you have to loop through the list more than once.

Option 2

The other option I can think about is to loop through the list only once, and to have two different sub list, one with the elements that match the first condition and another with the elements that match the second condition. At the end, if the first sub list is empty, we return the second sub list.

Which one of these two is better (more efficient)?

Which would you use and why?

Do you think there is a better solution than these?


问:
What is meant by "OOP hides the state"?
In one of many anti-OOP rants on cat-v.org I found a passage by Joe Armstrong raising several objections against the OOP model, one of which was the following:

Objection 4 – Objects have private state

State is the root of all evil. In particular functions with side effects should be avoided.

While state in programming languages is undesirable, in the real world state abounds. I am highly interested in the state of my bank account, and when I deposit or withdraw money from my bank I expect the state of my bank account to be correctly updated.

Given that state exists in the real world what facilities should programming language provide for dealing with state?

OOPLs say “hide the state from the programmer”. The states is hidden and visible only through access functions.
  Conventional programming languages (C, Pascal) say that the visibility of state variables is controlled by the scope rules of the language.
  Pure declarative languages say that there is no state.
  The global state of the system is carried into all functions and comes out from all functions. Mechanisms like monads (for FPLs) and DCGs (logic languages) are used to hide state from the programmer so they can program “as if state didn’t matter” but have full access to the state of the system should this be necessary.

The “hide the state from the programmer” option chosen by OOPLs is the worse possible choice. Instead of revealing the state and trying to find ways to minimise the nuisance of state, they hide it away.

What exactly is meant by this?  I have very little low level or procedural experience, mostly OOP, so that probably explains how unfamiliar with this I am.  And from a more modern standpoint, now that most of the Object-Oriented hysteria is passed (at least as far as I can tell), how accurate/relevant do you guys think that passage is?

Thanks for your help.

答:
What exactly is meant by this?

In this context, it means that OOP obscures the state of a program by hiding it away from the programmer but still making it visible via (leaky) accessor methods. The argument is that by obscuring the state, it makes it more difficult to work with, and by extension lead to more bugs.

how accurate/relevant do you guys think that passage is?

I feel that it is relevant, but misdirected. There is absolutely an issue if your class leaks the concept of its state to the outside world. There is absolutely an issue if your class tries to obscure the state when it should be manipulated by the outside world. That though is not a failing of OOP as a whole, but with the individual design of the class. I wouldn't say that hiding state itself is an issue - monads do this in functional programming all the time.

In the best of cases, OOP works like the best mix of functional programming and procedural - people can use the class "as if state didn't matter" because the private state used to protect the invariants of the class is hidden, but have freedom to use a well defined public state of the class which abstracts away the details.

Does OOP make it harder for people to achieve this best of cases? Possibly. "Java schools" and the whole Shape/Circle/Rectangle or Car has Wheels school of teaching OO probably have more to blame than the approach itself. Modern OOP takes quite a bit from functional programming, encouraging immutable objects and pure functions while discouraging inheritence to help make it easier to design classes that work well.

Title: What is meant by "OOP hides the state"?


答:
A URI is intended to identify a resource.

Resource refers to the actual thing being retrieved. On a web site, that's typically a page. In a REST API, it would normally be an entity - person, profile, widget, photo, etc.

HTTP headers tell the server things about the client - they don't describe anything about the resource itself, or provide any help in locating that resource.

For example:

Accept-Encoding tells the server that the client knows how to convert or decompress certain content.

Accept-Language tells the server that the client is in a certain locale and prefers content in that locale.

Authorization tells the server that the client thinks it is authorized to access a protected resource.

A common theme with the majority of these request headers is that the server is not obligated to honor them. An Accept-Encoding of gzip does not guarantee that the response will be compressed. An Accept-Language of ur-PK is likely to be ignored when hitting a U.S. site, unless they specifically support Urdu. And the server reserves the right to verify the Authorization header and return a 401 or 403 anyway, if it doesn't like what it sees.

None of these headers are intended to materially change anything about which resource the server provides in response. The Accept header is no different. If a client specifies application/xml and the server only supports application/json, then the server is going to send back JSON - not XML. More importantly, the Accept header can specify multiple types, in which case the server is free to return whichever it prefers (or none of them). As you might imagine, this could easily lead to undefined behavior for the user, but let's ignore that for the moment.

The intent of a hyperlink is to link to a page - page being a certain type of resource. Or, you might be justified in the looser definition of simply linking to a resource, even if that resource is something other than a page (perhaps an image, or a data set). What it is definitely not meant to do, however, is link to a specific representation of a resource. That is for the client and server to negotiate, and the server to ultimately decide.

Accept-Language is an obvious example of why it might be problematic to allow hyperlinks to control headers. It doesn't really make sense, if you think about it. Each user controls his or her own language preference; it's configured in the operating system and/or the browser. The browser should always send the same Accept-Language header, regardless of which page is being visited. If the server supports that language, great; if not, then it will respond with whatever language it thinks is closest.

If this could be changed by hyperlinks, then inbound links could essentially force you into the Chinese-language version of the site, even when your browser and operating system aren't configured to support that language. That makes no sense. If the site supports English, and your browser is English, then it should respond in English, no matter what the hyperlink says.

Likewise, if your browser knows how to display XML as structured data, and can look for XSLs to make it look pretty, but doesn't really know what to do with JSON other than dump it out as plain text, then forcing them to the JSON content by way of a link (if such a thing were possible) is an aggressively user-hostile behaviour. The browser should always be the one to say, "I know how to display X, but not Y, so I would really prefer if you gave me X".

I can understand why you might think it's logical to allow the user of a browser to override this decision. But the truth of the matter is that you're thinking of a few tiny edge cases like downloading a report; 99% of the time, when this choice exists, the user is not qualified or does not have sufficient information to make it.

To put it slightly differently, imagine your parents or grandparents going to download a file and being asked to choose text/csv or text/plain. Are they likely to know the difference? I don't know about yours, but mine often can't even spot the difference between a banner ad and an error message, so there's no way they'd be able to make this choice intelligently. On the other hand, there might be a glimmer of hope if they're given separate links to download an "Excel workbook" or "Text only" - which to them are actually separate resources, not just different representation of the same resource, and the URIs should reflect that.

The user can't be relied upon to understand that these two things are actually the same resource, but different representation. And without changing everything about the way the web works today, we can't assume anything about what they will do with that hyperlink. They might click, or they might right-click -> "save as", or they might copy-and-paste it into their address bar, or they might be using a download manager, or they might still be using IE6, or they might be using some off-brand tablet or mobile device with a proprietary browser... and in many of these cases, they're not going to get the content they want, because either they'll lose the part of the hyperlink that declares the content-type, or their browser won't support it.

Could the HTML spec have been designed 40 years ago to support a content-type attribute in hyperlinks? Maybe, although as I've described in the first several paragraphs, there were strong reasons against it, especially during a time when bandwidth and server resources were scarce and the idea of being able to download the same report in multiple formats (or, frankly, downloading any report at all) honestly hadn't occurred to anyone. But certainly in today's world it would be insane to try adding something like that to the spec; it would completely break backward compatibility and lead to the dreaded "undefined behaviour" in every existing browser.


答:
In Haskell "+", "-", "*", "/" etc are just (infix) functions.

Should you name an infix function "plus" as in "4 plus 2"? Why not, if addition is what your function does. Should you name your "plus" function "+"? Why not.

I think the issue with so called "operators" are, that they mostly resemble mathematical operations and there are not many ways to interpret those and thus there are high expectations about what such a method/function/operator does.

EDIT: made my point more clear


问:
Django CBVs vs FBVs
For creating a large Django project with many apps, my first initial thought was to used Class Based Views (as the Django tutorials seem to emphasize). However, I noticed that due to a lot of the customizations to each app (multiple forms on each page etc), it became very tedious and was much easier to just implement Function Based Views where I just added decorators such as @require_GET and @login_required for easy authentication and method not supported messages, and am thoroughly convinced I will never go back to CBVs.

From a long term support perspective, has anyone had issues with choosing FBVs over CBVs? Am I doing something in the short term that will hurt long term, and could perhaps be solved by custom Class Based Views?

Update 12/2014

I have now become a complete advocate for CBVs! I will never go back! The reusability, inheritance, mixings create for an absolutely reusable and flexible system. I have reduced the amount of code I've used by a huge percent thanks to CBVs. There was admittedly a learning curve and I did not immediately see the results, but after refactoring I could not be happier. For large projects, it seems that CBVs are a necessity.

答:
On a number of occasions, I've had to drop down into code from a package. Some of them are FBV, some are CBV. I always have a harder time with the class based views. I just find it harder to follow. Particularly inheritance can be annoying to debug.

My own code is function based. I just find it very simple to find what I'm after. After all, most of the debugs start with a url. You just look in the url file, and that tells you what to look for in the views file. The view is pretty easy to follow, even if it has a lot of boilerplate (if POST etc...). But basically it's all right there in one place.

Class based views make it unobvious what is being executed. When something is inheriting from something else, the flow goes back and forth between the parent and the child. This isn't great for debugging.

Title: Django CBVs vs FBVs


答:
I'm recasting the question as "Should I communicate critical information I discover to the rest of the team only via commit message?" Because I think that makes it obvious that no, you shouldn't. I try hard to communicate a lot (this is something that most development teams, in my experience, need to put active effort into) and I certainly do everything I can to avoid creating pitfalls or letting them lie.

If the chain of actions leading me to such a discovery were triggered by a ticket, I'd update the ticket (and make sure the people who should know this have visibility), I'd probably mention it face-to-face (hoping to at least leave someone with some nagging sense that "Gee, I think Damon said something about updating that"), and I'd of course leave a comment in the code at the point the SDK was included so that no one could possibly update it without having a chance to see it. I might see if I could jam it in somewhere on our dev wiki, too, although that's done more with an eye toward future hires, not the current team.

It only takes a couple more minutes compared to the time it likely took to encounter and discover the problem. I certainly wouldn't decide that one of the least-used, low-signal pieces of our documentation and leave it at that.


问:
Which development methodology for a solo programmer on a 1 month project?
I've been tasked with a solo project to investigate & resolve memory leaks in 8000 lines of Javascript code.

I anticipate the project to take up to a month.

Please recommend a development methodology I can use to structure my efforts.

Prefer something light & easy to pickup and run with.

Thanks

答:
I'm guessing you don't really have time to read a book on working with legacy code, so here's my two cents (having read Working Effectively with Legacy Code) and having been in a similar position many times (I work for a Fortune 100 company, and periodically large companies have these HUGE project failures which cause them to reconsider investing in old legacy systems, so you end up with huge refactoring projects you hadn't planned to do).

Do SOMETHING.  Don't analyze the crap out of what you're planning to do.  The very fact that you asked about a methodology might indicate that you have a psychological tendency to do this.  Don't.  80% of getting it done right is getting it done -- especially on a small gig like a one month task.

Spend a short amount of time (less than 5% of your total time budget as a rule of thumb) figuring out where you'd like to be at the end.  What does success look like?

Am I working on the right problem?  Are you literally just trying to find a memory leak?  If so, why are we talking about these 8000 lines of code?  There are a limited number of ways to create memory leaks in JS (like circular references), so let's put first-things-first as they say, and make sure this issue is framed up right.

Are you working alone, or with a team?  If you're working with a team, have you figured out how to carve up the work among yourselves?  If not, this will be an exercise in frustration -- get that figured out early, or at least figure out how you're going to decide as the time clicks away.

Analysis/Development.  Once you've got the 4 items above figured out, you're going to have to do the hard work of doing deep analysis -- seeking to understand what the code is doing.  Once you figure out how something is working, codify that understanding by using a divide-and-conquer approach.  That is to say, rewrite some subset of the code "the right way", and replace all references to the old code to the new code in the least intrusive way possible (which often means you have to pick some arbitrary point to "stop pulling the yarn out of the sweater").  You end up with a "clean room" version of the code on one side -- good, known, fully unit tested code (Jasmine is good for unit testing JS by the way), and legacy code on the other side -- untested, unknown quality code that you're trying to slowly replace.


问:
Are there technical limitations or language features that prevent my Python script from being as fast as an equivalent C++ program?
I'm a long-time Python user. A few years ago, I started learning C++ to see what it could offer in terms of speed. During this time, I would continue to use Python as a tool for prototyping. This, it seemed, was a good system: agile development with Python, fast execution in C++.

Recently, I've been using Python more and more again, and learning how to avoid all of the pitfalls and anti-patterns that I was quick to use in my earlier years with the language. It's my understanding that using certain features (list comprehensions, enumerations, etc.) can increase performance.

But are there technical limitations or language features that prevent my Python script from being as fast as an equivalent C++ program?

答:
I kind of hit this wall myself when I took a full-time Python programming job a couple years ago. I love Python, I really do, but when I started to do some performance tuning, I had some rude shocks.

The strict Pythonistas can correct me, but here are the things I found, painted in very broad strokes.

Python memory usage is kind of scary. Python represents everything as a dict -- which is extremely powerful, but has a result that even simple data types are gigantic. I remember the character "a" took 28 bytes of memory. If you're using big data structures in Python, make sure to rely on numpy or scipy, because they are backed by direct byte-array implementation.

That has a performance impact, because it means there are extra levels of indirection at run time, in addition to slogging around huge amounts of memory compared to other languages.

Python does have a global interpreter lock, which means that for the most part, processes are running single-threaded. There may be libraries that distribute tasks across processes, but we were spinning up 32 or so instances of our python script and running each single threaded.

Others can talk to the execution model, but Python is a compile-at-runtime and then interpreted, which means it doesn't go all the way to machine code. That also has a performance impact. You can easily link in C or C++ modules, or find them, but if you just run straight up Python, it's going to have a performance hit.

Now, in web service benchmarks, Python compares favorably to the other compile-at-runtime languages like Ruby or PHP. But it's pretty far behind most of the compiled languages. Even the languages that compile to intermediate language and run in a VM (like Java or C#) do much, much better.

Here is a really interesting set of benchmark tests that I refer to occasionally:

http://www.techempower.com/benchmarks/

(All that said, I still love Python dearly, and if I get the chance to choose the language I'm working in, it's my first choice. Most of the time, I'm not constrained by crazy throughput requirements anyway.)


答:
Based on my personal experience, the Java way of allowing multiple methods, but not overloading operator, means that whenever you see an operator you know exactly what it does.

You do not have to see if * invokes strange code but know that it is a multiply, and it behaves exactly like in the way defined by the Java Language Specification.  This means you can concentrate on the actual behaviour instead of finding out all the wicket stuff defined by the programmer.

In other words, prohibiting operator overload is a benefit to the reader, not the writer, and hence makes programs easier to maintain!


答:
Yes. The primary problem is that the language is defined to be dynamic- that is, you never know what you're doing until you're about to do it. That makes it very hard to produce efficient machine code, because you don't know what to produce machine code for. JIT compilers can do some work in this area but it's never comparable to C++ because the JIT compiler simply can't spend time and memory running, since that's time and memory you're not spending running your program, and there are hard limits on what they can achieve without breaking the dynamic language semantics.

I'm not going to claim that this is an unacceptable tradeoff. But it is fundamental to the nature of Python that real implementations will never be as fast as C++ implementations.

Title: Are there technical limitations or language features that prevent my Python script from being as fast as an equivalent C++ program?

Body:
I'm a long-time Python user. A few years ago, I started learning C++ to see what it could offer in terms of speed. During this time, I would continue to use Python as a tool for prototyping. This, it seemed, was a good system: agile development with Python, fast execution in C++.

Recently, I've been using Python more and more again, and learning how to avoid all of the pitfalls and anti-patterns that I was quick to use in my earlier years with the language. It's my understanding that using certain features (list comprehensions, enumerations, etc.) can increase performance.

But are there technical limitations or language features that prevent my Python script from being as fast as an equivalent C++ program?


答:
Reasoning about a system will be difficult if there are pieces of mutable state that have no single clear "owner".  That doesn't mean that objects should never have mutable state, but rather that objects which do have mutable state should not be used in ways where ownership might be unclear, and conversely that objects which will need to be freely passed around without tracking ownership should be immutable.

In practice, efficient programming frequently requires that some objects have mutable state; such state, however, should be confined, however, to unshared worker objects.  Consider the IEnumerable/IEnumerator interfaces in .NET: if a collection implements IEnumerable, it will allow the items to be read out one at a time.  The actual process of reading out a collection will often require keeping track of which items have been read (a piece of mutable state), but such state is not contained within an implementation of IEnumerable.  Instead, IEnumerable provides a method called GetEnumerator which will return an object that implements IEnumerator and contains enough state to allow items to be read out from the collection.  The fact that the object contains such state will pose no problem, however, if object implementing IEnumerator is not shared.

The best pattern in most cases is to use a mixture of objects which are freely shared but will never be modified (at least not after they've been shared), and objects which have a clear owner, and may be freely modified by that owner, but are never shared with anyone.

Title: What is meant by "OOP hides the state"?

Body:
In one of many anti-OOP rants on cat-v.org I found a passage by Joe Armstrong raising several objections against the OOP model, one of which was the following:

Objection 4 – Objects have private state

State is the root of all evil. In particular functions with side effects should be avoided.

While state in programming languages is undesirable, in the real world state abounds. I am highly interested in the state of my bank account, and when I deposit or withdraw money from my bank I expect the state of my bank account to be correctly updated.

Given that state exists in the real world what facilities should programming language provide for dealing with state?

OOPLs say “hide the state from the programmer”. The states is hidden and visible only through access functions.
  Conventional programming languages (C, Pascal) say that the visibility of state variables is controlled by the scope rules of the language.
  Pure declarative languages say that there is no state.
  The global state of the system is carried into all functions and comes out from all functions. Mechanisms like monads (for FPLs) and DCGs (logic languages) are used to hide state from the programmer so they can program “as if state didn’t matter” but have full access to the state of the system should this be necessary.

The “hide the state from the programmer” option chosen by OOPLs is the worse possible choice. Instead of revealing the state and trying to find ways to minimise the nuisance of state, they hide it away.

What exactly is meant by this?  I have very little low level or procedural experience, mostly OOP, so that probably explains how unfamiliar with this I am.  And from a more modern standpoint, now that most of the Object-Oriented hysteria is passed (at least as far as I can tell), how accurate/relevant do you guys think that passage is?

Thanks for your help.