问:
How to use the Decorator pattern to add little functionality to big objects?
This question regards the usage of the Decorator pattern to add little functionality to objects of large classes.

Following the classic Decorator pattern, please consider the following class structure:

For example, imagine this happens inside a game. Instances of ConcreteCharacterDecorator are meant to add little functionality to the ConcreteCharacter they are 'wrapping'.

For instance, methodA() returns an int value representing the damage the character inflicts on enemies. The ConcreteCharacterDecorator simply adds to this value. Thus, it only needs to add code to methodA(). The functionality of methodB() stays the same.

ConcreteCharacterDecorator will look like this:

```<code>class ConcreteCharacterDecorator extends AbstractCharacterDecorator{

    ConcreteCharacter character;

    public ConcreteCharacterDecorator(ConcreteCharacter character){
        this.character = character;
    }

    public int methodA(){
        return 10 + character.methodA();
    }

    public int methodB(){
        character.methodB(); // simply delegate to the wrapped object.
    }

}
</code>```

This is no problem with small classes containing two methods.

But what if AbstractCharacter defined 15 methods? ConcreteCharacterDecorator would have to implement all of them, even though it's only meant to add little functionality.

I will end up with a class containing one method that adds a little functionality, and another 14 methods that simply delegate to the inner object.

It would look like so:

```<code>class ConcreteCharacterDecorator extends AbstractCharacterDecorator{

    ConcreteCharacter character;

    public ConcreteCharacterDecorator(ConcreteCharacter character){
        this.character = character;
    }

    public int methodA(){
        return 10 + character.methodA();
    }

    public int methodB(){
        character.methodB(); // simply delegate to the wrapped object.
    }
    public int methodC(){
        character.methodC(); // simply delegate to the wrapped object.
    }
    public int methodD(){
        character.methodD(); // simply delegate to the wrapped object.
    }
    public int methodE(){
        character.methodE(); // simply delegate to the wrapped object.
    }
    public int methodF(){
        character.methodF(); // simply delegate to the wrapped object.
    }
    public int methodG(){
        character.methodG(); // simply delegate to the wrapped object.
    }
    public int methodH(){
        character.methodH(); // simply delegate to the wrapped object.
    }
    public int methodI(){
        character.methodI(); // simply delegate to the wrapped object.
    }
    public int methodJ(){
        character.methodJ(); // simply delegate to the wrapped object.
    }
    public int methodK(){
        character.methodK(); // simply delegate to the wrapped object.
    }
    public int methodL(){
        character.methodL(); // simply delegate to the wrapped object.
    }
    public int methodM(){
        character.methodM(); // simply delegate to the wrapped object.
    }
    public int methodN(){
        character.methodN(); // simply delegate to the wrapped object.
    }
    public int methodO(){
        character.methodO(); // simply delegate to the wrapped object.
    }

}
</code>```

Obviously, very ugly.

I'm probably not the first to encounter this problem with the Decorator. How can I avoid this?

答:
If AbstractCharacter has 15 methods, it probably needs to be broken down into smaller classes. That aside, there's not much else you can do without the language providing some sort of special syntax support for delegation. Simply leave a comment where all the delegation starts so the reader knows he need not look any further down. As for writing all the forwarding methods, your IDE can help there.

That aside, it's my opinion that Decorator works best with interfaces. You generally either want to limit your abstraction to a finite (possibly 0) number of subclasses or go all the way with an interface. Unlimited inheritance has all of the drawbacks of interfaces (you could be passed an incorrect implementation) but you don't get full flexibility (you can only subclass one thing.) Worse yet, it opens you up to the Fragile Base Class Problem and it's not as flexible as composition (you make SubclassA and SubclassB, but then can't inherit from both to make SubclassAB with features of both). So I find being forced into an inheritance tree just to support decoration to be a kludge.


问:
Patterns for propagating changes up an object model..?
Here's a common scenario that's always frustrating for me to deal with.

I have an object model with a parent object. The parent contains some child objects. Something like this.

```<code>public class Zoo
{
    public List<Animal> Animals { get; set; }
    public bool IsDirty { get; set; }
}
</code>```

Each child object has various data and methods

```<code>public class Animal
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void MakeMess()
    {
        ...
    }
}
</code>```

When the child changes, in this case when the MakeMess method is called, some value in the parent needs to be updated. Let's say when a certain threshold of Animal's have made a mess, then the Zoo's IsDirty flag needs to be set.

There are a few ways to handle this scenario (that I know of).

1) Each Animal can have a parent Zoo reference in order to communicate changes.

```<code>public class Animal
{
    public Zoo Parent { get; set; }
    ...

    public void MakeMess()
    {
        Parent.OnAnimalMadeMess();
    }
}
</code>```

This feels like the worst option since it couples Animal to its parent object. What if I want an animal who lives in a house?

2) Another option, if you're using a language that supports events (like C#) is to have the parent subscribe to change events.

```<code>public class Animal
{
    public event OnMakeMessDelegate OnMakeMess;

    public void MakeMess()
    {
        OnMakeMess();
    }
}

public class Zoo
{
    ...

    public void SubscribeToChanges()
    {
        foreach (var animal in Animals)
        {
            animal.OnMakeMess += new OnMakeMessDelegate(OnMakeMessHandler);
        }
    }

    public void OnMakeMessHandler(object sender, EventArgs e)
    {
        ...
    }
}
</code>```

This seems to work but from experience gets hard to maintain. If Animals ever change Zoo's you have to unsubscribe events at the old Zoo and resubscribe at the new Zoo. This only gets worse as the composition tree gets deeper.

3) The other option is to move the logic up to the parent.

```<code>public class Zoo
{
    public void AnimalMakesMess(Animal animal)
    {
        ...
    }
}
</code>```

This seems very unnatural and causes duplication of logic. For example, if I had a House object that doesn't share any common inheritance parent with Zoo..

```<code>public class House
{
    // Now I have to duplicate this logic
    public void AnimalMakesMess(Animal animal)
    {
        ...
    }
}
</code>```

I have not yet found a good strategy for dealing with these situations. What else is available? How can this be made simpler?

答:
I've had a fair amount of success with architectures like your option 2 in the past. It's the most general option and will allow the greatest flexibility. But, if you have control over your listeners and aren't managing a lot of subscription types, you can subscribing to events more easily by creating an interface.

```<code>interface MessablePlace
{
  void OnMess(object sender, MessEvent e);
}

class MessEvent
{
  String DetailsOrWhatever;
}
</code>```

The interface option has the advantage of being almost as simple as your option 1, but also allows you to house animals pretty effortlessly in a House or FairlyLand.

ContentLicense: CC BY-SA 3.0

Body:
I've had a fair amount of success with architectures like your option 2 in the past. It's the most general option and will allow the greatest flexibility. But, if you have control over your listeners and aren't managing a lot of subscription types, you can subscribing to events more easily by creating an interface.

interface MessablePlace
{
  void OnMess(object sender, MessEvent e);
}

class MessEvent
{
  String DetailsOrWhatever;
}

The interface option has the advantage of being almost as simple as your option 1, but also allows you to house animals pretty effortlessly in a House or FairlyLand.


问:
Is this a good way to compare two numbers?
If we have double numbers, let's say I want to see if some double parameter is equal to zero that is passed as double:

```<code>public bool AlmostEqual(double x, double y)
{
    double epsilon = Math.Max(Math.Abs(x), Math.Abs(y)) * 1E-15;
    return Math.Abs(x - y) <= epsilon;
}
</code>```

considering double shows 15 accurate digits.
So do you think what I wrote is good? or it has issues?

well then I just wrote a simple method like this:

```<code>public bool ReallyEqual(double x, double y)
{
    return (x == y);
}
</code>```

and then I couldn't find a case that return values of those two methods are different. they were always returning the same result. :(

答:
Understanding the decimal format and working with a properly crafted number, it is not difficult to find two values that have differing values.

```<code>using System;

public class Example
{
   public static void Main()
   {
      double[] values = {
        //12345678901234567
        0.10000000000000001,
        0.10000000000000002
        };
      Console.WriteLine("{0:r} = {1:r}: =:{2} ae:{3} re:{4} hmd1:{5} hmd0:{6}",
                        values[0], values[1],
                        values[0].Equals(values[1]),
                        AlmostEqual(values[0], values[1]),
                        ReallyEqual(values[0], values[1]),
                        HasMinimalDifference(values[0], values[1], 1),
                        HasMinimalDifference(values[0], values[1], 0));
      Console.WriteLine();
   }

   public static bool AlmostEqual(double x, double y) {
      double epsilon = Math.Max(Math.Abs(x), Math.Abs(y)) * 1E-15;
      return Math.Abs(x - y) <= epsilon;
   }

   public static bool ReallyEqual(double x, double y) {
      return (x == y);
   }

   public static bool HasMinimalDifference(double value1, double value2, int units) {
      long lValue1 = BitConverter.DoubleToInt64Bits(value1);
      long lValue2 = BitConverter.DoubleToInt64Bits(value2);

      // If the signs are different, return false except for +0 and -0.
      if ((lValue1 >> 63) != (lValue2 >> 63))
      {
         if (value1 == value2)
            return true;

         return false;
      }

      long diff = Math.Abs(lValue1 - lValue2);
      Console.WriteLine("HMD: {0} {1} {2} {3}",
                        lValue1, lValue2, diff, units);

      if (diff <= (long) units)
         return true;

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

(If you want to play with this code online, it is at https://ideone.com/fwsq5o )

There are three functions here, the Almost Equal, the Really Equal and HasMinimalDifference (from Double.Equals Method (Double) @msdn)

Note that the numbers themselves that are being tested are almost the same, and when looking at the output of the numbers from within HasMinimalDifference they are only different by one bit in the representation.

The output of this program is:

```
HMD: 4591870180066957722 4591870180066957723 1 1
HMD: 4591870180066957722 4591870180066957723 1 0
0.1 = 0.10000000000000002: =:False ae:True re:False hmd1:True hmd0:False
```

You can see the two invocations of HasHminimalDistance with the two units arguments (1 and 0).  Only the last number between the two is different, and if you call HasHminimalDistance with 0 as the third parameter it is equivalent to an expensive .Equals.

With these numbers:

Equals is false

AlmostEquals is true

ReallyEqual is false

HasHminimalDistance allowing for 1 unit of slop is true

HasHminimalDistance allowing for 0 units of slop is false

You can get two floating point numbers that are really similar and its a question of if you want to consider them the same or similar or not.  Some applications two things are the same if they are within some tolerance, other applications need exact values to be the same.  The later set of applications might wish to consider exact math classes such as BigDecimal for situations where you want to to work with exact values that don't accidentally get some floating point inaccuracy rounding it and an incorrect exactly equal value propagate through the system.

One thing to consider here with the question as it is written is for comparisons with zero which deal with a rather special number - zero.

If we change the numbers we look at to:

```<code>  double[] values = {
    //12345678901234567
    0,
    Double.Epsilon
    };
</code>```

We will see:

```
HMD: 0 1 1 1
HMD: 0 1 1 0
0 = 4.94065645841247E-324: =:False ae:False re:False hmd1:True hmd0:False
```

When we look at AlmostEqual(0, Double.Epsilon) we see that epsilon (the local var) has a value of 0 (Double.Epsilon * 1E-15 == 0).  Then Math.abs(x-y) is equal to Double.Epsilon, which is greater than 0.  So for 0, the only way for this type of approach to be true is if the number is identical to 0 - not just really close.

The HasMinimalDifference call, however, is looking at the difference in the bits and can allow 0 and 1 (Double.Epsilon cast to a long) to be close enough.

Body:
Understanding the decimal format and working with a properly crafted number, it is not difficult to find two values that have differing values.

using System;

public class Example
{
   public static void Main()
   {
      double[] values = {
        //12345678901234567
        0.10000000000000001,
        0.10000000000000002
        };
      Console.WriteLine("{0:r} = {1:r}: =:{2} ae:{3} re:{4} hmd1:{5} hmd0:{6}",
                        values[0], values[1],
                        values[0].Equals(values[1]),
                        AlmostEqual(values[0], values[1]),
                        ReallyEqual(values[0], values[1]),
                        HasMinimalDifference(values[0], values[1], 1),
                        HasMinimalDifference(values[0], values[1], 0));
      Console.WriteLine();
   }

   public static bool AlmostEqual(double x, double y) {
      double epsilon = Math.Max(Math.Abs(x), Math.Abs(y)) * 1E-15;
      return Math.Abs(x - y) <= epsilon;
   }

   public static bool ReallyEqual(double x, double y) {
      return (x == y);
   }

   public static bool HasMinimalDifference(double value1, double value2, int units) {
      long lValue1 = BitConverter.DoubleToInt64Bits(value1);
      long lValue2 = BitConverter.DoubleToInt64Bits(value2);

      // If the signs are different, return false except for +0 and -0.
      if ((lValue1 >> 63) != (lValue2 >> 63))
      {
         if (value1 == value2)
            return true;

         return false;
      }

      long diff = Math.Abs(lValue1 - lValue2);
      Console.WriteLine("HMD: {0} {1} {2} {3}",
                        lValue1, lValue2, diff, units);

      if (diff <= (long) units)
         return true;

      return false;
   }
}

(If you want to play with this code online, it is at https://ideone.com/fwsq5o )

There are three functions here, the Almost Equal, the Really Equal and HasMinimalDifference (from Double.Equals Method (Double) @msdn)

Note that the numbers themselves that are being tested are almost the same, and when looking at the output of the numbers from within HasMinimalDifference they are only different by one bit in the representation.

The output of this program is:

HMD: 4591870180066957722 4591870180066957723 1 1
HMD: 4591870180066957722 4591870180066957723 1 0
0.1 = 0.10000000000000002: =:False ae:True re:False hmd1:True hmd0:False

You can see the two invocations of HasHminimalDistance with the two units arguments (1 and 0).  Only the last number between the two is different, and if you call HasHminimalDistance with 0 as the third parameter it is equivalent to an expensive .Equals.

With these numbers:

Equals is false

AlmostEquals is true

ReallyEqual is false

HasHminimalDistance allowing for 1 unit of slop is true

HasHminimalDistance allowing for 0 units of slop is false

You can get two floating point numbers that are really similar and its a question of if you want to consider them the same or similar or not.  Some applications two things are the same if they are within some tolerance, other applications need exact values to be the same.  The later set of applications might wish to consider exact math classes such as BigDecimal for situations where you want to to work with exact values that don't accidentally get some floating point inaccuracy rounding it and an incorrect exactly equal value propagate through the system.

One thing to consider here with the question as it is written is for comparisons with zero which deal with a rather special number - zero.

If we change the numbers we look at to:

  double[] values = {
    //12345678901234567
    0,
    Double.Epsilon
    };

We will see:

HMD: 0 1 1 1
HMD: 0 1 1 0
0 = 4.94065645841247E-324: =:False ae:False re:False hmd1:True hmd0:False

When we look at AlmostEqual(0, Double.Epsilon) we see that epsilon (the local var) has a value of 0 (Double.Epsilon * 1E-15 == 0).  Then Math.abs(x-y) is equal to Double.Epsilon, which is greater than 0.  So for 0, the only way for this type of approach to be true is if the number is identical to 0 - not just really close.

The HasMinimalDifference call, however, is looking at the difference in the bits and can allow 0 and 1 (Double.Epsilon cast to a long) to be close enough.


问:
How do you call one program from another?
What I'm wondering is how running programs communicate with each other, and if someone could post some sample code for how to do this, so I can try it out myself, just for educational purposes.

For example, I've worked with databases before, and in my code I always have to "establish a connection to the database." The database service has to be running before I start my program, or else it will fail. What exactly is going on with that connection and how does it work?

答: Any sort of communication with the outside world is ultimately mediated by the operating system. There's various mechanisms available for Inter-process communication, but pipes and network sockets are probably some of the most common. If you've ever piped the output of one program into another on a command line shell, those processes were communicating with a pipe. The connection to the database you mentioned is using a network socket, perhaps with a custom protocol. For communicating separate machines in a fairly universal way, you'd probably go with a web service, which generally means passing information through HTTP and possibly XML.</p>


答:
This is not such an easy question to be answered because it envolves distinct types of work.

For the case of a database, for example, it's usually a connection to a server through TCP/IP protocol, and the database needs to be running because the server needs to be connected so that it receives the request from your code (think that you can't access an offline website).

However, for the case of other programs, it depends a lot. If it's just a module written in the same language, you could just import. If it's a Unix process, you could call system function passing the command. If you want something to be multi-platform, you could use a Restful or a SOAP web service (that'd require internet connection), and so on.

Title: How do you call one program from another?

Body:
What I'm wondering is how running programs communicate with each other, and if someone could post some sample code for how to do this, so I can try it out myself, just for educational purposes.

For example, I've worked with databases before, and in my code I always have to "establish a connection to the database." The database service has to be running before I start my program, or else it will fail. What exactly is going on with that connection and how does it work?


答:
From Comparing Floating Point Numbers, 2012 Edition

There is no silver bullet. You have to choose wisely.

If you are comparing against zero, then relative epsilons and ULPs based comparisons are usually meaningless. You’ll need to use an absolute epsilon, whose value might be some small multiple of FLT_EPSILON and the inputs to your calculation. Maybe.

If you are comparing against a non-zero number then relative epsilons or ULPs based comparisons are probably what you want. You’ll probably want some small multiple of FLT_EPSILON for your relative epsilon, or some small number of ULPs. An absolute epsilon could be used if you knew exactly what number you were comparing against.

If you are comparing two arbitrary numbers that could be zero or non-zero then you need the kitchen sink. Good luck and God speed.

Working with floats is not trivial, so I urge you to read up more on how they work. What I quoted is part of a long series of articles explaining the intricacies and complexities of working with floats. Here's the first post. I find it more digestible than What Every Computer Scientist Should Know About Floating Point Numbers.

Title: Is this a good way to compare two numbers?

Body:
If we have double numbers, let's say I want to see if some double parameter is equal to zero that is passed as double:

```<code>public bool AlmostEqual(double x, double y)
{
    double epsilon = Math.Max(Math.Abs(x), Math.Abs(y)) * 1E-15;
    return Math.Abs(x - y) <= epsilon;
}
</code>```

considering double shows 15 accurate digits.
So do you think what I wrote is good? or it has issues?

well then I just wrote a simple method like this:

```<code>public bool ReallyEqual(double x, double y)
{
    return (x == y);
}
</code>```

and then I couldn't find a case that return values of those two methods are different. they were always returning the same result. :(


问:
Intel Nehalem/SB/IB/Haswell CPUs, cache vs TLB
On the Nehalem+ architecture Intel CPUs what is the interaction between the L1 cache, L2 cache, L1 DTLB and L2 DTLB? On all the images I have found there isnt a clear explanation whether the CPU looks at the L1 DTLB first, then goes to the L1D cache, or whether it only goes to the L1 DTLB cache if there is a cache miss in the L1D or the L2 cache?</p>

答:
A common method is to access both in parallel. This method is described in the Wikipedia article: http://en.wikipedia.org/wiki/Translation_lookaside_buffer.

The whole point of a lookaside buffer is that the CPU looks there as well as somewhere else, typically using different parts of the same address. Either can miss, and what happens next depends on the architecture.


答:
Quick and easy: AbstractCharacterDelegator does not have abstract functions, but virtual instead. By default, they pass through to the wrapped character and can be overridden. Then you inherit and only override the few you want.

This sort of thing isn't particularly useful unless you do quite a bit of decoration and your common interface is particularly wide. That shouldn't be too common. And this approach might not be by the letter a decorator, but it uses the concept and would be well understood to be a decorator by programmers that know the pattern.

Title: How to use the Decorator pattern to add little functionality to big objects?

Body:
This question regards the usage of the Decorator pattern to add little functionality to objects of large classes.

Following the classic Decorator pattern, please consider the following class structure:

For example, imagine this happens inside a game. Instances of ConcreteCharacterDecorator are meant to add little functionality to the ConcreteCharacter they are 'wrapping'.

For instance, methodA() returns an int value representing the damage the character inflicts on enemies. The ConcreteCharacterDecorator simply adds to this value. Thus, it only needs to add code to methodA(). The functionality of methodB() stays the same.

ConcreteCharacterDecorator will look like this:

```<code>class ConcreteCharacterDecorator extends AbstractCharacterDecorator{

    ConcreteCharacter character;

    public ConcreteCharacterDecorator(ConcreteCharacter character){
        this.character = character;
    }

    public int methodA(){
        return 10 + character.methodA();
    }

    public int methodB(){
        character.methodB(); // simply delegate to the wrapped object.
    }

}
</code>```

This is no problem with small classes containing two methods.

But what if AbstractCharacter defined 15 methods? ConcreteCharacterDecorator would have to implement all of them, even though it's only meant to add little functionality.

I will end up with a class containing one method that adds a little functionality, and another 14 methods that simply delegate to the inner object.

It would look like so:

```<code>class ConcreteCharacterDecorator extends AbstractCharacterDecorator{

    ConcreteCharacter character;

    public ConcreteCharacterDecorator(ConcreteCharacter character){
        this.character = character;
    }

    public int methodA(){
        return 10 + character.methodA();
    }

    public int methodB(){
        character.methodB(); // simply delegate to the wrapped object.
    }
    public int methodC(){
        character.methodC(); // simply delegate to the wrapped object.
    }
    public int methodD(){
        character.methodD(); // simply delegate to the wrapped object.
    }
    public int methodE(){
        character.methodE(); // simply delegate to the wrapped object.
    }
    public int methodF(){
        character.methodF(); // simply delegate to the wrapped object.
    }
    public int methodG(){
        character.methodG(); // simply delegate to the wrapped object.
    }
    public int methodH(){
        character.methodH(); // simply delegate to the wrapped object.
    }
    public int methodI(){
        character.methodI(); // simply delegate to the wrapped object.
    }
    public int methodJ(){
        character.methodJ(); // simply delegate to the wrapped object.
    }
    public int methodK(){
        character.methodK(); // simply delegate to the wrapped object.
    }
    public int methodL(){
        character.methodL(); // simply delegate to the wrapped object.
    }
    public int methodM(){
        character.methodM(); // simply delegate to the wrapped object.
    }
    public int methodN(){
        character.methodN(); // simply delegate to the wrapped object.
    }
    public int methodO(){
        character.methodO(); // simply delegate to the wrapped object.
    }

}
</code>```

Obviously, very ugly.

I'm probably not the first to encounter this problem with the Decorator. How can I avoid this?


问:
Do you experiment with unconventional ways to use design patterns?
We stick to standard usages and best practices because they work and communicate intent well, but without trying new things we can't really grow. Have you ever tried something that seemed absurd but worked out really well? When it works, how do you avoid confusing other developers with non-standard usages? And what do you do when things go horribly wrong - refactor, start over, or just go with it?</p>

答:
All the time.

I avoid confusing other developers by only expierementing on personal projects. Id say some of the best and most of the worst code I have ever written has been for personal projects- when trying out new things.

When things go horribly wrong, since its usually just a small part I throw it away or refactor it until it is useable.

ContentLicense: CC BY-SA 2.5


问:
Isolating unit tests in python
As a 30-year software developer, mostly in OO languages, but a newbie at python, I'm looking to find what is best practise for isolating unit tests in python.

Let's say I have the following, semi-pseudo-code. I know some_database_client isn't a real database client:

```<code>from some_database_client import connection

connection.connect('server_id', 'username', 'password')

def function_under_test():
    return connection.get_value('some_value_reference') + 10
</code>```

If I write a test for function_under_test(), then I'm effectively testing the potentially enormous amount of logic in connecting and retrieving the data from connection.

Instead, I really want to test that function_under_test() adds ten to the value retrieved.

This relates to a practical real-world example where the module-level variable connection (or it's real-world equivalent) is referenced heavily all over the code.

Therefore, it would involve a large and therefore very risky change to pass connection as an argument to all the functions that use it. Without doing this though, I can't easily separate the variable connection when I'm trying to unit-test the functions that use it. connection is instantiated before I even get to run the unit-test.

Is there a recommended way to isolate functions like this for testing? I can certainly think of many, many ways, but I suspect that some have more of the "Zen of Python" about them than others. e.g. Wrapping everything in classes is a possibility, but that is perhaps moving too far away from keeping stuff simple, which is a goal of python.

答:
It intrinsically has to do with a basic yet important OOP concept: Inversion of control.

One of the ways to reach it is Dependency Injection. In a few words, instead of calling a determined function specified in the body of the function, you'll call a function given by the caller.

Introducing it to your problem:

```<code>def function_under_test(connection):
    return connection.get_value('some_value_reference') + 10
</code>```

Now, we need to pass an object that has the method get_value. In production, you'd pass the real connection object. When testing, however, you'd pass a mock (fake version) of it.

An example of how easy testing becomes:

```<code>class FakeConnection():
    def get_value(self, reference):
        return 30

def test_function():
   connection = FakeConnection()
   result = function_under_test(connection)

   assert result == 40
</code>```

Title: Isolating unit tests in python

Body:
It intrinsically has to do with a basic yet important OOP concept: Inversion of control.

One of the ways to reach it is Dependency Injection. In a few words, instead of calling a determined function specified in the body of the function, you'll call a function given by the caller.

Introducing it to your problem:

def function_under_test(connection):
    return connection.get_value('some_value_reference') + 10

Now, we need to pass an object that has the method get_value. In production, you'd pass the real connection object. When testing, however, you'd pass a mock (fake version) of it.

An example of how easy testing becomes:

class FakeConnection():
    def get_value(self, reference):
        return 30

def test_function():
   connection = FakeConnection()
   result = function_under_test(connection)

   assert result == 40


问:
Why did the Sun engineers decided to make Java only call by value?
Is there any specific reason they decided to go with Call by value? Is it for simplicity?</p>

答:
Java has call by value for a small number of predefined value types, and call by reference for object types. [The reference is internally a pointer that is passed by value, but that's not the point.]

In C# (which is kind of Java 3.0) there are out and ref parameters, but Java doesn't have them. As a compiler writer I can tell you that they really complicate things. You have to decide whether to use a pointer mechanism (similar to objects) which leads to boxing; whether to use copy-in-copy-out which leads to aliasing problems; how to track whether variables are initialised or not. I guess the Java designers thought this was all too hard, or just not worth it.

The real decision made by Java was not to treat value types as first class citizens. There are no user-defined value types, no boxing and only pass by value. In C# they were thought worthwhile, but in Java they thought primitive values and user-defined objects were enough. I prefer C#, but I almost never use out or ref parameters.

Edit: In my defence, call by reference has been used to describe a range of strategies since the 1960s, and my usage here is borderline and will offend purists. I use it in the sense that the object is not copied, but any change to the passed in object will affect the original. However, an assignment to the passed in parameter will not affect the original but instead refer to a new object (or null).


答:
Let's walk through what actually happens when an instruction like mov eax,[ds:ebx*2+4] is executed.

First the CPU has to calculate the virtual address. The virtual address would be ebx*2+4.

Next the CPU adds the segment register's base address to the virtual address to get a linear address. The base address for each segment register is stored in the CPU, and for most segment registers (for most OSs) it's zero, so this can happen fast. Note: There's also some protection checks involved here, but ignore that.

Once the CPU has a linear address it needs to be converted into a physical address (e.g. an actual RAM location). To do this everything is broken up into (4 KiB or possibly larger) pages, and there's several layers of paging structures. For example (long mode), CPU would use the PML4 (Page Map Level 4) to find the PDPT (Page Directory Pointer Table), then use a PDPT entry to find the PD (Page Directory), then use a PD entry to find the PT (Page Table). The page table entry contains the physical address of the page. By adding the "offset within page" from the virtual address to the physical address of the page it gets the final physical address. Note: There's also some protection checks involved at each step here, but ignore that.

All these table lookups take time. To speed it up the CPU caches the "virtual address to physical address" translations (including the final/resulting permissions for protection checks) in the TLB (Translation Look-aside Buffer).

Once the CPU knows the physical address, it can read the data from that physical address. This can be slow too, so the CPU uses other caches to cache the actual data.

Now; the problem with caches is that (due to "technical stuff") the larger they are the slower they are. To get the best performance and larger caches, they have multiple levels of caches - e.g. very small very fast L1, larger/slower L2, etc. For the caches close to the CPU, it can also help to have different caches for instructions and data (different working sets, different access patterns, etc). This is why there's L1I and L1D, then a (unified) L2 and maybe a (unified) L3.

Of course the same applies to TLBs - there can be multiple levels of TLBs and different TLBs for instructions and data (plus some more caches specifically for the high level paging structures to reduce TLB miss overhead).

Getting back to those "virtual address to physical address" translations - if the translation is not cached in the TLB, then the CPU needs to fetch (potentially) lots of tables from RAM to do the translation. A TLB miss causes several fetches, and those fetches might (or might not) be satisfied by data still in the L2 or L3 cache.

Title: Intel Nehalem/SB/IB/Haswell CPUs, cache vs TLB

Body: On the Nehalem+ architecture Intel CPUs what is the interaction between the L1 cache, L2 cache, L1 DTLB and L2 DTLB? On all the images I have found there isnt a clear explanation whether the CPU looks at the L1 DTLB first, then goes to the L1D cache, or whether it only goes to the L1 DTLB cache if there is a cache miss in the L1D or the L2 cache?</p>


问:
Server side C# MVC with AngularJS
I like using .NET MVC and have used it quite a bit in the past.  I have also built SPA's using AngularJS with no page loads other than the initial one.  I think I want to use a blend of the two in many cases.  Set up the application initially using .NET MVC and set up routing server side.  Then set up each page as a mini-SPA.  These pages can be quite complex with a lot of client side functionality.

My confusion comes in how to handle the model-view binding using both .NET MVC and the AngularJS scope.  Do I avoid the use of razor Html helpers?  The Html helpers create the markup behind the scene so it could get messy trying to add angularjs tags using the helpers.  So how to add ng-model for example to @Html.TextBoxFor(x => x.Name).  Also ng-repeat wouldn't work because I'm not loading my model into the scope, right?  I'd still want to use a c# foreach loop?

Where do I draw the lines of separation?  Has anyone gotten .NET MVC and AngularJS to play nicely together and what are your architectural suggestions to do so?

答:
I am building an app that is a combination of MVC on the server and AngularJS on the client.

On the server:

I found the easiest thing to do was to build a bunch of RESTful web api's to provide data services to the client. I also perform validation on the server to make sure that no one cheats (sending data using a client other than the web page). I also assemble the web page (though a controller and minimal view) to load all of the libraries it needs. Since I am building the web page with almost no changes from the view to the final HTML, I should be able to replace AngularJS with something else.

On the client:

On the client, I used AngularJS to handle everything from calling the web api's to local validation. It gives the user the "immediate" response that is being pushed by the latest push on the web. You can make your page dynamic or relatively static. By using an architecture that is using a separation of concerns, I can replace the back end with anything that supports a RESTful api.

OwnerDisplayName: Ryan Langton

Title: Server side C# MVC with AngularJS


问:
Is better Show() + Hide() or SetVisible(bool visible)?
What is better and why? (From interface-design point of view) :

a) To have two Show() and Hide() functions

b) To have one SetVisible(bool visible) function

EDIT: For example some object have visibility state and this functions is used to change it.

c) To have all three Show(), Hide(), SetVisible(bool visible) functions

答:
I agree with Darien's answer, but wanted to add a point of view from a C# programmers perspective.

When I see code which says 'setXXX' I read that to say that it's setting a value on a thing, I don't expect this to have side effects in that thing other than setting that value, and I do expect this to be idempotent (ie I can keep setting it with the same value and it's okay). It's rather like accessing a field. Generally I'd also expect to see a 'getXXX' method along with a 'setXXX'.

I don't know if this is what you expect in Java and C++, but that's what I'd expect in C#, albeit in C# there's a short hand for this called Properties. And here's some nice guidance on how to use Properties (http://msdn.microsoft.com/en-us/library/ms182181.aspx).

Given this view, then the interface I'd choose depends purely on if there are any side effects (other than changing that field value):

If performing the action has side effects, for example it's showing a dialog box then I'd go with "Show()", and "Hide()".

If it doesn't have side effects, say I'm setting the visibility of a "widget" and something else renders that widget depending on it's state then I'd use setVisibility or setIsVisible. (I wouldn't call it SetVisible).

In C# (not sure about Java) it's pretty common to adopt an observer pattern, where a UI framework will listen for changes to objects and will automatically re-render the UI when a property such as Visibility changes. That means that setting the value by calling setIsVisible appears as if it has side effects, but in my definition it doesn't. The widget's contract is fulfilled by setting it's field value representing "IsVisible".

Put another way, it's okay for me to toggle the visibility of a label on a form before the form is shown. Ie label.getIsVisible == true, but the form isn't shown.

It's not okay for me to call Hide() when the form isn't being shown.


问:
Is storing software in the cloud with reputable vendors secure?
I have a team member who refuses to use any form of private source code repository on Github or Bitbucket due to "security concerns".  As a result, we have a hard time sharing code with him.  He appears to be concerned about source code theft by some party.  To me, using cloud based source code repos is fairly standard industry practice.  But does this individual have a point?  Vendors do steal from customers in other industries.  Should a multimillion dollar idea not be stored on a third party cloud service like AWS, Github, Bitbucket, App Engine, etc?</p>

答:
First, you seem to have a management problem. One team member should not make such a decision and dictate terms that impose that decision on others.

Second, you seem to misunderstand the nature of cloud-based services. Most such services provide a high degree of isolation between users and against external agents (other than the NSA), but no protection from employees of your providers. Since you upload unencrypted text, any person with access to any part of the route from you to the provider, or with access to the internals of the provider, has access to your source code.

You can address this 3 ways.

Legal/trust. You either trust all those providers implicitly, or you obtain legal documents which bind them to certain standards of behaviour, on penalty of getting sued.

Local encryption. You employ a mechanism to transmit and store your source code in an encrypted form, for which only you have the keys. The technical details are complex, but achievable. Bear in mind you still need to exchange keys with your co-workers.

Own server. You run your own source code repository, and you use something like https with your own self-signed certificate for secure transmission, or a client that does it for you. You still have the problem of key exchange.

Doubtless there are strategies and variants I haven't thought of, but these are the main ones. Most people tend to pretend there isn't a problem and for most people there isn't. If your code is valuable enough (say you're developing high-profile financial systems or gambling systems or security systems) then I wouldn't be the one to make that call.


问:
How can I monitor the JVM memory in a proper way?
I'm thinking of how we do JVM memory monitor in a low overhead way in production environment even under busy hour.

Suppose I have two tomcat app server in production, load balance set up behind them. If I can see the jvm memory statistics I can tell load balance to stop sending the request to the server which will encounter OOM issue.  Do this make sense? Jconsole or VisualVM eats more performance resourse is not my choice.

答:
Others have provided suggestions on how to monitor memory usage ...

Suppose I have two tomcat app server in production, load balance set up behind them. If I can see the jvm memory statistics I can tell load balance to stop sending the request to the server which will encounter OOM issue. Do this make sense?

Sort of.  But it isn't necessarily the best way to solve your problem.

Lets backtrack to the root of the problem ... the OOMEs.  In the context of Tomcat, OOMEs are likely to be caused by one of the following:

memory leaks in your application, (or possibly Tomcat itself),

attempting to process too many requests in parallel on each Tomcat, or

individual requests that need too much memory during processing.

To solve your problem, you first need to find out which of these is happening ... because the solution is different for each of them.

1) To see if this is a memory leak, you need to use a memory analysis tool to examine the long-term memory usage patterns.  This will probably show a sawtooth pattern ... which is normal.  What you need to look for is the the level of the bottoms of the "teeth" trending upwards over time.  That indicates that something is creating garbage that cannot be collected; i.e. a memory leak.

If you have a memory leak, then the best solution is to figure out what part of your code is responsible, and fix it.  Anything else ... including load balancing ... is a bandaid solution and could lead to worse problems down the track.

2) Having eliminated memory leaks, you need to figure out if the problem is that you are processing too many requests at once.  I'm not sure of the best way to do that, but if this is the problem (or you suspect it is) then there are a few possible solutions:

Adjust the Tomcat server configuration to reduce the number of worker threads.

If your requests are I/O bound, then another possibility would be to look at the asynchronous request handling support available in recent versions of the Servlet spec - see http://docs.oracle.com/javaee/7/tutorial/doc/servlets012.htm.  But that will be more work.

3) If the problem turns out to be that certain requests are using too much memory, then you need to figure out how to detect those requests before hand and "deal with them".  Both detecting and dealing with these requests could be difficult ... and it is hard to advise without details of your application.  But a couple of pragmatic solutions are:

Forward the anomalous requests to another server with a big heap ... where the OOMEs won't interfere with "normal" requests.

Increase the heap size.  If you have enough physical memory, running with a larger heap could actually make your Tomcat servers more efficient ... as well as avoiding OOMEs.

In summary, rather trying to load balance to avoid OOMEs, I suggest you figure out why you are getting OOMEs ... and try to deal with the cause of the OOMEs directly.


问:
What is the idiomatic way to persist the data in this simple data-based application?
I'm looking at developing a simple application in Java for a game which allows a user to keep track of which items they own and how much experience they have obtained while using the item. All of this data is input by the user.

What is the idiomatic/standard way to persist the data that is being manipulated (the model)? The immediate possibilities seem to be saving it to a file, serialization, databases, etc, but many of these seem to be overkill for simple text fields that don't seem to necessitate objects. What is the idiomatic/traditional way to handle something like this?

答:
SQLite is a nice, lightweight database application. Some of the NoSql databases are easy to download and get running quickly, with low learning curve. I've heard Redis is pretty easy for saving simple data. MongoDB is very accessible as well, if you just use the basic features and don't worry about the complicated bits.

Managing everything in flat files on disk would work, too, but my guess is that the time it would take to define file formats, serialization, random access, and all the tricky parts -- with all the unit tests because you don't want a bug to corrupt your data -- then it would take more time and effort than just launching and learning something easy like SQLite or Redis.


问:
To make a class function or not?
I'm wondering about functions used like this:

```<code>object1->objectMethod1(arg1, arg2);
</code>```

if objectMethod1:

- does not change the object state

- does not use the object's state at all

- is used by the class extensively

- logically fits as being used by the class

should it be made into a member function?

example:

```<code>class CSVFile {
private:
  filestream stream
  string header
  int num_columns
public:
  CSVFile(string filename)
  CSVFile() throws DefaultConstructorException()
...
CSVFile::initHeader() {
  header = stream.getLine()
  assert(isInCSVFormat(header)) <-- that
</code>```

should isInCSVFormat(string) be a member function or not?

答:
I would answer this by considering dependencies. I assume your class depends on this function, so what else does?

If no other class does, then yes, it should be packaged with the class. You might even make it private. Whether it is a static method, or in a static class or in a namespace depends on the implementation language and local coding conventions.

If other classes depend on it but only when using your class, then it should probably still be packaged with the class.

If other classes depend on it for uses other than related to using your class, then it should packaged separately.

You should also consider whether this function brings in its own dependencies. If the function brings in a whole additional library with its own dependencies then it might better to keep it separate, regardless of the above.

Title: To make a class function or not?


答:
To ensure that the database service is running , You can either check whether the service is running, and start or stop it accordingly.

for Windows you should use Windows API to do that accordingly.

here is the example code

http://msdn.microsoft.com/en-us/library/windows/desktop/ms686315(v=vs.85).aspx

and also a different approach here

http://code.msdn.microsoft.com/windowsdesktop/CppWindowsService-cacf4948


答:
I would go with 1, but I would make the parent-child relationship along with notification logic into separate wrapper. This removes the dependency of Animal on Zoo and allows automatic management of parent-child relationships. But this requires you to remake the objects in the hierarchy into interfaces/abstract classes first and write a specific wrapper for each interface. But that could be removed using code generation.

Something like :

```<code>public interface IAnimal
{
    string Name { get; set; }
    int Age { get; set; }

    void MakeMess();
}

public class Animal : IAnimal
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void MakeMess()
    {
        // makes mess
    }
}

public class ZooAnimals
{
    class AnimalInZoo : IAnimal
    {
        public IAnimal _animal;
        public ZooAnimals _zoo;

        public AnimalInZoo(IAnimal animal, ZooAnimals zoo)
        {
            _animal = animal;
            _zoo = zoo;
        }

        public string Name { get { return _animal.Name; } set { _animal.Name = value; } }
        public int Age { get { return _animal.Age; } set { _animal.Age = value; } }

        public void MakeMess()
        {
            _animal.MakeMess();
            _zoo.IsDirty = true;
        }
    }

    private Collection<AnimalInZoo> animals = new Collection<AnimalInZoo>();

    public IAnimal Add(IAnimal animal)
    {
        if (animal is AnimalInZoo)
        {
            var inZoo = (AnimalInZoo)animal;
            if (inZoo._zoo != this)
            {
                // animal is in a different zoo, what to do ?
                // either move animal to this zoo
                // or throw an exception so caller is forced to remove the animal from previous zoo first
            }
        }

        var anim = new AnimalInZoo(animal, this);
        animals.Add(anim);
        return anim;
    }

    public IAnimal Remove(IAnimal animal)
    {
        if (!(animal is AnimalInZoo))
        {
            // animal is not in zoo, throw an exception?
        }
        var inZoo = (AnimalInZoo)animal;
        if (inZoo._zoo != this)
        {
            // animal is in a different zoo, throw an exception?
        }

        animals.Remove(inZoo);
        return inZoo._animal;
    }

    public bool IsDirty { get; set; }
}
</code>```

This is actually how some ORMs do their change tracking on entities. They create wrappers around the entities and make you work with those. Those wrappers are usually made using reflection and dynamic code generation.

Title: Patterns for propagating changes up an object model..?

Body:
Here's a common scenario that's always frustrating for me to deal with.

I have an object model with a parent object. The parent contains some child objects. Something like this.

```<code>public class Zoo
{
    public List<Animal> Animals { get; set; }
    public bool IsDirty { get; set; }
}
</code>```

Each child object has various data and methods

```<code>public class Animal
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void MakeMess()
    {
        ...
    }
}
</code>```

When the child changes, in this case when the MakeMess method is called, some value in the parent needs to be updated. Let's say when a certain threshold of Animal's have made a mess, then the Zoo's IsDirty flag needs to be set.

There are a few ways to handle this scenario (that I know of).

1) Each Animal can have a parent Zoo reference in order to communicate changes.

```<code>public class Animal
{
    public Zoo Parent { get; set; }
    ...

    public void MakeMess()
    {
        Parent.OnAnimalMadeMess();
    }
}
</code>```

This feels like the worst option since it couples Animal to its parent object. What if I want an animal who lives in a house?

2) Another option, if you're using a language that supports events (like C#) is to have the parent subscribe to change events.

```<code>public class Animal
{
    public event OnMakeMessDelegate OnMakeMess;

    public void MakeMess()
    {
        OnMakeMess();
    }
}

public class Zoo
{
    ...

    public void SubscribeToChanges()
    {
        foreach (var animal in Animals)
        {
            animal.OnMakeMess += new OnMakeMessDelegate(OnMakeMessHandler);
        }
    }

    public void OnMakeMessHandler(object sender, EventArgs e)
    {
        ...
    }
}
</code>```

This seems to work but from experience gets hard to maintain. If Animals ever change Zoo's you have to unsubscribe events at the old Zoo and resubscribe at the new Zoo. This only gets worse as the composition tree gets deeper.

3) The other option is to move the logic up to the parent.

```<code>public class Zoo
{
    public void AnimalMakesMess(Animal animal)
    {
        ...
    }
}
</code>```

This seems very unnatural and causes duplication of logic. For example, if I had a House object that doesn't share any common inheritance parent with Zoo..

```<code>public class House
{
    // Now I have to duplicate this logic
    public void AnimalMakesMess(Animal animal)
    {
        ...
    }
}
</code>```

I have not yet found a good strategy for dealing with these situations. What else is available? How can this be made simpler?

Body:
I would go with 1, but I would make the parent-child relationship along with notification logic into separate wrapper. This removes the dependency of Animal on Zoo and allows automatic management of parent-child relationships. But this requires you to remake the objects in the hierarchy into interfaces/abstract classes first and write a specific wrapper for each interface. But that could be removed using code generation.

Something like :

public interface IAnimal
{
    string Name { get; set; }
    int Age { get; set; }

    void MakeMess();
}

public class Animal : IAnimal
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void MakeMess()
    {
        // makes mess
    }
}

public class ZooAnimals
{
    class AnimalInZoo : IAnimal
    {
        public IAnimal _animal;
        public ZooAnimals _zoo;

        public AnimalInZoo(IAnimal animal, ZooAnimals zoo)
        {
            _animal = animal;
            _zoo = zoo;
        }

        public string Name { get { return _animal.Name; } set { _animal.Name = value; } }
        public int Age { get { return _animal.Age; } set { _animal.Age = value; } }

        public void MakeMess()
        {
            _animal.MakeMess();
            _zoo.IsDirty = true;
        }
    }

    private Collection<AnimalInZoo> animals = new Collection<AnimalInZoo>();

    public IAnimal Add(IAnimal animal)
    {
        if (animal is AnimalInZoo)
        {
            var inZoo = (AnimalInZoo)animal;
            if (inZoo._zoo != this)
            {
                // animal is in a different zoo, what to do ?
                // either move animal to this zoo
                // or throw an exception so caller is forced to remove the animal from previous zoo first
            }
        }

        var anim = new AnimalInZoo(animal, this);
        animals.Add(anim);
        return anim;
    }

    public IAnimal Remove(IAnimal animal)
    {
        if (!(animal is AnimalInZoo))
        {
            // animal is not in zoo, throw an exception?
        }
        var inZoo = (AnimalInZoo)animal;
        if (inZoo._zoo != this)
        {
            // animal is in a different zoo, throw an exception?
        }

        animals.Remove(inZoo);
        return inZoo._animal;
    }

    public bool IsDirty { get; set; }
}

This is actually how some ORMs do their change tracking on entities. They create wrappers around the entities and make you work with those. Those wrappers are usually made using reflection and dynamic code generation.


问:
Programmers forgetting syntax
Do good programmers need to have syntax at the tip of their tongue when writing code? What do you make of them if they google for simple stuff online?  Are they good or bad(maybe they know where to look for)? Should programmers have a good memory? Is this a trait for a good programmer?</p>

答: If you're in a position where you're changing languages regularly or working in 3 or 4 languages at the same time there's not a lot you can do about it. For a while I ended up working on projects that required constant switching and began to refer to myself as a "reference programmer," having to look stuff up much more than I would have preferred.</p>

Title: Programmers forgetting syntax


问:
OOP what is meant by object-to-object communication
I've been reading in basic concepts of OOP,as i'm trying to make this shift from transactional scripts to more oop manner in php, and i often come across this definition :

An object stores its state in fields (variables) and exposes its
  behavior through methods (functions). Methods operate on an object's
  internal state and serve as the primary mechanism for object-to-object
  communication

and a simple example like :

Objects like real life objects have state and behavior. Dogs have
  state (name, color, breed, hungry) and behavior (barking, fetching,
  wagging tail).

from definition i see that methods should be either manipulating internal state (setters) or communicating with other objects;

but when i try to apply this to a Blog example. composed of mainly 2 domains User and posts.

what could be the User object Behavior ?

I cannt find any !

login, its an auth lib. thing so i should not include it in user.

posting articles is a Post object thing; again user conduct it; but its more of a post object concern to create a post right ?

User may be the main Aggregate object in a blog; yet the user is more like the Creator of Other Objects but he does not have a Behavior i can think of; he is being used -and his state- by other objects in most cases that all !

in a nutshell : what are allowed type of methods inside an object ?

答:
There is no hard and fast rule which methods an object must have.

Something is an object if you can talk about it as an entity with a name that is familiar to domain experts in either your problem domain or the solution domain.
In essence, if you have a related set of properties and behaviors that you can refer to by a single name, then that set of properties and behaviors is an object.

The behaviors that I refer to fall into two broad categories:

Requests to take an action. The classic example of Dog::bark() falls in this category.

Requests for information. Most getter functions fall in this category.

There is nothing wrong with an object that has mostly (or only) getters. Some objects in some domains are just model an entity that must exist but that does not have any active behavior. Your User class might be one of those.

A class X with mostly getters becomes a code smell when

each getter also has a setter to change the property, and

either class X has invariants (invalid combinations of property values) that can be broken if you use the setters 'wrongly', or

class Y is performing operations on the properties of X that would logically fall within the responsibility of X.

An example of the first class with a code smell would be a class like this:

```<code>class Square {
    int x1, x2, y1, y2;
public:
    void SetTopLeft(int x, int y);
    void SetBottomRight(int x, int y);
};
</code>```

Allowing to change the top-left and bottom-right coordinates independently makes it very easy to break the invariant that all sides of a square must have the same length and all corners are square.

An example of the second form of the code smell is a Dog class where the client moves a Tail object to make the dog wag its tail.

Body:
There is no hard and fast rule which methods an object must have.

Something is an object if you can talk about it as an entity with a name that is familiar to domain experts in either your problem domain or the solution domain.
In essence, if you have a related set of properties and behaviors that you can refer to by a single name, then that set of properties and behaviors is an object.

The behaviors that I refer to fall into two broad categories:

Requests to take an action. The classic example of Dog::bark() falls in this category.

Requests for information. Most getter functions fall in this category.

There is nothing wrong with an object that has mostly (or only) getters. Some objects in some domains are just model an entity that must exist but that does not have any active behavior. Your User class might be one of those.

A class X with mostly getters becomes a code smell when

each getter also has a setter to change the property, and

either class X has invariants (invalid combinations of property values) that can be broken if you use the setters 'wrongly', or

class Y is performing operations on the properties of X that would logically fall within the responsibility of X.

An example of the first class with a code smell would be a class like this:

class Square {
    int x1, x2, y1, y2;
public:
    void SetTopLeft(int x, int y);
    void SetBottomRight(int x, int y);
};

Allowing to change the top-left and bottom-right coordinates independently makes it very easy to break the invariant that all sides of a square must have the same length and all corners are square.

An example of the second form of the code smell is a Dog class where the client moves a Tail object to make the dog wag its tail.


答:
There high-level communication possibilities:

Remote Procedure Calls (Web Services, CORBA etc. included)

File Transfer

Shared Database

Messaging (AMQP, ZeroMQ etc.)

There are also low-level communication possibilities:

Sockets

Pipes

Shared-memory

Signal


问:
Mapping between 4+1 architectural view model & UML
I'm a bit confused about how the 4+1 architectural view model maps to UML.

Wikipedia gives the following mapping:

Logical view: Class diagram, Communication diagram, Sequence diagram.

Development view: Component diagram, Package diagram

Process view: Activity diagram

Physical view: Deployment diagram

Scenarios: Use-case diagram

The paper Role of UML Sequence Diagram Constructs in Object Lifecycle Concept gives the following mapping:

Logical view (class diagram (CD), object diagram (OD), sequence diagram (SD), collaboration diagram (COD), state chart diagram (SCD), activity diagram (AD))

Development view (package diagram, component diagram),

Process view (use case diagram, CD, OD, SD, COD, SCD, AD),

Physical view (deployment diagram), and

Use case view (use case diagram, OD, SD, COD, SCD, AD) which combines the four mentioned above.

The web page UML 4+1 View Materials presents the following mapping:

Finally, the white paper Applying 4+1 View Architecture with UML 2 gives yet another mapping:

Logical view class diagrams, object diagrams, state charts, and composite structures

Process view sequence diagrams, communication diagrams, activity diagrams, timing diagrams, interaction overview diagrams

Development view component diagrams

Physical view deployment diagram

Use case view use case diagram, activity diagrams

I'm sure further search will reveal other mappings as well.

While various people usually have different perspectives, I don't see why this is the case here. Specially, each UML diagram describes the system from a particular aspect. So, for instance, why the "sequence diagram" is considered as describing the "logical view" of the system by one author, while another author considers it as describing the "process view"?

Could you please help me clarify the confusion?

答:
The reason that you can't find a one-to-one mapping between the views of the 4+1 Architectural Model and the various UML diagrams is because such a mapping doesn't exist.

What all those authors are trying to tell with their 'mappings' is that for each view, there is a different set of UML diagrams that can be useful to convey the information that you want to tell in that view.

Additionally, some UML diagrams can be used in different ways, by emphasizing different elements in the diagram, which makes them useful for multiple views. But even if one UML diagram type can be used in multiple views, you would draw a different diagram (or set of diagrams) for each view.


答:
Well, do you think when Dropbox employees are board they dive into our photos? or Gmail staff read our emails when there is nothing else to do?

I'm pretty sure in smaller companies like local telecom companies you might have issues with them as some individuals has quite a dangerous amount of power in their hand and usually that's not illegal, but the bigger companies are more of an Organization that has the power. For example X amount of shares belongs to an investment company, not an individual, so it is less likely that somebody can do whatever s/he wants within the company and no one notice or argue with them -- because they might risk the whole reputation of such a big company or drive it to a total disaster.

Also for a mature company which is big enough to make a big business like that, stealing from their customers is more like a suicide plan instead of a smart idea to make some dollars. I still see many people that they are afraid to go and search a domain name online in the registrar's website because they believe if the domain is really good, then the registrar company will register it before them and will ask them to pay thousands of bucks if they want that domain. If that's a small company then that might be true, but that's not the way Godady or Name.com work for example, but some people are still paranoid about that.

The other thing is that how someone can find your assets there? If you are a famous person or if you do work on a well-known company, then it might be possible, but I'm still pretty sure that those companies do a lot to hire the right people, so nobody on Github will go and take a look at the Jon Skeet's repositories, otherwise no one would trust Github anymore. However if you're someone who's not famous and/or your company is not in the news, then it's very unlikely that someone by accident finds your assets and realizes that they are valuable and worth stealing and risking the rest of their life.

Imagine if somehow it leaks out that someone in Dropbox were blackmailing his ex-girlfriend because he had access to her account in the company. That's a serious thing and the consequences are extremely disastrous. So I assume there are lot's of things inside a company like Dropbox to make sure such a thing will never happen -- from hiring process to monitoring what they do. Same goes for other companies like Github, Amazon, PayPal, Google, Yahoo, etc.

Title: Is storing software in the cloud with reputable vendors secure?

Body: I have a team member who refuses to use any form of private source code repository on Github or Bitbucket due to "security concerns".  As a result, we have a hard time sharing code with him.  He appears to be concerned about source code theft by some party.  To me, using cloud based source code repos is fairly standard industry practice.  But does this individual have a point?  Vendors do steal from customers in other industries.  Should a multimillion dollar idea not be stored on a third party cloud service like AWS, Github, Bitbucket, App Engine, etc?</p>


答:
Although I generally agree with Bart van Ingen Schenau's answer, I think a few points need additional elaboration.

Th advantage of the 4+1 View Model is that it maps stakeholders to the type of information that they need, without requiring specific modeling notations to be used. The emphasis is on ensuring that all groups have the information to understand the system and continue to do their job.

The 4+1 View Model of Software Architecture was described in Philippe Kruchten's paper Architectural Blueprints - The "4+1" View Model of Software Architeture that was originally published in IEEE Software (November 1995). This publication doesn't make specific references to UML. In fact, the paper uses the Booch notation for the logical view, extensions to the Booch notation for process view and development view, calls out the use of "several forms" of developing a physical view, and a new notation for scenarios.

Instead of trying to map each of the views to particular types of diagrams, consider who the target audience of each view is and what information they need. Knowing that, look at various types of models and which one(s) provide the required information.

The logical view is designed to address the end user's concerns about ensuring that all of their desired functionality is captured by the system. In an object-oriented system, this is often at the class level. In complex systems, you may need a package view and decompose the packages into multiple class diagrams. In other paradigms, you may be interested in representing modules and the functions they provide. The end result should be a mapping of the required functionality to components that provide that functionality.

The process view is designed for people designing the whole system and then integrating the subsystems or the system into a system of systems. This view shows tasks and processes that the system has, interfaces to the outside world and/or between components within the system, the messages sent and received, and how performance, availability, fault-tolerance, and integrity are being addressed.

The development view is primarily for developers who will be building the modules and the subsystems. It should show dependencies and relationships between modules, how modules are organized, reuse, and portability.

The physical view is primarily for system designers and administrators who need to understand the physical locations of the software, physical connections between nodes, deployment and installation, and scalability.

Finally, the scenarios help to capture the requirements so that all the stakeholders understand how the system is intended to be used.

Once you understand what each view is supposed to provide, you can choose what modeling notations to use and at what level of detail is required. Bart's last paragraph is especially true - you can show various levels of details in your UML models by focusing on particular design elements or combining various types of diagrams into a set. In addition, you may want to consider going beyond UML to other modeling notations to better describe your system architecture - SysML, Entity-Relation modeling, or IDEF.

Title: Mapping between 4+1 architectural view model & UML

Body:
I'm a bit confused about how the 4+1 architectural view model maps to UML.

Wikipedia gives the following mapping:

Logical view: Class diagram, Communication diagram, Sequence diagram.

Development view: Component diagram, Package diagram

Process view: Activity diagram

Physical view: Deployment diagram

Scenarios: Use-case diagram

The paper Role of UML Sequence Diagram Constructs in Object Lifecycle Concept gives the following mapping:

Logical view (class diagram (CD), object diagram (OD), sequence diagram (SD), collaboration diagram (COD), state chart diagram (SCD), activity diagram (AD))

Development view (package diagram, component diagram),

Process view (use case diagram, CD, OD, SD, COD, SCD, AD),

Physical view (deployment diagram), and

Use case view (use case diagram, OD, SD, COD, SCD, AD) which combines the four mentioned above.

The web page UML 4+1 View Materials presents the following mapping:

Finally, the white paper Applying 4+1 View Architecture with UML 2 gives yet another mapping:

Logical view class diagrams, object diagrams, state charts, and composite structures

Process view sequence diagrams, communication diagrams, activity diagrams, timing diagrams, interaction overview diagrams

Development view component diagrams

Physical view deployment diagram

Use case view use case diagram, activity diagrams

I'm sure further search will reveal other mappings as well.

While various people usually have different perspectives, I don't see why this is the case here. Specially, each UML diagram describes the system from a particular aspect. So, for instance, why the "sequence diagram" is considered as describing the "logical view" of the system by one author, while another author considers it as describing the "process view"?

Could you please help me clarify the confusion?


答:
I've made a simple class diagram that describes your domain:

Each Animal has a Habitat it messes up.

The Habitat does not care what or how many animals it has (unless it is fundamentally part of your design which in this case you described it is not).

But the Animal does care, because it will behave differently in every Habitat.

This diagram is similar to the UML Diagram of the strategy design pattern, but we will use it differently.

Here are some code examples in Java
(I don't want to make any C# specific mistakes).

Of course you can make your own tweak to this design, language and requirements.

This is the Strategy interface:

```<code>public interface Habitat {
    public void messUp(float magnitude);

    public float getCleanliness();
}
</code>```

An example of a concrete Habitat.
of course each Habitat subclass can implement these methods differently.

```<code>public class Zoo implements Habitat {
    public float cleanliness = 1;

    public float getCleanliness() {
        return cleanliness;
    }

    public void messUp(float magnitude) {
        cleanliness -= magnitude;
    }
}
</code>```

Of course you can have multiple animal subclasses, where each one messes it up differently:

```<code>public class Animel {
    private Habitat habitat;

    public void makeMess() {
        habitat.messUp(.05f);
    }

    public Animel addTo(Habitat habitat) {
        this.habitat = habitat;
        return this;
    }
}
</code>```

This is the client class, this basically explains how you can use this design.

```<code>public class ZooKeeper {
    public Habitat zoo = new Zoo();

    public ZooKeeper() {
        new Animal()
            .addTo( zoo )
            .makeMess();

        if (zoo.getCleanliness() < 0.5f) {
            System.out.println("The zoo is really messy");
        } else {
            System.out.println("The zoo looks clean");
        }
    }
}
</code>```

Of course in your real application you can let the Habitat know and manage the Animal if you need.

Body:
I've made a simple class diagram that describes your domain:

Each Animal has a Habitat it messes up.

The Habitat does not care what or how many animals it has (unless it is fundamentally part of your design which in this case you described it is not).

But the Animal does care, because it will behave differently in every Habitat.

This diagram is similar to the UML Diagram of the strategy design pattern, but we will use it differently.

Here are some code examples in Java
(I don't want to make any C# specific mistakes).

Of course you can make your own tweak to this design, language and requirements.

This is the Strategy interface:

public interface Habitat {
    public void messUp(float magnitude);

    public float getCleanliness();
}

An example of a concrete Habitat.
of course each Habitat subclass can implement these methods differently.

public class Zoo implements Habitat {
    public float cleanliness = 1;

    public float getCleanliness() {
        return cleanliness;
    }

    public void messUp(float magnitude) {
        cleanliness -= magnitude;
    }
}

Of course you can have multiple animal subclasses, where each one messes it up differently:

public class Animel {
    private Habitat habitat;

    public void makeMess() {
        habitat.messUp(.05f);
    }

    public Animel addTo(Habitat habitat) {
        this.habitat = habitat;
        return this;
    }
}

This is the client class, this basically explains how you can use this design.

public class ZooKeeper {
    public Habitat zoo = new Zoo();

    public ZooKeeper() {
        new Animal()
            .addTo( zoo )
            .makeMess();

        if (zoo.getCleanliness() < 0.5f) {
            System.out.println("The zoo is really messy");
        } else {
            System.out.println("The zoo looks clean");
        }
    }
}

Of course in your real application you can let the Habitat know and manage the Animal if you need.


答:
I agree with @david.pfx that a team member has no business in unilaterally deciding for or against a company's business decision, especially as the code is not his... He might raise his concerns, present his case, and let the decision makers (source control may be a decision taken as high as VP or as low as team leader, depending on company policy) accept or reject it. After which - he should accept the verdict.

When companies add private repositories on GitHub, they subscribe to GitHub under its privacy policy, which is legally binding to GitHub.

As for security, you could point him to GitHub's article on the subject:

We know your code is extremely important to you and your business, and
  we're very protective of it. After all, GitHub's code is hosted on
  GitHub, too!

They go on, and detail the security measures they take physically, operationally, etc. and also address employee access.

At the end of the day, you must trust someone... servers may be compromised, third party libraries may contain malicious code, and employees may leak information or sabotage the product - but without trusting (vetted) servers, libraries or employees - you would achieve nothing...


问:
Representing a deck of cards in C (not C++)
So far my best ideas have been as fallows

A) Represent a "card" in one structure and have a "deck" in another
a deck being an array of 52 cards and a card being 2 chars one for and rank one for suit.

B) The second seems like it might be easier to manage but less obvious in code. Creating an array of ints each with a different value ranging from 1-52. Then crating a conversion function that would translate the value to a card structure that would have a string for the suit and a string for the rank. The value of zero could indicate a card that has not been "dealt".

Just trying to find a better way of doing this.

答:
It depends on the cards (joker included or not), but I'm using situation B mostly. However I use the first two bits of the integer value to define the color and the rest to define the card value making them together the card. Then I can get the color or value from the card much quicker with bitwise (or mod, divide and multiplication) operations. We simply store two integer values into one integer. The card value we store starting from the third bit, so we can simply multiply that value by four or use a bitshift of 2. Then we add the card color (0, 1, 2 and 3) which is never more than 2 bits in the first 2 bits of the card.

Assuming that the second card is a two and the second color is clubs. So a 2 of clubs will be stored as (binary) 100 + 1 = 101 which is 5 in decimals. If we have card 5 we can use mod and divide because card / 4 will tell us the card value and card % 4 will tell us the card color.


问:
Why is Global State so Evil?
Before we start this, let me say I'm well aware of the concepts of Abstraction and Dependency Injection. I don't need my eyes opened here.

Well, most of us say, (too) many times without really understanding, "Don't use global variables", or "Singletons are evil because they are global". But what really is so bad about the ominous global state?

Let's say I need a global configuration for my application, for instance system folder paths, or application-wide database credentials.

In that case, I don't see any good solution other than providing these settings in some sort of global space, which will be commonly available to the entire application.

I know it's bad to abuse it, but is the global space really THAT evil? And if it is, what good alternatives are there?

答:
I'm not gonna tell if global variables are either good or bad, but what I'm going to add to the discussion is to tell the fact that if you are not using global state, then you are probably wasting a lot of memory, especially when you use classess to store their dependencies in fields.

For global state, there is no such issue, everything is global.

For example: imagine a following scenario: You have a 10x10 grid which is made of classess "Board" and "Tile".

If you want to do it the OOP way you will probably pass the "Board" object to each "Tile".
Let's say now that "Tile" has 2 "byte" type fields storing it's coordinate. The total memory it would take on 32bit machine for one tile would be (1 + 1 + 4 = 6)bytes: 1 for x coord, 1 for y coord and 4 for a pointer to the board. This gives a total of 600 bytes for 10x10 tiles setup

Now for the case where the Board is in global scope, a single object  accessible from each tile you only would have to get 2 bytes of memory per each tile, that's the x and y coordinate bytes. This would give only 200 bytes.

So in this case you get 1/3 of the memory usage if you only use global state.

This ,besides other things , I guess is a reason why the global scope still remains in (relatively)low level languages like C++

Title: Why is Global State so Evil?


问:
Is there a name for the number of values a variable can take?
For example, a bit or a boolean can be either 0 or 1 so the number 2 is associated with it. Similarly, for a byte which is 8 bits, the maximum number of different assignments would be 2^8.

Is there a name for this number?

When we pass everything through our system that has ECMAScript, Java and MySQL, then a boolean does not have only two possible assignments. For instance, a false boolean gets saved as a 0 and the boxed value could be null so a boolean suddenly can get true, false, 0, 1, null or even undefined or <missing>.

I think it could get problematic in tests to guarantee that the values are not inconsistent. For instance, a value boolean locked could become null and then when a script or a layout template evaluates it then it will evaluate to false somewhere if the real value was null and similar problems.

So why don't we always assert that a boolean has the same number of possible values (2 values) and similarly for other types?

There is a mathematical term named "arity" that is something similar but not exactly, and statistics and probability theory also has the concept of "event space" that would be almost exactly what I mean. For instance, the event space for a boolean would be the set {0,1} which has cardinality 2 and that cardinality doesn't get preserved throughout the system, especially when data is passed as polyglots and/or serialized (json, jsonp, xml, yaml).

答:
I would call it cardinality (and indeed I have used it in that sense). It is strictly the cardinality of the set of all values a variable can take.

Edit: for example, a 16-bit integer can take exactly 65536 values. The cardinality of the set of all values that the integer can take is 655536.

Once you start to consider variables that have a range of valid values and also a range of invalid values (like a boolean with a bitwise value of 17), then you have to extend the concept somewhat, but you can still describe those values with set notation and the concept of cardinality still applies.

Edit: Yes, this is the mathematical set, not programming Set. If you were to apply the concept to the C# type short and derive the type short?, this would not have 65537 values, represented by the union of the set of 65536 values mentioned previously and one additional value, null.


答:
If you subscribe to the "types as a set of values" interpretation of type theory, then cardinality is in fact a good name.

So, the cardinality of bool would be 2, the cardinality of byte would be 256, and the cardinality of String would be ℵ0.

Title: Is there a name for the number of values a variable can take?

Body:
For example, a bit or a boolean can be either 0 or 1 so the number 2 is associated with it. Similarly, for a byte which is 8 bits, the maximum number of different assignments would be 2^8.

Is there a name for this number?

When we pass everything through our system that has ECMAScript, Java and MySQL, then a boolean does not have only two possible assignments. For instance, a false boolean gets saved as a 0 and the boxed value could be null so a boolean suddenly can get true, false, 0, 1, null or even undefined or <missing>.

I think it could get problematic in tests to guarantee that the values are not inconsistent. For instance, a value boolean locked could become null and then when a script or a layout template evaluates it then it will evaluate to false somewhere if the real value was null and similar problems.

So why don't we always assert that a boolean has the same number of possible values (2 values) and similarly for other types?

There is a mathematical term named "arity" that is something similar but not exactly, and statistics and probability theory also has the concept of "event space" that would be almost exactly what I mean. For instance, the event space for a boolean would be the set {0,1} which has cardinality 2 and that cardinality doesn't get preserved throughout the system, especially when data is passed as polyglots and/or serialized (json, jsonp, xml, yaml).


答:
You can certainly use any mix of client-side rendering and server-side rendering, but I would recommend against trying to mix ASP.NET MVC helpers with AngularJS directives. It might seem like a good idea at first because you're already used to using those helpers and you don't have to write "raw html", but they defeat the some of the purpose of what client-side applications try to achieve: separation of concerns, responsiveness, data-binding, and testability.

There's definitely a place for making mini-SPAs within a larger, traditional web-application, especially if you're converting a legacy application or if parts of the larger application don't need a SPA or are best served without it. But if you're going to render a given page - or part of page - on the client, then buy in completely and let AngularJS do what it knows how to do.

So let's say you have a Products model (some enumerable list of ) and you want to render that on the page in a list. You have three options I can think of:

Use a razor @ForEach and render it server-side, but accept that
your client-side AngularJS application won't know about this list
and won't bind it to its model

Wait until the page loads and AngularJS bootstraps, then make an API
call to your MVC server-side application for some JSON data and
stick it in the model. Use ng-repeat to render the list.

Use razor to serialize the Products model on the server into some
JSON string and embed that in the AngularJS controller you send
back. Use ng-repeat to render the list and take advantage of
client-side data-binding.

The last option is ugly. I can't think of a really good reason for it, unless you need client-side data-binding and you have to pay for each API call.

The first would be good if you don't need any data-binding on the client (it's a read-only list) or you need SEO.

The second is the way I would do it in most scenarios. You've decided to use AngularJS for a reason - let it do its job.

Don't use MVC helpers just because they're there. AngularJS provides its own directives that do much the same stuff. And if you need more, write your own. Part of using a client-side framework is buying in to the philosophy: the server is responsible for server-y stuff like authentication, server validation, and providing data through an API, and the client is responsible for being a front-end application. Keep your concerns separate.

None of this means you can't use ASP.NET MVC for routing, authentication, or the overall structure of your app. All that surrounds your AngularJS apps. Once you're inside a mini-SPA, though, do it the SPA way.

This is philosophy I've used when integrating ASP.NET MVC with AngularJS. The server-side MVC is responsible solely for rendering the initial page, and then providing a semi-RESTful API after that. It uses ASP.NET MVC to route URLs, authenticate, and other goodies. But there's almost no razor and definitely no HTML helpers.

Title: Server side C# MVC with AngularJS

Body:
I like using .NET MVC and have used it quite a bit in the past.  I have also built SPA's using AngularJS with no page loads other than the initial one.  I think I want to use a blend of the two in many cases.  Set up the application initially using .NET MVC and set up routing server side.  Then set up each page as a mini-SPA.  These pages can be quite complex with a lot of client side functionality.

My confusion comes in how to handle the model-view binding using both .NET MVC and the AngularJS scope.  Do I avoid the use of razor Html helpers?  The Html helpers create the markup behind the scene so it could get messy trying to add angularjs tags using the helpers.  So how to add ng-model for example to @Html.TextBoxFor(x => x.Name).  Also ng-repeat wouldn't work because I'm not loading my model into the scope, right?  I'd still want to use a c# foreach loop?

Where do I draw the lines of separation?  Has anyone gotten .NET MVC and AngularJS to play nicely together and what are your architectural suggestions to do so?


问:
Database design: circular reference but dynamically created
I am trying to design database for this case:

Assignments have vectors, relation is 1:N

Assignments have submissions, relation is 1:N

Submissions have executions, relation is 1:N

Every execution have one vector.

Business logic

teacher creates assignments and defines test vectors

student upload his solution, so record in submissions is created

After successful compilation of submission, submission is executed with defined test vectors. Each execution is one record in executions (One execution per vector).

So circular reference is created after successful execution, but if compilation failed no record is created in executions. Link between vectors and executions is needed for score calculation process, where is reference output from vectors compared to output from executions.

So in my case, circular reference is not persistent, but it depends on runtime, so it is wrong design?

答:
The tricky part is that relational databases don't care about the direction of the relationship or circular dependencies. In the object model we do care.

Define your "has a" relationships, and then abstract one of the classes with an interface to break the circular dependency. For example:

Assignment aggregates TestVector (i.e. has a collection of)

Submission has a Assignment

Execution has a Submission

Execution aggregates ExecutionStep (interface)

Vector is a ExecutionStep (interface)

See how Execution refers to an abstract ExecutionStep rather than a concrete Vector? That breaks the circular dependency, because now you can define other things for the execution to run without changing the object model.

(However, looking at it now, you don't need the foreign key from execution to vector, because you can get that with a join of Execution -> Submission -> Assignment -> Vector.)

...

When you write the classes to model these tables, then you have a circular code dependency, which is bad. So you can break the code dependency with an interface, but that's a separate issue from the database design.

In the database design, the reason Execution -> Vector is problematic is that it duplicates Execution -> Submission -> Assignment -> Vector. So you'd have to make sure those stay in sync.

Unless:

you're duplicating the data as a performance optimization & know the risks

you want Execution to reflect the vectors involved when it ran

That is, let's say an Assignment adds a new Vector. Any existing Executions won't see that new vector, because they already point to their list of vectors. But that may be a good thing, because it's saying "When this Execution ran, it used these Vectors, even though an Assignment may have added or removed Vectors since then".

I was thinking these artifacts wouldn't change; that they are all immutable. But that may be a bad assumption. So I could be wrong -- the reference from Execution to Vector may not be redundant. You'd know the answer to that better than me.


问:
Type casting variables in PHP, what is the practical reason for doing this?
PHP, as most of us know, has weak typing.  For those who don't, PHP.net says:

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used.

Love it or hate it, PHP re-casts variables on-the-fly.  So, the following code is valid:

```<code>$var = "10";
$value = 10 + $var;
var_dump($value); // int(20)
</code>```

PHP also allows you to explicitly cast a variable, like so:

```<code>$var = "10";
$value = 10 + $var;
$value = (string)$value;
var_dump($value); // string(2) "20"
</code>```

That's all cool...  but, for the life of me, I cannot conceive of a practical reason for doing this.

I don't have a problem with strong typing in languages that support it, like Java.  That's fine, and I completely understand it.  Also, I'm aware of - and fully understand the usefulness of - type hinting in function parameters.

The problem I have with type casting is explained by the above quote.  If PHP can swap types at-will, it can do so even after you force cast a type; and it can do so on-the-fly when you need a certain type in an operation.  That makes the following valid:

```<code>$var = "10";
$value = (int)$var;
$value = $value . ' TaDa!';
var_dump($value); // string(8) "10 TaDa!"
</code>```

So what's the point?

Take this theoretical example of a world where user-defined type casting makes sense in PHP:

You force cast variable $foo as int → (int)$foo.

You attempt to store a string value in the variable $foo.

PHP throws an exception!! ← That would make sense.  Suddenly the reason for user defined type casting exists!

The fact that PHP will switch things around as needed makes the point of user defined type casting vague.  For example, the following two code samples are equivalent:

```<code>// example 1
$foo = 0;
$foo = (string)$foo;
$foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo;

// example 2
$foo = 0;
$foo = (int)$foo;
$foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo;
</code>```

A year after originally asking this question, guess who found himself using typecasting in a practical environment?  Yours Truly.

The requirement was to display money values on a website for a restaurant menu.  The design of the site required that trailing zeros be trimmed, so that the display looked something like the following:

Menu Item 1 .............. $ 4
Menu Item 2 .............. $ 7.5
Menu Item 3 .............. $ 3
```

<p>The best way I found to do that wast to cast the variable as a float:</p>

```$price = '7.50'; // a string from the database layer.
echo 'Menu Item 2 .............. $ ' . (float)$price;
```

PHP trims the float's trailing zeros, and then recasts the float as a string for concatenation.

答:
One "use" of PHP re-casting variables on-the-fly that I see in use often is when retrieving data from external sources (user input or database). It lets coders (note that I did not say developers) ignore (or not even learn) the different datatypes available from different sources.

One coder (note that I did not say developer) whose code I have inherited and still maintain does not seem to know that there exists a difference between the string "20" that is returned in the $_GET super variable, to between the integer operation 20 + 20 when she adds it to the value in the database. She is only lucky that PHP uses . for string concatenation and not + like every other language, because I have seen her code "add" two strings (a varcahr from MySQL and a value from $_GET) and get an int.

Is this a practical example? Only in the sense that it lets coders get away with not knowing what datatypes they are working with. I personally hate it.


问:
Understanding Front End vs Back End Javascript?
I've been noticing lately, as I've played around with javascript, HTML5, and node.js for the first times that javascript seems to be a language that is used very differently (and with different syntax) depending on where it is used at.  My observation with javascript is this:

-Front end javascript finds the JS embedded in HTML5 pages, where it is used to build dynamic webpages and react to events that occur on the page.

-Back end JS is used as a solo language with node.js and its associated packages to handle web page requests, data transfers, and general server tasks.

Have I accurately summarized front end versus back end JS?

答:
That's a good summary.

Note that if you're front-loading functionality into your browser page, there may be little difference between your front-end and back-end javascript. For example, I worked on an app that did pathfinding through maps of airports. I did it in javascript in the browers to keep it fast & save a round trip. My code to do the graph traversal didn't make any reference to the browser or events, so it could have run on either front end or back end. I just put it on the front end to speed things up.

That's an addendum to your summary, though, rather than a contradiction.