问:
How is fundamental mathematics efficiently evaluated by programming languages?
As I get more and more involved with the theory behind programming, I find myself fascinated and dumbfounded by seemingly simple things..
I realize that my understanding of the majority of fundamental processes is justified through circular logic

Q: How does this work?

A: Because it does!

I hate this realization! I love knowledge, and on top of that I love learning, which leads me to my question (albeit it's a broad one).

Question:

How are fundamental mathematical operators assessed with programming languages?

How have current methods been improved?

Example

```<code>var = 5 * 5;
</code>```

My interpretation:

```<code>$num1 = 5; $num2 = 5; $num3 = 0;
while ($num2 > 0) {
    $num3 = $num3 + $num1;
    $num2 = $num2 - 1;
}
echo $num3;
</code>```

This seems to be highly inefficient. With Higher factors, this method is very slow while the standard built in method is instantanious. How would you simulate multiplication without iterating addition?

```<code>var = 5 / 5;
</code>```

How is this even done? I can't think of a way to literally split it 5 into 5 equal parts.

```<code>var = 5 ^ 5;
</code>```

Iterations of iterations of addition?
My interpretation:

```<code>$base = 5;
$mod = 5;
$num1 = $base;
while ($mod > 1) {

    $num2 = 5; $num3 = 0;
    while ($num2 > 0) {
        $num3 = $num3 + $num1;
        $num2 = $num2 - 1;
    }
    $num1 = $num3;
    $mod -=1;
}
echo $num3;
</code>```

Again, this is EXTREMELY inefficient, yet I can't think of another way to do this.
This same question extends to all mathematical related functions that are handled automagically.

答:
I'll try to give you an idea of how digital circuits are designed to solve digital processing problems by using the problems you pose: how do CPUs implement additions and multiplications.

Firstly, lets get the direct question out of the way: how does a programming language efficiently evaluate multiplications and additions. The answer is simple, they compile them into multiply and add instructions. For example, the following code:

```<code>a = 1 + 1;
b = a * 20;
</code>```

is simply compiled to something like:

```<code>ADD 1 1  a
MUL a 20 b
</code>```

(note, that the above assembly is for an imaginary CPU that doesn't exist, for simplicity's sake).

At this point you realize that the above answer simply shifts the problem and solve it by hardware magic. The follow-up question is obviously how does that hardware magic work?

Lets look at the simpler problem first: addition.

First we do a familiar problem, adding in regular base 10 numbers:

```<code> 17
+28
</code>```

The first step would be to add 7 and 8. But this results in 15 which is more than a single digit. So we carry the 1:

```<code>(1)
 17
+28
= 5
</code>```

Now we add 1, 1 and 2 together:

```<code> 17
+28
=45
</code>```

So from this we get the following rules:

when the result of addition is more than one digit, we keep the least significant digit and carry the most significant digit forward

if we have a digit carried forward into our column we add it along with the numbers we're adding

Now it's time to interpret the rules above in base 2 - boolean algebra.

So in boolean algebra, adding 0 and 1 together = 1. Adding 0 and 0 = 0. And adding 1 and 1 = 10 which is more than one digit so we carry the 1 forward.

From this we can construct a truth table:

```<code>a b  |  sum  carry
-------------------
0 0  |   0     0
0 1  |   1     0
1 0  |   1     0
1 1  |   0     1
</code>```

From this, we can construct two circuits/boolean equations - one for the output of sum and one for the output of carry. The most naive way is to simply list out all the inputs. Any truth table, no matter how big and complex can be restated in this form:

```<code>(AND inputs in first row) OR (AND of inputs in second row) OR ...
</code>```

This is basically the sum of products form. We only look at outputs that result in a 1 and ignore the 0s:

```<code>sum = (NOT a AND b) OR (a AND NOT b)
</code>```

Let's replace the AND OR and NOT with programming language symbols to make that easier to read:

```<code>sum = (!a & b) | (a & !b)
</code>```

Basically, we've converted the table like so:

```<code>a b  |  sum  equation
-------------------
0 0  |   0
0 1  |   1   (!a & b)
1 0  |   1   (a & !b)
1 1  |   0
</code>```

This can be directly implemented as a circuit:

```<code>ADD 1 1  a
MUL a 20 b
</code>```0

Observant readers would at this point notice that the above logic can actually be implemented as a single gate - an XOR gate which conveniently has the behavior required by our truth table:

```<code>ADD 1 1  a
MUL a 20 b
</code>```1

But if your hardware doesn't provide you with an XOR gate, the steps above is how you'd go about defining and implementing it in terms of AND, OR and NOT gates.

How you'd go about converting logic gates to actual hardware depends on the hardware you have. They can be implemented using various physical mechanisms as long as the mechanism provides some sort of switching behavior. Logic gates have been implemented with everything from jets of water or puffs of air (fluidics) to transisitors (electronics) to falling marbles. It's a big topic in its own right so I'm going to just gloss it over and say that it's possible to implement logic gates as physical devices.

Now we do the same for the carry signal. Since there is only one condition where the carry signal is true, the equation is simply:

```<code>ADD 1 1  a
MUL a 20 b
</code>```2

So carry is simple:

```<code>                _____
 a ------------|     |
               | AND |---- carry
 b ------------|_____|
</code>```

Combining them together we get what's known as the half adder:

```<code>                _____
 a ------;-----|     |
         |     | XOR |---- sum
 b --;---|-----|_____|
     |   |      _____
     |   '-----|     |
     |         | AND |---- carry
     '---------|_____|
</code>```

The equations for the above circuit by the way looks like this:

```<code>sum = a ^ b
carry = a & b
</code>```

The half adder is missing something. We've implemented the first rule - if the result is more than one digit than carry forward, but we haven't implemented the second rule - if there is a carry add it together with the numbers.

So to implement a full adder, an adding circuit that can add numbers that are more than one digit, we need to define a truth table:

```<code>a b c  |  sum  carry
---------------------
0 0 0  |   0     0
0 0 1  |   1     0
0 1 0  |   1     0
0 1 1  |   0     1
1 0 0  |   1     0
1 0 1  |   0     1
1 1 0  |   0     1
1 1 1  |   1     1
</code>```

The equation for sum is now:

```<code>sum = (!a & !b & c) | (!a & b & !c) | (a & !b & !c) | (a & b & c)
</code>```

We can go through the same process to factor out and simplify the equation and interpret it as a circuit etc. as we've done above but I think this answer is getting overly long.

By now you should get an idea of how digital logic is designed. There are other tricks I've not mentioned such as Karnaugh maps (used to simplify truth tables) and logic compilers such as espresso (so that you don't have to factor boolean equations by hand) but the basic is basically what I've outlined above:

Decompose the problem until you can work at single bit (digit) level.

Define the outputs you want using a truth table.

Convert the table to a boolean equation and simplify the equation.

Interpret the equation as logic gates.

Convert your logic circuit to real hardware circuits by implementing logic gates.

That's how fundamental (or rather, low-level) problems are really solved - lots and lots of truth tables. The real creative work is in the breaking down of a complex task such as MP3 decoding to bit level so that you can work on it with truth tables.

Sorry I don't have the time to explain how to implement multiplication. You can try taking a crack at it by figuring out rules of how long multiplication works then interpreting it in binary then try to break it down to truth tables. Or you can read Wikipedia: http://en.wikipedia.org/wiki/Binary_multiplier

Body:
I'll try to give you an idea of how digital circuits are designed to solve digital processing problems by using the problems you pose: how do CPUs implement additions and multiplications.

Firstly, lets get the direct question out of the way: how does a programming language efficiently evaluate multiplications and additions. The answer is simple, they compile them into multiply and add instructions. For example, the following code:

a = 1 + 1;
b = a * 20;

is simply compiled to something like:

ADD 1 1  a
MUL a 20 b

(note, that the above assembly is for an imaginary CPU that doesn't exist, for simplicity's sake).

At this point you realize that the above answer simply shifts the problem and solve it by hardware magic. The follow-up question is obviously how does that hardware magic work?

Lets look at the simpler problem first: addition.

First we do a familiar problem, adding in regular base 10 numbers:

 17
+28

The first step would be to add 7 and 8. But this results in 15 which is more than a single digit. So we carry the 1:

(1)
 17
+28
= 5

Now we add 1, 1 and 2 together:

 17
+28
=45

So from this we get the following rules:

when the result of addition is more than one digit, we keep the least significant digit and carry the most significant digit forward

if we have a digit carried forward into our column we add it along with the numbers we're adding

Now it's time to interpret the rules above in base 2 - boolean algebra.

So in boolean algebra, adding 0 and 1 together = 1. Adding 0 and 0 = 0. And adding 1 and 1 = 10 which is more than one digit so we carry the 1 forward.

From this we can construct a truth table:

a b  |  sum  carry
-------------------
0 0  |   0     0
0 1  |   1     0
1 0  |   1     0
1 1  |   0     1

From this, we can construct two circuits/boolean equations - one for the output of sum and one for the output of carry. The most naive way is to simply list out all the inputs. Any truth table, no matter how big and complex can be restated in this form:

(AND inputs in first row) OR (AND of inputs in second row) OR ...

This is basically the sum of products form. We only look at outputs that result in a 1 and ignore the 0s:

sum = (NOT a AND b) OR (a AND NOT b)

Let's replace the AND OR and NOT with programming language symbols to make that easier to read:

sum = (!a & b) | (a & !b)

Basically, we've converted the table like so:

a b  |  sum  equation
-------------------
0 0  |   0
0 1  |   1   (!a & b)
1 0  |   1   (a & !b)
1 1  |   0

This can be directly implemented as a circuit:

                _____
 a ------------|     |
    \          | AND |-.     ____
     \  ,-NOT--|_____|  \   |    |
      \/                 `--| OR |----- sum
      /\        _____    ,--|____|
     /  `-NOT--|     |  /
    /          | AND |-`
 b ------------|_____|

Observant readers would at this point notice that the above logic can actually be implemented as a single gate - an XOR gate which conveniently has the behavior required by our truth table:

                _____
 a ------------|     |
               | XOR |---- sum
 b ------------|_____|

But if your hardware doesn't provide you with an XOR gate, the steps above is how you'd go about defining and implementing it in terms of AND, OR and NOT gates.

How you'd go about converting logic gates to actual hardware depends on the hardware you have. They can be implemented using various physical mechanisms as long as the mechanism provides some sort of switching behavior. Logic gates have been implemented with everything from jets of water or puffs of air (fluidics) to transisitors (electronics) to falling marbles. It's a big topic in its own right so I'm going to just gloss it over and say that it's possible to implement logic gates as physical devices.

Now we do the same for the carry signal. Since there is only one condition where the carry signal is true, the equation is simply:

carry = a & b

So carry is simple:

                _____
 a ------------|     |
               | AND |---- carry
 b ------------|_____|

Combining them together we get what's known as the half adder:

                _____
 a ------;-----|     |
         |     | XOR |---- sum
 b --;---|-----|_____|
     |   |      _____
     |   '-----|     |
     |         | AND |---- carry
     '---------|_____|

The equations for the above circuit by the way looks like this:

sum = a ^ b
carry = a & b

The half adder is missing something. We've implemented the first rule - if the result is more than one digit than carry forward, but we haven't implemented the second rule - if there is a carry add it together with the numbers.

So to implement a full adder, an adding circuit that can add numbers that are more than one digit, we need to define a truth table:

a b c  |  sum  carry
---------------------
0 0 0  |   0     0
0 0 1  |   1     0
0 1 0  |   1     0
0 1 1  |   0     1
1 0 0  |   1     0
1 0 1  |   0     1
1 1 0  |   0     1
1 1 1  |   1     1

The equation for sum is now:

sum = (!a & !b & c) | (!a & b & !c) | (a & !b & !c) | (a & b & c)

We can go through the same process to factor out and simplify the equation and interpret it as a circuit etc. as we've done above but I think this answer is getting overly long.

By now you should get an idea of how digital logic is designed. There are other tricks I've not mentioned such as Karnaugh maps (used to simplify truth tables) and logic compilers such as espresso (so that you don't have to factor boolean equations by hand) but the basic is basically what I've outlined above:

Decompose the problem until you can work at single bit (digit) level.

Define the outputs you want using a truth table.

Convert the table to a boolean equation and simplify the equation.

Interpret the equation as logic gates.

Convert your logic circuit to real hardware circuits by implementing logic gates.

That's how fundamental (or rather, low-level) problems are really solved - lots and lots of truth tables. The real creative work is in the breaking down of a complex task such as MP3 decoding to bit level so that you can work on it with truth tables.

Sorry I don't have the time to explain how to implement multiplication. You can try taking a crack at it by figuring out rules of how long multiplication works then interpreting it in binary then try to break it down to truth tables. Or you can read Wikipedia: http://en.wikipedia.org/wiki/Binary_multiplier


问:
Using struct to enforce validation of built-in type
Commonly domain objects have properties which can be represented by a built-in type but whose valid values are a subset of the values which may be represented by that type.

In these cases, the value can be stored using the built-in type but it is necessary to ensure values are always validated at the point of entry, otherwise we might end up working with an invalid value.

One way to solve this is to store the value as a custom struct which has a single private readonly backing field of the built-in type and whose constructor validates the provided value. We can then always be sure of only using validated values by using this struct type.

We can also provide cast operators from and to the underlying built-in type so that values can seamlessly enter and exit as the underlying type.

Take as an example a situation where we need to represent the name of a domain object, and valid values are any string which is between 1 and 255 characters in length inclusive. We could represent this using the following struct:

```<code>public struct ValidatedName : IEquatable<ValidatedName>
{
    private readonly string _value;

    private ValidatedName(string name)
    {
        _value = name;
    }

    public static bool IsValid(string name)
    {
        return !String.IsNullOrEmpty(name) && name.Length <= 255;
    }

    public bool Equals(ValidatedName other)
    {
        return _value == other._value;
    }

    public override bool Equals(object obj)
    {
        if (obj is ValidatedName)
        {
            return Equals((ValidatedName)obj);
        }
        return false;
    }

    public static implicit operator string(ValidatedName x)
    {
        return x.ToString();
    }

    public static explicit operator ValidatedName(string x)
    {
        if (IsValid(x))
        {
            return new ValidatedName(x);
        }
        throw new InvalidCastException();
    }

    public static bool operator ==(ValidatedName x, ValidatedName y)
    {
        return x.Equals(y);
    }

    public static bool operator !=(ValidatedName x, ValidatedName y)
    {
        return !x.Equals(y);
    }

    public override int GetHashCode()
    {
        return _value.GetHashCode();
    }

    public override string ToString()
    {
        return _value;
    }
}
</code>```

The example shows the to-string cast as implicit as this can never fail but the from-string cast as explicit as this will throw for invalid values, but of course these could both be either implicit or explicit.

Note also that one can only initialize this struct by way of a cast from string, but one can test whether such a cast will fail in advance using the IsValid static method.

This would seem to be a good pattern to enforce validation of domain values which can be represented by simple types, but I don't see it used often or suggested and I'm interested as to why.

So my question is: what do you see as being the advantages and disadvantages of using this pattern, and why?

If you feel that this is a bad pattern, I would like to understand why and also what you feel is the best alternative.

NB I originally asked this question on Stack Overflow but it was put on hold as primarily opinion-based (ironically subjective in itself) - hopefully it can enjoy more success here.

Above is the original text, below a couple more thoughts, partly in response to the answers received there before it went on hold:

One of the major points made by the answers was around the amount of boiler plate code necessary for the above pattern, especially when many such types are required. However in defence of the pattern, this could be largely automated using templates and actually to me it doesn't seem too bad anyway, but that is just my opinion.

From a conceptual point of view, does it not seem strange when working with a strongly-typed language such as C# to only apply the strongly-typed principle to composite values, rather than extending it to values which can be represented by an instance of a built-in type?

答:
Your way is quite heavy and intensive. I typically define domain entities like:

```<code>public class Institution
{
    private Institution() { }

    public Institution(int organizationId, string name)
    {
        OrganizationId = organizationId;
        Name = name;
        ReplicationKey = Guid.NewGuid();

        new InstitutionValidator().ValidateAndThrow(this);
    }

    public int Id { get; private set; }
    public string Name { get; private set; }
    public virtual ICollection<Department> Departments { get; private set; }

    ... other properties

    public Department AddDepartment(string name)
    {
        var department = new Department(Id, name);
        if (Departments == null) Departments = new List<Department>();
        Departments.Add(department);
        return department;
    }

    ... other domain operations
}
</code>```

In the entity's constructor, validation is triggered using FluentValidation.NET, to make sure you cannot create an entity with invalid state. Note that properties are all readonly - you can only set them through the constructor or dedicated domain operations.

Validation of this entity is a separate class:

```<code>public class InstitutionValidator : AbstractValidator<Institution>
{
    public InstitutionValidator()
    {
        RuleFor(institution => institution.Name).NotNull().Length(1, 100).WithLocalizedName(() =>   Prim.Mgp.Infrastructure.Resources.GlobalResources.InstitutionName);
        RuleFor(institution => institution.OrganizationId).GreaterThan(0);
        RuleFor(institution => institution.ReplicationKey).NotNull().NotEqual(Guid.Empty);
    }
}
</code>```

These validators can also be easily reused, and you write less boilerplate code. And another advantage is that it's readable.

ContentLicense: CC BY-SA 3.0

Body:
Your way is quite heavy and intensive. I typically define domain entities like:

public class Institution
{
    private Institution() { }

    public Institution(int organizationId, string name)
    {
        OrganizationId = organizationId;
        Name = name;
        ReplicationKey = Guid.NewGuid();

        new InstitutionValidator().ValidateAndThrow(this);
    }

    public int Id { get; private set; }
    public string Name { get; private set; }
    public virtual ICollection<Department> Departments { get; private set; }

    ... other properties

    public Department AddDepartment(string name)
    {
        var department = new Department(Id, name);
        if (Departments == null) Departments = new List<Department>();
        Departments.Add(department);
        return department;
    }

    ... other domain operations
}

In the entity's constructor, validation is triggered using FluentValidation.NET, to make sure you cannot create an entity with invalid state. Note that properties are all readonly - you can only set them through the constructor or dedicated domain operations.

Validation of this entity is a separate class:

public class InstitutionValidator : AbstractValidator<Institution>
{
    public InstitutionValidator()
    {
        RuleFor(institution => institution.Name).NotNull().Length(1, 100).WithLocalizedName(() =>   Prim.Mgp.Infrastructure.Resources.GlobalResources.InstitutionName);
        RuleFor(institution => institution.OrganizationId).GreaterThan(0);
        RuleFor(institution => institution.ReplicationKey).NotNull().NotEqual(Guid.Empty);
    }
}

These validators can also be easily reused, and you write less boilerplate code. And another advantage is that it's readable.


问:
Needs (in principle) C++ parenthesis around if statement condition?
In current C++ when body of if statements contain only one command then:

Parenthesis around if condition are mandatory but block are optional. So, both examples are OK:

```<code>if ( condition ) { return 0; }
if ( condition ) return 0;
</code>```

But is it theoretically possible to do it also oppositely?:

Blocks mandatory and parenthesis around if condition optional:

```<code>if ( condition ) { return 0; }
if condition { return 0; }
</code>```

Is it teoretically possible to extend C++ syntax this way? (for example as extension in some C++ compiler or theoretically in some future C++ standard).
Or collides this hypothetical extension with some other C++ syntactic rule?

Note: Personal opinions if this extension should be made or not are irelevant - that's not the question.

EDIT:

Strict interpretation of question has ben answered by Jules.

But if "optional parenthesis" will not mean "optional in every case" but instead "optional in most of cases", then proposed change in C++ still can be made. In rare corner cases like that in Jules answer, compiler can detect ambiquity, and output error:

```<code>"Ambiguous if condition. You must explicitly use parenthesis to resolve it"
</code>```

答:
No. The C and C++ standards explicitly specify that the if keyword must be followed by a parenthesized expression. The compiler is required to reject any program where that's not the case.

The relevant section in the C++ standard is §6.4 Selection statements:

Selection statements choose one of several flows of control.

selection-statement:

```<code>if ( condition ) statement
if ( condition ) statement else statement
</code>```

This is the BNR grammar for the if statement, and the ( and ) are specified and therefore required for the statement to match as valid.

To make your suggested syntax valid will require a revision to the standard, which you are free to propose to the ISO Working Group 21, but you will be expected to defend the proposal.

Body:
No. The C and C++ standards explicitly specify that the if keyword must be followed by a parenthesized expression. The compiler is required to reject any program where that's not the case.

The relevant section in the C++ standard is §6.4 Selection statements:

Selection statements choose one of several flows of control.

selection-statement:

if ( condition ) statement
if ( condition ) statement else statement

This is the BNR grammar for the if statement, and the ( and ) are specified and therefore required for the statement to match as valid.

To make your suggested syntax valid will require a revision to the standard, which you are free to propose to the ISO Working Group 21, but you will be expected to defend the proposal.


问:
How should blank/empty value objects be instantiated/structured?
I was wondering... what is considered the best practice to instantiate blank value objects? (in Java)

E.g. Assume we have some value object class Foo, that could be blank.

Would creating methods like these be a clean solution? <s>(And perhaps adding in a "Blankable" interface or something).</s>

```<code>interface Blankable {
    public Foo blankInstance();
    public boolean isBlank();
}

class Foo implements Blankable {
    public Foo blankInstance();
    public boolean isBlank();
}

Foo foo = something();
if (foo.isBlank()) // Tell the user
</code>```

Or would something more simple like this be better?

```<code>class Foo {
    public static Foo BLANK = /* Some constructor */;
}

Foo foo = something();
if (foo == Foo.BLANK) // Tell the user
</code>```

I am leaning toward the first example, but I am still not sure if it is a widely accepted technique.

I feel a bit resistant to (but still open to) using the Guava Optional< T> class because it seems like a work-around solution in this circumstance.

答:
A solution such as Option<T> is not a so bad idea. In fact, it has been successfully introduced in Haskell as a Maybe (but I don't know if this is the first time this solution has been used). Maybe monads are common in Haskell programs. Since, other languages have adopted the same system. For instance, Scala has an Option type.

If you don't want to become dependent of Guava, you could use Java 8, which introduces the Optional class.

However, Option/Maybe/… types are more relevant in a functional environment, because what you typically want to do is to get a behaviour/a property from the element if it really exists, and to get nothing or a default behaviour/property otherwise. So, a typical use of Options consists in

applying a function A->B on the Option[A] in order to get an Option[B];

switching your code on the basis of the real content of the Option (for instance, by using Pattern matching if the language supports it and if Option has two subtypes, or by using method overload);

or filtering the Options that represent (non-)existing elements.

As an alternative, you could use the Null Object Pattern, in which you have an abstract class MyClass and two concrete subclasses: MyRealClass and MyNullClass. You manipulate instances of MyClass, but generate instances of MyRealClass (if the element is really existing) or MyNullClass (if the element doesn't exist). MyNullClass contains the default behaviours/properties. If the null objects are stateless (which is typically the case), one could cache them, or even make them singletons.

This pattern is described in [Fowler].

[Fowler] Martin Fowler, Kent Beck, Refactoring: Improving the Design of Existing Code.


答:
I like this approach to value types. The concept is great, but I have some suggestions/complains about the implementation.

Casting: I don't like use of casting in this case. The explicit from-string cast is not a problem, but there is not much difference between (ValidatedName)nameValue and new ValidatedName(nameValue). So it seems kind of unnecessary. The implicit to-string cast is worst problem. I think that getting actual string value should be more explicit, because it might accidentally get assigned to string and compiler won't warn you about possible "loss of precision". This kind of precision loss should be explicit.

ToString: I prefer using ToString overloads just for debugging purposes. And I don't think returning the raw value for it is a good idea. This is same issue as with implicit to-string conversion. Getting the internal value should be explicit operation. I believe you are trying to make the structure behave as a normal string to the outside code, but I think in doing so, you are loosing some of the value you get from implementing this kind of type.

Equals and GetHashCode: Structs are using structural equality by default. So your Equals and GetHashCode are duplicating this default behavior. You can remove them and it will be pretty much same thing.

Title: Using struct to enforce validation of built-in type

Body:
Commonly domain objects have properties which can be represented by a built-in type but whose valid values are a subset of the values which may be represented by that type.

In these cases, the value can be stored using the built-in type but it is necessary to ensure values are always validated at the point of entry, otherwise we might end up working with an invalid value.

One way to solve this is to store the value as a custom struct which has a single private readonly backing field of the built-in type and whose constructor validates the provided value. We can then always be sure of only using validated values by using this struct type.

We can also provide cast operators from and to the underlying built-in type so that values can seamlessly enter and exit as the underlying type.

Take as an example a situation where we need to represent the name of a domain object, and valid values are any string which is between 1 and 255 characters in length inclusive. We could represent this using the following struct:

```<code>public struct ValidatedName : IEquatable<ValidatedName>
{
    private readonly string _value;

    private ValidatedName(string name)
    {
        _value = name;
    }

    public static bool IsValid(string name)
    {
        return !String.IsNullOrEmpty(name) && name.Length <= 255;
    }

    public bool Equals(ValidatedName other)
    {
        return _value == other._value;
    }

    public override bool Equals(object obj)
    {
        if (obj is ValidatedName)
        {
            return Equals((ValidatedName)obj);
        }
        return false;
    }

    public static implicit operator string(ValidatedName x)
    {
        return x.ToString();
    }

    public static explicit operator ValidatedName(string x)
    {
        if (IsValid(x))
        {
            return new ValidatedName(x);
        }
        throw new InvalidCastException();
    }

    public static bool operator ==(ValidatedName x, ValidatedName y)
    {
        return x.Equals(y);
    }

    public static bool operator !=(ValidatedName x, ValidatedName y)
    {
        return !x.Equals(y);
    }

    public override int GetHashCode()
    {
        return _value.GetHashCode();
    }

    public override string ToString()
    {
        return _value;
    }
}
</code>```

The example shows the to-string cast as implicit as this can never fail but the from-string cast as explicit as this will throw for invalid values, but of course these could both be either implicit or explicit.

Note also that one can only initialize this struct by way of a cast from string, but one can test whether such a cast will fail in advance using the IsValid static method.

This would seem to be a good pattern to enforce validation of domain values which can be represented by simple types, but I don't see it used often or suggested and I'm interested as to why.

So my question is: what do you see as being the advantages and disadvantages of using this pattern, and why?

If you feel that this is a bad pattern, I would like to understand why and also what you feel is the best alternative.

NB I originally asked this question on Stack Overflow but it was put on hold as primarily opinion-based (ironically subjective in itself) - hopefully it can enjoy more success here.

Above is the original text, below a couple more thoughts, partly in response to the answers received there before it went on hold:

One of the major points made by the answers was around the amount of boiler plate code necessary for the above pattern, especially when many such types are required. However in defence of the pattern, this could be largely automated using templates and actually to me it doesn't seem too bad anyway, but that is just my opinion.

From a conceptual point of view, does it not seem strange when working with a strongly-typed language such as C# to only apply the strongly-typed principle to composite values, rather than extending it to values which can be represented by an instance of a built-in type?


答:
I don't believe any such extension could be made. The problem is that there doesn't seem to be any way to tell if a brace is the start of an initializer or not. For example, the following code would appear to be ambiguous under your proposed change:

```<code>if new T{} { hello(); }
</code>```

The two interpretations are:

Create a new T with an empty initializer list, and if the result is not null call "hello".

Create a new T with the default constructor, and if the result is not null, do nothing. Then call "hello" in either case.

Title: Needs (in principle) C++ parenthesis around if statement condition?

Body:
In current C++ when body of if statements contain only one command then:

Parenthesis around if condition are mandatory but block are optional. So, both examples are OK:

```<code>if ( condition ) { return 0; }
if ( condition ) return 0;
</code>```

But is it theoretically possible to do it also oppositely?:

Blocks mandatory and parenthesis around if condition optional:

```<code>if ( condition ) { return 0; }
if condition { return 0; }
</code>```

Is it teoretically possible to extend C++ syntax this way? (for example as extension in some C++ compiler or theoretically in some future C++ standard).
Or collides this hypothetical extension with some other C++ syntactic rule?

Note: Personal opinions if this extension should be made or not are irelevant - that's not the question.

EDIT:

Strict interpretation of question has ben answered by Jules.

But if "optional parenthesis" will not mean "optional in every case" but instead "optional in most of cases", then proposed change in C++ still can be made. In rare corner cases like that in Jules answer, compiler can detect ambiquity, and output error:

```<code>"Ambiguous if condition. You must explicitly use parenthesis to resolve it"
</code>```

Body:
I don't believe any such extension could be made. The problem is that there doesn't seem to be any way to tell if a brace is the start of an initializer or not. For example, the following code would appear to be ambiguous under your proposed change:

if new T{} { hello(); }

The two interpretations are:

Create a new T with an empty initializer list, and if the result is not null call "hello".

Create a new T with the default constructor, and if the result is not null, do nothing. Then call "hello" in either case.


问:
What is the best way to allow a user to specify a SQL server and database from a Windows application?
I am working on building a Windows application that will require a connection to at least two different Microsoft SQL Server databases (for example, a source and a target), which may or may not be on the same server.

So, in the application settings, I would like the user to be able to specify both the server(s) involved, as well as the source and target databases. I did a little bit of research and immediately found this article on Code Project:

http://www.codeproject.com/Articles/31826/SQL-Server-Authentication-using-SMO

It uses something I wasn't previously aware of called, SQL Server Management Objects:

http://msdn.microsoft.com/en-us/library/ms162169(v=sql.105).aspx

Anyway, I am wondering if SMO is the best way to handle establishing connections to data sources that are not known to me, but will be known by the user of the application. Part of the reason I am asking is that most information I am finding seems to be from roughly 5 years ago and want to make sure there isn't a better way to do this today.

Technical Details: I am looking at building it with Windows Forms or as a WPF application and will be dealing with Microsoft SQL Server 2008 R2 and up (likely 2012 and potentially 2014).

Thank you in advance for any advice, thoughts, or suggestions.

答:
To build on @Mike's solution, This is how I solved a similar problem</p>

```<code>Public Con_Str As String

    Function Get_Con_Str()

        If .......Write yo code here...... Then
            Con_Str= "Initial Catalog=databasename1;" & "Data Source=datasource1;Integrated Security=True;"

        Else
           Con_Str= "Initial Catalog=databasename2;" & "Data Source=datasource2;Integrated Security=True;"
        End If
        Return Con_Str
    End Function
</code>```

Body:
To build on @Mike's solution, This is how I solved a similar problem

Public Con_Str As String

    Function Get_Con_Str()

        If .......Write yo code here...... Then
            Con_Str= "Initial Catalog=databasename1;" & "Data Source=datasource1;Integrated Security=True;"

        Else
           Con_Str= "Initial Catalog=databasename2;" & "Data Source=datasource2;Integrated Security=True;"
        End If
        Return Con_Str
    End Function


问:
Does key-value observing between model and view violate MVC?
In MVC the Controller is the go-between for the View and the Model. So the Controller should be the one that observes or receives changes from the Model and View and updates the other accordingly. I know for sure that doesn't break MVC.

But what if the Controller registers and unregisters the View as observer to the Model? What the view would know is the key path, what kind of change, and what the value is without having a reference to the model object. So if you assign model.title = @"new title" the View can map that property change to an action, like a UILabel subclass assigning self.text = @"new title". Does this break MVC?

答:
No, having the View observe the Model (or perform other read actions on the Model) is a valid implementation of the MVC pattern.

There are two main ways that the MVC pattern is typically implemented and they differ mostly in how the information from the Model gets to the View.

In the first form, all information passes through the Controller, who is made responsible for feeding the View with the information it needs and to transform complex data structures used in the Model (like classes) into simple arrays/dictionaries that the View works with. This form is fairly popular with web frameworks with the philosophy that UX experts with limited coding experience can create the Views.

In the second form, the Controller might connect the View and the Model with each other, but the View itself determines which information to retrieve from the Model. In this form, the View can also observe the Model and be notified of changes without the Controller being involved in the update. I would expect this form more with interactive (non-web) applications.


问:
Defining resource allocation in method documentation
I want to write a library with "no resource leak guarantee" feature. So I shall know whether each method allocates any resource or not.
It may change the code. For example:

```<code>void foo()
{
  methodDontAllocateAnyResources();
  methodCanThrow();
}

void bar()
  methodAllocateSomeResources();
  try{
    methodCanThrow();
  }
  catch(const std::exception& exp){
    releaseAllocatedResources();
    throw;
  }
}
</code>```

Both foo() and bar() functions can throw an exception. It doesn't matter because I let exceptions to propagate. But In bar(), I must catch a possible exception to avoid a resource leak.

In the example I could decide to use or not a try-catch block easily. However, you know, normally we cannot understand whether a method allocates any resource or not by its name. So, I've decided to put this information into method documentation. Doxygen doesn't have such a tag. Also, I cannot find any web resources suggest that.
Do you think using a custom @resource-allocation tag is a good idea?

Thanks

答:
your goal : "no resource leak guarantee"

your propsed solution: using a custom @resource-allocation tag to document all possible resource allocations

I donot think that the idea to document resource allocation will help you to avoid resource leaks.

the chances that you forget to add the resource-documention-tag is at least as high as the chance that you forget to release a resource in a catch or finally block.

In my opition it would be better to have a declarative way to avoid resource leaks like c++ smart pointers.

java and c# have a declarative language construct "using" that takes care of resource-deallocation:

```<code> using (MyResource r = new MyResource()) {
    doSomeThingWith(r);
 }
</code>```

The compiler translates this into something like (java syntax. c++ syntax should be similar)

```<code> MyResource r = null;
 try {
    r = new MyResource();
    doSomeThingWith(r);
 } finally {
    if (r != null) delete r;
 }
</code>```

I donot know if there is something similar to "using" in the c++ world.

Body:
your goal : "no resource leak guarantee"

your propsed solution: using a custom @resource-allocation tag to document all possible resource allocations

I donot think that the idea to document resource allocation will help you to avoid resource leaks.

the chances that you forget to add the resource-documention-tag is at least as high as the chance that you forget to release a resource in a catch or finally block.

In my opition it would be better to have a declarative way to avoid resource leaks like c++ smart pointers.

java and c# have a declarative language construct "using" that takes care of resource-deallocation:

 using (MyResource r = new MyResource()) {
    doSomeThingWith(r);
 }

The compiler translates this into something like (java syntax. c++ syntax should be similar)

 MyResource r = null;
 try {
    r = new MyResource();
    doSomeThingWith(r);
 } finally {
    if (r != null) delete r;
 }

I donot know if there is something similar to "using" in the c++ world.


问:
How to deal with historic exception specifications in maintained C++ code
Today, I discovered a few exception specifications in legacy code I've to maintain, when Cppcheck 1.68 ([Inconclusive] but correctly) pointed out that the specified exceptions are not handled in specific portions of the code.

[Inconclusive] Unhandled exception specification when calling function [...]. Either use a try/catch around the function call, or add a exception specification for [...] also.

But the occurrence of any of them would be catastrophic for the program, so it's a good idea not to handle them locally, and copying the specification over and over the code would be nonsense. And furthermore, exception specifications got deprecated in C++11 (for good reasons).

So, generally spoken: Is the best I can do with exception specifications, removing them?

答:
Exception specifications are not optimal in C++ as also mentioned in the link from Rob K by Herb Sutter, and therefore they are deprecated from the standard in C++11 see § 15.4.18.

Instead of using the exception specifications, an alternative could be to move them to the function comment block, in this way the information is not entirely lost. Don't underestimate the power of well written comments.

If for instance Doxygen was used one could easily use the throws or exception commands to describe the exceptions thrown by the function.

```<code>/**
 * Some function description.
 *
 * @throws SomeException In this or that situation this function will thrown an
 * exception of type SomeException.
 */
void Foo();
</code>```

In my opinion exception specification does not do any good (with the exception of the new noexcept) in C++, due to the problems mentioned by Herb Sutter (see link by Rob K), therefore your are better of removing them, but moving the information to a comment, for the function.

Body:
Exception specifications are not optimal in C++ as also mentioned in the link from Rob K by Herb Sutter, and therefore they are deprecated from the standard in C++11 see § 15.4.18.

Instead of using the exception specifications, an alternative could be to move them to the function comment block, in this way the information is not entirely lost. Don't underestimate the power of well written comments.

If for instance Doxygen was used one could easily use the throws or exception commands to describe the exceptions thrown by the function.

/**
 * Some function description.
 *
 * @throws SomeException In this or that situation this function will thrown an
 * exception of type SomeException.
 */
void Foo();

In my opinion exception specification does not do any good (with the exception of the new noexcept) in C++, due to the problems mentioned by Herb Sutter (see link by Rob K), therefore your are better of removing them, but moving the information to a comment, for the function.


答:
I want to write a library with "no resource leak guarantee" feature. [...] It doesn't matter because I let exceptions to propagate. But In bar(), I must catch a possible exception to avoid a resource leak.

This sounds good, all the way to the last sentence.

Consider using RAII resources and smarter return types to manage resources, instead of internal try/catch blocks.

Alternative implementation for bar:

```<code>struct raii_resource {
{
  raii_resource(type value) : value_{value} {}
  ~raii_resource() { releaseAllocatedResources(value_); }
  type value_;
};

void bar() {
  raii_resource r = methodAllocateSomeResources(); // returns type instance
  methodCanThrow();
}
</code>```

If your function needs to return the allocated resource to the client code, simply wrap the return value in a smart wrapper (that will delete it at the end of scope).

Usually, in C++ you should only use try/catch blocks to handle errors, not to release allocated resources.

If you do this (use raii), the documentation of allocated resources will become irrelevant, because resource leaks are no longer possible.

That said, to add allocations information to the API documentation, I would add it as a @remarks or something similar.

Title: Defining resource allocation in method documentation

Body:
I want to write a library with "no resource leak guarantee" feature. So I shall know whether each method allocates any resource or not.
It may change the code. For example:

```<code>void foo()
{
  methodDontAllocateAnyResources();
  methodCanThrow();
}

void bar()
  methodAllocateSomeResources();
  try{
    methodCanThrow();
  }
  catch(const std::exception& exp){
    releaseAllocatedResources();
    throw;
  }
}
</code>```

Both foo() and bar() functions can throw an exception. It doesn't matter because I let exceptions to propagate. But In bar(), I must catch a possible exception to avoid a resource leak.

In the example I could decide to use or not a try-catch block easily. However, you know, normally we cannot understand whether a method allocates any resource or not by its name. So, I've decided to put this information into method documentation. Doxygen doesn't have such a tag. Also, I cannot find any web resources suggest that.
Do you think using a custom @resource-allocation tag is a good idea?

Thanks

Body:
I want to write a library with "no resource leak guarantee" feature. [...] It doesn't matter because I let exceptions to propagate. But In bar(), I must catch a possible exception to avoid a resource leak.

This sounds good, all the way to the last sentence.

Consider using RAII resources and smarter return types to manage resources, instead of internal try/catch blocks.

Alternative implementation for bar:

struct raii_resource {
{
  raii_resource(type value) : value_{value} {}
  ~raii_resource() { releaseAllocatedResources(value_); }
  type value_;
};

void bar() {
  raii_resource r = methodAllocateSomeResources(); // returns type instance
  methodCanThrow();
}

If your function needs to return the allocated resource to the client code, simply wrap the return value in a smart wrapper (that will delete it at the end of scope).

Usually, in C++ you should only use try/catch blocks to handle errors, not to release allocated resources.

If you do this (use raii), the documentation of allocated resources will become irrelevant, because resource leaks are no longer possible.

That said, to add allocations information to the API documentation, I would add it as a @remarks or something similar.


问:
Is it always safe to shift bool values?
I stumbled about a Cppcheck warning (an inconclusive one), that I mistakenly used & instead of &&:

```<code>/// @param code identifies the command. Only the lower 16 bits of are being processed
int encodeCmdState(bool finished, int code, bool errorneous)
{
    return
        (finished & 1) |
        ((code & 0xffff)<<1) |
        ((err & 1)<< 17);
}
</code>```

I'm not sure if this code (style) reaches back into times where bool wasn't available in C. My first idea would be to simply strip the & 1 normalization from the bool parts. But I want to be sure, so...

Is shifting bool values "portable" and "safe"? Or, more generally:

Does the implicit bool-to-int conversation in arithmetic expressions always normalize values?

答:
According to the C++ standard, §4.5 ad. 6 (On integral promotions):

A prvalue of type bool can be converted to a prvalue of type int, with
  false becoming zero and true becoming one.

According to the C++ standard, §4.7 ad. 4 (On integral conversions):

If the destination type is bool, see 4.12. If the source type is bool,
  the value false is converted to zero and the value true is converted
  to one.

So a boolean true is always converted to 1, and a boolean false is always converted to 0, during integral promotion and conversion.

As an example take a look at this simple and naive example (http://ideone.com/kgxrTW):

```<code>#include <iostream>
using namespace std;

int main() {
    bool a = true;
    bool b = false;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << boolalpha << "a = " << a << endl;
    cout << boolalpha << "b = " << b << endl;

    int c = a << 1;
    int d = b << 1;
    bool e = a << 1;
    cout << "c = " << c << endl;
    cout << "d = " << d << endl;
    cout << "e = " << e << endl;
    return 0;
}
</code>```

The output of which will be:

```<code>a = 1
b = 0
a = true
b = false
c = 2
d = 0
e = true
</code>```

Title: Is it always safe to shift bool values?

Body:
According to the C++ standard, §4.5 ad. 6 (On integral promotions):

A prvalue of type bool can be converted to a prvalue of type int, with
  false becoming zero and true becoming one.

According to the C++ standard, §4.7 ad. 4 (On integral conversions):

If the destination type is bool, see 4.12. If the source type is bool,
  the value false is converted to zero and the value true is converted
  to one.

So a boolean true is always converted to 1, and a boolean false is always converted to 0, during integral promotion and conversion.

As an example take a look at this simple and naive example (http://ideone.com/kgxrTW):

#include <iostream>
using namespace std;

int main() {
    bool a = true;
    bool b = false;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << boolalpha << "a = " << a << endl;
    cout << boolalpha << "b = " << b << endl;

    int c = a << 1;
    int d = b << 1;
    bool e = a << 1;
    cout << "c = " << c << endl;
    cout << "d = " << d << endl;
    cout << "e = " << e << endl;
    return 0;
}

The output of which will be:

a = 1
b = 0
a = true
b = false
c = 2
d = 0
e = true


问:
Why would a program require a specific minimum number of CPU cores?
Is it possible to write code (or complete software, rather than a piece of code) that won't work properly when run on a CPU that has less than N number of cores? Without checking it explicitly and failing on purpose:

IF (noOfCores < 4) THEN don't run properly on purpose

I'm looking at a game's (Dragon Age: Inquisition) minimum system requirements, and it states a minimum of a four-core CPU. Many players say it does NOT run on two-core CPU's and EVEN on Intel Core i3s with two physical and two logical cores. And it's NOT a problem of computing power.

From my understanding, threads are completely isolated from the CPU by the OS since that cannot be done.

Just to clear things out:

I am NOT asking "Can I find out the number of CPU cores from code, and fail on purpose?" ... Such code would be ill-intentioned (forces you to buy a more expensive CPU to run a program - without the need of computational power). I am asking that your code, say, has four threads and fails when two threads are run on the same physical core (without explicitly checking system information and purposely failing).

In short, can there be software that requires multiple cores, without needing additional computing power that comes from multiple cores? It would just require N separate physical cores.

答:
Windows has built-in functionality for this: the function GetLogicalProcessorInformation is in the Windows API. You can call it from your program to get information about cores, virtual cores, and hyperthreading.

So the answer to your question would be: Yes.


问:
Are there established guidelines for code formatting in included files with references to other files?
When developing for the web you will inevitably end up referencing a lot of files that eventually all get included and combined into a finished product. I specifically develop a lot of Wordpress sites and, as an example, the project I'm working on right now includes a file called footer.php which simply contains this code:

```<code><?php wp_footer(); ?>

</body>

</html>
</code>```

Now I'm aware what I'm asking is absolutely non-critical but I'm wondering if there are any established best practices for things like code indentation and other formatting issues within included files. The body tag is obviously nested within the html tag, so should that indentation be kept inside footer.php? At the same time it feels kind of strange to start a file by potentially indenting the first line of code a lot of times depending on where it's included, but it might end up making a big mess if you open a lot of nested tags in a different file, don't account for the nesting in your new file but then close them all in the new file.

答:
In both (X)HTML and PHP, whitespace is largely irrelevant and and indentation is only useful for human readers. The browser reading the HTML and the interpreter processing the PHP will just ignore the indentation.

This makes that the best practice is that you try to makes the codes look nice to a human reader in those files and/or outputs that will read by humans on a regular basis.

The complete page output does not have to be nicely formatted HTML, as it will be only rarely seen by a human.

Files that provide portions to the page output should be formatted in such a way that the structure of the HTML in the file is optimally understandable for the persons editing the file. It usually helps if the opening and closing tags of an element are in the same file (although the body and html tags can be exceptions).


答:
Simply adding tags where you allocate resources just documents where the leaks are likely to occur.  It doesn't actually prevent the leak.

Use RAII when allocating leakable resources - acquire them only in constructors, and then free them in the corresponding destructors.  Watch out for constructors that can throw exceptions.  Either add exception handlers within the constructor to tidy up any already acquired resources, or else wrap each resource in a simple class that does its own RAII.

Beware of raw pointers - when a pointer goes out of scope, it doesn't release the thing it's pointing to.  Prefer storing your RAII-wrapped reources by value, or using smart pointers which will free up the thing they point to.


问:
What is abstraction?
Is there a generally agreed upon definition for what a programming abstraction is, as used by programmers? [Note, programming abstraction is not to be confused with dictionary definitions for the word "abstraction."] Is there an unambiguous, or even mathematical definition? What are some clear examples of abstractions?

答:
For me abstraction is something that doesn't exist "literally", it's something like an idea.
If you express it mathematically, it's not abstract anymore because mathematics are a language to express what happens in your brain so it can be understood by somebody else's brain, so you can't structure your ideas, because if you do, it's not an idea anymore: you would need to understand how a brain works to express an idea model.

Abstraction is something that allows you to interpret reality into something that can be independent from it. You can abstract a beach and a dream, but the beach exists but the dream doesn't. But you could tell both exist, but it's not true.

The hardest thing in abstraction is finding a way to express it so that other people can understand it so it can turn into reality. That's the toughest job, and it can't really be done alone: you have to invent a relative model that works on your ideas and that can be understood by somebody else.

To me abstraction in computer language should be name "mathematicating" the model, it's about reusing ideas that can be communicated, and it's an enormous constraint compared to what can be achieved abstractly.

To put it simply, atoms are next to each others, but they don't care.
A large set of molecules organised into a human being can understand that he is next to somebody, but it can't understand how, it's just how the atoms positionned themselves into some pattern.

One object that is ruled by a concept, in general, cannot "understand" itself. That's why we try to believe in god and why we have an hard time understanding our brain.

Can I have my medal now ?

Title: What is abstraction?

ContentLicense: CC BY-SA 2.5


答:
It could be necessary to have 4 cores because the application runs four tasks in parallel threads and expects them to finish almost simultaneously.

When every thread is executed by a separate core and all threads have the exact same computational workload, they are quite likely (but far from guaranteed) to finish roughly the same time. But when two threads run on one core, the timing will be a lot less predictable because the core will switch context between the two threads all the time.

Bugs which occur because of unexpected thread timing are referred to as "race conditions".

In the context of game development, one plausible architecture with this kind of problem could be one where different features of the game are simulated in real-time by different CPU threads. When each feature runs on an own core, they are all simulated with roughly the same speed. But when two features run on one core, both will only be simulated half as fast as the rest of the game world, which could cause all kinds of weird behaviors.

Note that a software architecture which depends on independent threads running with specific timings is extremely fragile and a sign of very bad understanding of concurrent programming. There are features available in practically all multithreading APIs to synchronize threads explicitly to prevent these kinds of problems.

Title: Why would a program require a specific minimum number of CPU cores?

Body:
Is it possible to write code (or complete software, rather than a piece of code) that won't work properly when run on a CPU that has less than N number of cores? Without checking it explicitly and failing on purpose:

IF (noOfCores < 4) THEN don't run properly on purpose

I'm looking at a game's (Dragon Age: Inquisition) minimum system requirements, and it states a minimum of a four-core CPU. Many players say it does NOT run on two-core CPU's and EVEN on Intel Core i3s with two physical and two logical cores. And it's NOT a problem of computing power.

From my understanding, threads are completely isolated from the CPU by the OS since that cannot be done.

Just to clear things out:

I am NOT asking "Can I find out the number of CPU cores from code, and fail on purpose?" ... Such code would be ill-intentioned (forces you to buy a more expensive CPU to run a program - without the need of computational power). I am asking that your code, say, has four threads and fails when two threads are run on the same physical core (without explicitly checking system information and purposely failing).

In short, can there be software that requires multiple cores, without needing additional computing power that comes from multiple cores? It would just require N separate physical cores.


答:
First of all software threads has nothing to do with hardware threads and is often mixed up. Software threads are pieces of code than can be dispatched and run on it's own within the process context. Hardware threads are mostly managed by the OS and are dispatches to the processor's core when talking about regular programs. These hardware threads are dispatched based on load; the hardware thread dispatcher acts more or less like a load balancer. </p>

<p>However when it comes to gaming, especially high end gaming, sometimes the hardware threads are managed by the game itself or the game instructs the hardware thread dispatcher what to do. That is because every tasks or group of tasks doesn't have the same priority like in a normal program. Because dragon age comes from an high end game studio using high end game engines I can imagine that it uses "manual" dispatch and then the number of cores becomes a minimal system requirement. Any program would crash when I send a piece of code to the 3rd physical core running on a machine with only 1 or 2 cores. </p>

Body:
First of all software threads has nothing to do with hardware threads and is often mixed up. Software threads are pieces of code than can be dispatched and run on it's own within the process context. Hardware threads are mostly managed by the OS and are dispatches to the processor's core when talking about regular programs. These hardware threads are dispatched based on load; the hardware thread dispatcher acts more or less like a load balancer.

However when it comes to gaming, especially high end gaming, sometimes the hardware threads are managed by the game itself or the game instructs the hardware thread dispatcher what to do. That is because every tasks or group of tasks doesn't have the same priority like in a normal program. Because dragon age comes from an high end game studio using high end game engines I can imagine that it uses "manual" dispatch and then the number of cores becomes a minimal system requirement. Any program would crash when I send a piece of code to the 3rd physical core running on a machine with only 1 or 2 cores.


答:
I completely agree with Bart on this, considering that you will rarely if ever see your footer.php as text included in the referencing file you only need to make sure footer.php is human reader friendly. The only time footer.php is seen as text and not a reference is the complete page output in the browser page source which will not be seen by humans.

So essentially ensure each file is nicely formatted so you can easily work on it but do not stress about formatting across referenced files.

Title: Are there established guidelines for code formatting in included files with references to other files?

Body:
When developing for the web you will inevitably end up referencing a lot of files that eventually all get included and combined into a finished product. I specifically develop a lot of Wordpress sites and, as an example, the project I'm working on right now includes a file called footer.php which simply contains this code:

```<code><?php wp_footer(); ?>

</body>

</html>
</code>```

Now I'm aware what I'm asking is absolutely non-critical but I'm wondering if there are any established best practices for things like code indentation and other formatting issues within included files. The body tag is obviously nested within the html tag, so should that indentation be kept inside footer.php? At the same time it feels kind of strange to start a file by potentially indenting the first line of code a lot of times depending on where it's included, but it might end up making a big mess if you open a lot of nested tags in a different file, don't account for the nesting in your new file but then close them all in the new file.


问:
Massive View Controller - IOS - Solutions
I'm sure every new iOS developer has the following problem: The View Controllers get very fast crowded with code for various purposes, easily getting to 500 + lines of code.

This is how it looks like for two basic and common screens:

1) The Form Screen:

2) The Table View Controller Screen

So far I have read about two different solutions:

First Solution: https://bendyworks.com/single-responsibility-principle-ios/.
This is based on Notifications, it completely separates the View Controller from the (Intentions) View Model and thus reduces code in the View Controller.
I think that it has the downside of breaking code, similar to Go-To structures.
It looks like this:

The second solution keeps the same crowded View Controllers (button actions are executed inside VC and so on). but uses libraries like TPKeyboardAvoiding, BlocksKit or other solutions most of them based on categories. With this second solution, code is drastically reduced but the view controller still has a lot of responsibility.

What do you think about these solutions? Which is better? Is there a better one?

答:
I've had to untangle code in massive-sized View Controllers before and it really impeded my ability to navigate content at first. One important thing I realized is that size alone of the View Controller wasn't reason enough to break things apart. There is complexity in having 1 large file and also complexity in having a bunch of little files. Here are some valid reasons to refactor to break a View Controller into smaller parts:

MVC

The View Controller shouldn't be doing much more than being the connecting glue between the View and the Model. If you a lot of network connection code, image manipulation code, etc, then consider breaking those out into helper classes.

Multiple Controls with the View Controller as a data source

If you have a bunch of controls on screen that have your View Controller as data source, consider breaking those into separate data source objects and have them be the data source. Or you can also break them into separate View Controllers (like if you View Controller has a table view in addition to other controller, you can break that into its own Table View Controller class).

Duplicate Code

If you have the exact same code in different View Controllers put that in 1 shared location. That will make your code reusable and help manage the complexity.

Here is some additional advice to minimize View Controller complexity:

Storyboard instead of Programmatic

Creating View elements is a lot of code and frame geometry code is a lot of work as well. If not already consider using auto layout constraints and putting as much of the View elements in the storyboard as possible.

Unnecessary code/comments

Also be sure to remove unnecessary code/comments. A lot of times a new View Controller file will come with methods you are not using. If you aren't using a method like didReceiveMemoryWarning then it is safe to take it out. Also, because the View Controller file is so big sometimes it is scary to remove old code or comments. Don't put that off! It only adds to the complexity.

Notifications

To answer your question about notifications: Notifications aren't a Golden Hammer to use with everything. I find notifications to be useful when multiple View Controllers need to update at the same time because of 1 particular action. Be careful with notifications though, overusing them can cause you a lot of pain trying to track them down.


问:
Which code should I use to inform me of updates on websites?
I don't know if this is the correct place to ask this question but I'll ask it here anyway.

I don't know much about programming (I only ever learned MATLAB!) but I wonder if there is a simple way to write a code to check a website every x minutes, say, to see if a certain thing changes and notify me when it does?

I hope this question is not too vague!

Thanks in advance for your help.

EDIT: I have computer running Windows and one running Ubuntu.

答:
First tell us your operating system. :) You could use all languages. You have to read the html sourcecode of a website (better only the body). Be careful if there are current timestamp and so on.

Another solution would be (if supported) reading the RSS feed.


答:
It is too vague. But you basically need the following things, and glue them together:

A thing that downloads the webpage and saves it to your computer

A thing that compares it to the version you downloaded before this one

A thing that notifies you about the comparison if a difference was found

A thing that runs this whole contraption every x minutes

For the last one, if you are on Linux, then cron is good for running something every x minutes. The rest can be done with many different languages, like Python, but I'm not going to write it all out.

Title: Which code should I use to inform me of updates on websites?

Body:
I don't know if this is the correct place to ask this question but I'll ask it here anyway.

I don't know much about programming (I only ever learned MATLAB!) but I wonder if there is a simple way to write a code to check a website every x minutes, say, to see if a certain thing changes and notify me when it does?

I hope this question is not too vague!

Thanks in advance for your help.

EDIT: I have computer running Windows and one running Ubuntu.


答:
As TommyA pointed out, it is safe, at least under normal circumstances.

But caution is necessary if you deal with unchecked assignments of bool values (from input), for example when copying memory portions (naive IPC approaches using structs), I expected this to be possibly a problem. So I created this simple test case,

```<code>#include <iostream>
#include <cstring>
using namespace std;

int b2i(bool v)
{
    return v << 1;
}

int main() {
    bool v = true;
    cout << "v = " << v << endl;
    cout << "b2i(v) = " << b2i(v) << endl;

    // simulating input:
    memset(&v, -1, sizeof v);

    cout << "b2i(v) = " << b2i(v) << endl;
    return 0;
}
</code>```

and tried it with some compilers. Indeed, the outputs differ.

C++14 and C++ 4.9.2:

```<code>v = 1
b2i(v) = 2
b2i(v) = 2
</code>```

C++ 4.3.2 (also in Borland 0x0564):

```<code>v = 1
b2i(v) = 2
b2i(v) = 510
</code>```

Title: Is it always safe to shift bool values?

Body:
I stumbled about a Cppcheck warning (an inconclusive one), that I mistakenly used & instead of &&:

```<code>/// @param code identifies the command. Only the lower 16 bits of are being processed
int encodeCmdState(bool finished, int code, bool errorneous)
{
    return
        (finished & 1) |
        ((code & 0xffff)<<1) |
        ((err & 1)<< 17);
}
</code>```

I'm not sure if this code (style) reaches back into times where bool wasn't available in C. My first idea would be to simply strip the & 1 normalization from the bool parts. But I want to be sure, so...

Is shifting bool values "portable" and "safe"? Or, more generally:

Does the implicit bool-to-int conversation in arithmetic expressions always normalize values?

Body:
As TommyA pointed out, it is safe, at least under normal circumstances.

But caution is necessary if you deal with unchecked assignments of bool values (from input), for example when copying memory portions (naive IPC approaches using structs), I expected this to be possibly a problem. So I created this simple test case,

#include <iostream>
#include <cstring>
using namespace std;

int b2i(bool v)
{
    return v << 1;
}

int main() {
    bool v = true;
    cout << "v = " << v << endl;
    cout << "b2i(v) = " << b2i(v) << endl;

    // simulating input:
    memset(&v, -1, sizeof v);

    cout << "b2i(v) = " << b2i(v) << endl;
    return 0;
}

and tried it with some compilers. Indeed, the outputs differ.

C++14 and C++ 4.9.2:

v = 1
b2i(v) = 2
b2i(v) = 2

C++ 4.3.2 (also in Borland 0x0564):

v = 1
b2i(v) = 2
b2i(v) = 510


答:
To complete on RemcoGerlich answer from a Linux perspective:

download a page using a command like wget or curl or a library like libcurl (which has many wrapping, including for Python, Guile, etc...)

compare two files with diff or cmp (or code the simple loop reading them and comparing byte by byte)

to notify you about changes: you could send email (e.g. programmatically with vmime, or popen a mail or sendmail command, or code a mailcommand with a here document....); you could also be notified on the desktop e.g. with notify-send

to do something periodically, a crontab(5) entry.

As I commented, it could be a bad idea (so don't run that too often, at most every 30 minutes to avoid crushing the website). You might be interested by RSS. And doing that automatically might be against the rules of the website! And it might not work if the website is using cookies or sessions, etc...

BTW, some sites offer a so-called Web API which could be useful, e.g. because they are providing the info perhaps in JSON format. Read also about web services & Web Sockets & REST & robots.txt


问:
Is it possible to protect client side algorithms 100%?
If you had a pretty novel idea that involved a new algorithm. Like lets say you were the first person to think of orbitz.com or kayak.com (travel sites) and you were able to and wanted to implement all of the novel algorithm clientside in javascript. </p>

<p>Is it possible to obfuscate it 100% where you cant reverse engineer it like this reverse engineer javascript obfuscators  , or are developers still forced to keep sensitive algorithms server side if they want to completely protect them (or at least have a better chance of doing so)? </p>

答:
If you want someone to be able to run a program, you have to give them the program. (Duh!) If you want the CPU to execute the program, the CPU has to understand the program. (Duh again.) Computers are stupid, much stupider than humans. Ergo, if the CPU can understand the program, a human can too.

One way would be to give your users both the program and the CPU. Make the computer a black box where they put something in and get something out, and that's it. Note, however, that this is hard. Game console designers spend millions, maybe billions on protecting their hardware and still they get cracked pretty fast. (And it's usually not nefarious crime syndicates selling pirated games, but curious students wanting to run Linux on their XBox.)

The better way is to give them neither: keep the computer and the program in your possession and simply offer a service.

Or, just don't worry about it.


答:
Since it is possible to use virtualize to have more virtual cores than physical and the software would not know it is running on a virtualize and instead think that it does have that many physical cores, I would say such software is not possible.

That is to say, it is not possible to write software that will always stop on less than N cores.

As others have pointed out, there are software solutions that can potentially check, especially if the OS and code being used has little protection against race conditions when N processes run on <N processors.  The real trick is code that will fail when you have less than N processors but won't fail when you do have N processors but have an OS that may assign work to less than N processors.


问:
Would a statically typed alternative to JavaScript on webpages be practical?
Preference for dynamic and static typing is largely a matter of taste, and different people find them more or less suitable in different situations.

My question is, would it be technically possible to have a statically-typed alternative to JavaScript for client-side web page augmentation etc.?

答:
It's technically possible to write client-side scripts in any scripting language that the user agent (browser) supports. In practice, the only widely supported language is JavaScript / ECMAScript. Convincing browser makers to implement and support a new language at this stage is unlikely to succeed; thus, if you wanted to use a new statically typed client-side language, you would need to either translate the new language to JavaScript, or implement an interpreter for it in JavaScript.

There are several projects that already do something like this; for example, Google Web Toolkit, as mentioned in one of the other answers.


问:
Is throwing an exception from a property bad form?
I've always been of the mindset that properties (ie, their set/get operations) should be fast/immediate and failure-free. You should never have to try/catch around getting or setting a property.

But I'm looking at some ways to apply role-based security on the properties of some objects. For instance an Employee.Salary property. Some of the solutions I've run across that others have tried (one in particular is the AOP example here) involve throwing an exception if the accessor doesn't have the right permissions - but this goes against a personal rule that I've had for a long time now.

So I ask: am I wrong? Have things changed? Has it been accepted that properties should be able to throw exceptions?

答:
I would definitely argue that there is a flaw in the design if you feel the need to throw exceptions from a property setter or getter.

A property is an abstraction that represents something that is just a value. And you should be able to set a value without fearing that doing so could throw an exception.*

If setting the property results in a side effect, that that should really be implemented as a method instead. And if it doesn't produce any side effects, then no exception should be thrown.

One example already mentioned in a different answer is the Stream.Position property. This does produce side effects, and may throw exceptions. But this property setter is basically just a wrapper around Stream.Seek that you could call instead.

Personally, I believe that the position should not have been a writeable property.

Another example where you could be tempted to throw an exception from a property setter is in the validation of data:

```<code>public class User {
    public string Email {
        get { return _email; }
        set {
            if (!IsValidEmail(value)) throw InvalidEmailException(value);
            _email = value;
        }
    }
</code>```

But there is a better solution to this problem. Introduce a type representing a valid email address:

```<code>public class Email {
    public Email(string value) {
        if (!IsValidEmail(value)) throw new InvalidEmailException(value);
        ...
    }
    ...
}

public class User {
    public Email Email { get; set; }
}
</code>```

The Email class ensures that it cannot hold a value that is not a valid email address, and classes that need to store emails are relieved of the duty of validating them.

This also leads to higher cohesion (an indicator of good software design) - the knowledge about what an email address is, and how it is validated, exists only in the Email class, which has only that concern.

* ObjectDisposedException is the only valid exception (no pun intended) I can think of at the moment.

Body:
I would definitely argue that there is a flaw in the design if you feel the need to throw exceptions from a property setter or getter.

A property is an abstraction that represents something that is just a value. And you should be able to set a value without fearing that doing so could throw an exception.*

If setting the property results in a side effect, that that should really be implemented as a method instead. And if it doesn't produce any side effects, then no exception should be thrown.

One example already mentioned in a different answer is the Stream.Position property. This does produce side effects, and may throw exceptions. But this property setter is basically just a wrapper around Stream.Seek that you could call instead.

Personally, I believe that the position should not have been a writeable property.

Another example where you could be tempted to throw an exception from a property setter is in the validation of data:

public class User {
    public string Email {
        get { return _email; }
        set {
            if (!IsValidEmail(value)) throw InvalidEmailException(value);
            _email = value;
        }
    }

But there is a better solution to this problem. Introduce a type representing a valid email address:

public class Email {
    public Email(string value) {
        if (!IsValidEmail(value)) throw new InvalidEmailException(value);
        ...
    }
    ...
}

public class User {
    public Email Email { get; set; }
}

The Email class ensures that it cannot hold a value that is not a valid email address, and classes that need to store emails are relieved of the duty of validating them.

This also leads to higher cohesion (an indicator of good software design) - the knowledge about what an email address is, and how it is validated, exists only in the Email class, which has only that concern.

* ObjectDisposedException is the only valid exception (no pun intended) I can think of at the moment.


问:
Using GPL’d software in a proprietary web application
We are developing website that we charge money from members to join it as membership annual cost, so, we decided to put a plan for the second stage so we are choosing now the load balancer that we will use for our web application. I suggested HAProxy but one of my friends told me that HAProxy is under GPL and LGPL so if we used it we will have to provide source code of our website to our customers. But as I know that our website is providing service not redistributing  haproxy binary and we don't modify it so I disagreed  him.

Now I am truly very very confused so please answer me: if we used HAproxy as our load balancer will we have to provide our website source code for customers? And the OpenSSL is GPL licensed so if we used it in our web application will we have to provide our web application source code for customers? And is using HAProxy as our load balancer considered redistributing or providing service? Didn't all websites considered providing service not redistributing HAProxy if they used it as there load balancer?

答:
Your friend is wrong.

First, the GPL only requires to disclose your source code to your customers when your software runs on their machines. Your load balancer runs on your own hardware, so you don't need to provide the sourcecode to anyone who connects to it. There is a variant of the GPL which requires to disclose the sourcecode to everyone who "interacts with [the software] remotely through a computer network" called the AGPL, but HAProxy isn't licensed under it and OpenSSL isn't either.

Second, even if your load-balancer would be under the AGPL, this would not affect the application behind it. The GPL only "infects" other code when GPL and non-GPL code are combined to create a single software product. But this is not the case here. The load-balancer communicates with the application "at arms reach". Load balancer and website are separate pieces of software which are useful on their own, so different licenses can apply to them.


问:
How to differentiate between exceptions coming from system and business logic?
I would like to differentiate between exceptions coming from business logic like

requested database record does not exist

attempt to store invalid business data (validation failed)

provided CSV file has wrong format

from standard system exceptions like

database connection timeout

file I/O error

out of memory

I generate business logic exceptions in my code as a quick way to quit undergoing operation when something goes wrong (instead of returning false and other techniques).

So I would implement different handling of these types of exceptions:

my business logic exception: display as ordinary plain error message

standard system exception: log exception to file, user is given options Abort / Ignore (/Retry) etc...

The best idea I could figure out was to create common ancestor for business exceptions and check it in the handler. I think this was original purpose of ApplicationException which is now deprecated. Do you think I can resurrect it for the purpose or is there some better approach?

答:
If you expect certain exceptions to be handled at the top level of the program (or close to it), create a specific exception class for them so you can identify them. That way you don't accidentally catch exceptions that arise from program bugs or unrecoverable errors (e.g. out of memory).

I don't know the purpose of ApplicationException but Microsoft's documentation warns against extending it, and I don't think you'd gain anything from doing so. You wouldn't want to catch ApplicationException directly since there might be ApplicationExceptions your application didn't define. So you'd need to create a subclass specifically for your application, and in that case you could just as easily extend Exception.


答: It could be that there are three threads doing something (generating backgrounds or generating NPC movement) and passing events to a fourth, which is supposed to aggregate/filter the events and update the view model. If the fourth thread doesn't get all the events (because it's not scheduled on a core) then the view model doesn't get updated correctly. This may only happen sporadically, but those cores need to be available at any point. This might explain why you're not seeing high CPU usage all the time, but the game is failing to work properly anyway.</p>


问:
How to let users share custom code content under the mobile app store restrictions?
Situation

Mobile application store owners are known to explicitly forbid some application extensibility scenarios.

Apple:

2.7 Apps that download code in any way or form will be rejected

2.8 Apps that install or launch other executable code will be rejected

https://developer.apple.com/app-store/review/guidelines/#functionality

Microsoft:

3.9 All app logic must originate from, and reside in, your app package
  Your app must not attempt to change or extend the packaged content through any form of dynamic inclusion of code that changes how the application behaves with regard to Store certification requirements. Your app should not, for example, download a remote script and subsequently execute that script in the local context of the app package.

http://msdn.microsoft.com/en-us/library/windows/apps/hh694083.aspx

Google (not sure if it is as restrictive):

An app downloaded from Google Play may not modify, replace or update its own APK binary code using any method other than Google Play's update mechanism.

https://play.google.com/about/developer-content-policy.html

Problem

Some applications such as Minecraft and Codea are meant to let users produce content (not just consume it). Codea projects are obviously an executable code and Minecraft is known to be Turing-complete.

Now they don't have any built-in online community gallery capabilities, but it would be easy to imagine them added in future. This is something users would definitely appreciate:

https://gaming.stackexchange.com/questions/148549/how-to-transfer-minecraft-pocket-edition-world-between-ipads

http://codea.io/talk/discussion/527/best-way-to-share-code-straight-from-ipad/p1

Microsoft has already done this with their Project Spark (PC/Xbox) and Media Molecule/Sony have this in their Little Big Planet (PS, also Turing-complete).

Questions

1) Obviously specific store owners make their own, often random and unfair decisions, but generally where is the line between 'code' and user-created content?

2) Is it a conscious decision to favour security over experience or a simple case of  short-sightedness?

3) What can be done to work around today? I am aware of the browser technology but am only interested in application development.

答:
For a really definitive answer, you will have to ask Apple, Microsoft and Google for what they consider to be code and why those restrictions are in place.

Generally, "code" means instructions that can be executed on the device in question, either directly or through an interpreter. It thus also includes scripts.

These restrictions probably exist to give the store owners a fighting chance against malware. It should be noted that due to the way that apps on these mobile platforms are insulated from each other, virus-scanners are also prohibited from doing much of the work in protecting you that you might take for granted on a PC.

If you really want to create an app that can execute downloaded third-party code, your only legal option seems to be to provide it outside the official stores. You run a big risk that the app will be regarded with suspicion in any case.


答:
It may be possible to do this "by accident" with careless use of core affinity. Consider the following pseudocode:

start a thread

in that thread, find out which core it is running on

set its CPU affinity to that core

start doing something computationally intensive / loop forever

If you start four of those on a two-core CPU, then either something goes wrong with the core affinity setting or you end up with two threads hogging the available cores and two threads that never get scheduled. At no point has it explicitly asked how many cores there are in total.

(If you have long-running threads, setting CPU affinity generally improves throughput)

The idea that game companies are "forcing" people to buy more expensive hardware for no good reason is not very plausible. It can only lose them customers.

Edit: this post has now got 33 upvotes, which is quite a lot given that it's based on educated guesswork!

It seems that people have got DA:I to run, badly, on dual-core systems: http://www.dsogaming.com/pc-performance-analyses/dragon-age-inquisition-pc-performance-analysis/ That analysis mentions that the situation greatly improves if hyperthreading is turned on. Given that HT does not add any more instruction issue units or cache, it merely allows one thread to run while another is in a cache stall, that suggests strongly that it's linked to purely the number of threads.

Another poster claims that changing the graphics drivers works: http://answers.ea.com/t5/Dragon-Age-Inquisition/Working-solution-for-Intel-dual-core-CPUs/td-p/3994141 ; given that graphics drivers tend to be a wretched hive of scum and villany, this isn't surprising. One notorious set of drivers had a "correct&slow" versus "fast&incorrect" mode that was selected if called from QUAKE.EXE. It's entirely possible that the drivers behave differently for different numbers of apparent CPUs. Perhaps (back to speculation) a different synchronisation mechanism is used. Misuse of spinlocks?

"Misuse of locking and synchronisation primitives" is a very, very common source of bugs. (The bug I'm supposed to be looking at at work while writing this is "crash if changing printer settings at same time as print job finishes").

Edit 2: comments mention OS attempting to avoid thread starvation. Note that the game may have its own internal quasi-scheduler for assigning work to threads, and there will be a similar mechanism in the graphics card itself (which is effectively a multitasking system of its own). Chances of a bug in one of those or the interaction between them are quite high.

www.ecsl.cs.sunysb.edu/tr/ashok.pdf (2008) is a graduate thesis on better scheduling for graphics cards which explicitly mentions that they normally use first-come-first-served scheduling, which is easy to implement in non-preemptive systems. Has the situation improved? Probably not.


答:
If I understand what you're asking, it's possible, but it's a very, very bad thing.

The canonical example of what you're describing would be maintaining a counter which is incremented by multiple threads.  This requires almost nothing in therms of computing power but requires careful coordination among the threads.  As long as only one thread at a time does an increment (which is actually a read followed by an addition followed by a write), its value will always be correct.  This is because one thread will always read the correct "previous" value, add one and write the correct "next" value.  Get two threads into the action at the same time and both will read the same "previous" value, get the same result from the increment and write the same "next" value.  The counter will effectively have been incremented only once even though two threads think they each did it.

This dependency between timing and correctness is what computer science calls a race condition.

Race conditions are often avoided by using synchronization mechanisms to make sure threads wanting to operate on a piece of shared data have to get in line for access.  The counter described above might use a read-write lock for this.

Without access to the internal design of Dragon Age: Inquisition, all anyone can do is speculate about why it behaves the way it does.  But I'll have a go based on some things I've seen done in my own experience:

It might be that the program is based around four threads that have been tuned so everything works when the threads run mostly-uninterrupted on their own physical cores.  The "tuning" could come in the form of rearranging code or inserting sleeps in strategic places to mitigate race-condition-induced bugs that cropped up during development.  Again, this is all conjecture, but I've seen race conditions "resolved" that way more times than I care to count.

Running a program like that way on anything less capable than the environment for which it was tuned introduces timing changes that are a result of the code not running as quickly or, more likely, context switches.  Context switches happen in physical (i.e., the CPU's physical cores are switching between the work its logical cores are holding) and logical (i.e., the OS on the CPU is assigning work to the cores) ways, but either is a significant divergence from what would be the "expected" execution timing.  That can bring out bad behavior.

If Dragon Age: Inquisition doesn't take the simple step of making sure there are enough physical cores available before proceeding, that's EA's fault.  They're probably spending a small fortune fielding support calls and emails from people who tried to run the game on too little hardware.


问:
What's the benefit of having everything as an object in dynamically typed programming language?
modern dynamic programming languages like Python, Ruby and Javascript all take the approach of treating everything as an object, what's the benefit of this approach, and what's the curse of it?

Benefit I can think of: first class functions, duck typing.

Drawbacks:performance issue, especially performance of primitive types like integer etc.

答:
Performance doesn't matter. Or rather: compared to providing developers the best tool with which they can express and model what they want the computer to do, performance is the easier problem to solve.

Types, classes, objects, functions, lambdas - all those concepts help organize your thoughts and your code. At this point, they're all quite unrelated to how the processor is going to actually execute your code. The 'curse', if there is one, is when your language of choice forces you into a particular model (classes vs object, of object vs functional) when you'd like to use another for a particular problem.

Regarding actual implementation, I don't know enough to comment about it. However consistency is valuable: having everything appear as an object to the developer might make implementing the language slightly harder, but makes using it much easier. It doesn't matter (in most cases) wether internally it has special treatment because it's an int or not.


问:
Advice for Evaluating Web Frameworks (or software libraries in general)
At my workplace we are currently looking to redesign our application stack on the web. We are satisfied and accepted that our server will be Node.js but we are finding it very difficult to find a front-end framework we can agree on.

I'm not asking for opinions on particular frameworks (there are tons of other resources for that) but our primary candidates are Angular, React + Flux + (other components for Routing, Models, etc) and Knockout.

We're looking for advice on how to evaluate each choice and come up with a best fit for ourselves. We've spent time researching the opinions of others but it's not inspiring confidence. http://todomvc.com/ was recommended as a place to get a feel for each framework but we want to get deeper understanding than a simple implementation of a todo list app.

Of course, we considered the idea of prototyping each framework but worry we would be spending too much time and we have to present our plan to our boss for acceptance. We feel that spending weeks prototyping would help us but maybe there is a better way to approach it?

Another valid answer may be that evaluation between several proven frameworks is useless. We are being somewhat pressured to make a choice and perhaps living with any of the choices is better than spending a lot of time deliberating. Thoughts?

答:
Hold a meeting and decide which factors (ease of use, scalability, etc.) you are going to use to judge each framework.

Then, write a small prototype application, making several versions that use each of the different candidate frameworks.  Have another meeting (code-review style), and evaluate each of the frameworks on the factors you decided on in the first meeting, and then make your decision.

There are books you can buy and several articles on the web that will help you make your decision.

See Also

Selecting an MVC Framework -- Already has prototype application code to help you choose.

Micro Framework Chooser

Template Engine Chooser