问:
What are "class methods" and "instance methods", in Python?
There has been a discussion in chat relating to a question (the question itself being irrelevant to this one), that has revealed I may not know Python whatsoever.

In my mind, although terminology differs across languages, we may generally categorise functions as:

[free] functions

static methods / static member functions

non-static methods / non-static member functions

Apparently in Python there is another kind of function that doesn't fit into the above categories, one that is a method but "doesn't know its class".

What are "class methods" and "instance methods", in Python?

答:
What are “class methods” and “instance methods”, in Python?

An "instance method" uses the information contained in the instance to figure out what value to return (or which side-effect to do). These are very common.

A "class method" uses information about the class (and not an instance of that class) to affect what it does (they're typically used to create new instances as alternative constructors, and thus aren't incredibly common).

A "static method" doesn't use any information about the class or instance to calculate what it does. It is usually just in the class for convenience. (As such, these aren't very common either.)

A Function of X

Remember math class, "y is a function of x, f(x)?" Let's apply that in code:

```<code>y = function(x)
</code>```

Implied by the above is that since x may change, y may change when x changes. This is what is meant when we say that "y is a function of x"

What will y be when z is 1? 2? 'FooBarBaz'?

y is not a function of z, so z can be anything and not affect the outcome of the function assuming our function is a pure function. (If it accesses z as a global variable, then it's not a pure function - this is what is meant by functional purity.)

Keep the above in mind as you read the following descriptions:

Instance Methods

An instance method is function that is a function of an instance. The function accepts the instance implicitly as an argument to it, and the instance is used by the function to determine the output of the function.

A built-in example of an instance method is str.lower:

>>> 'ABC'.lower()
'abc'
```
<p><code>str.lower</code> is implicitly called on the instance of the string, and it uses the information contained in the instance to figure out which new string to return.</p>
<p>We can also explicitly pass the instance to the method looked up from the <code>str</code> class:</p>
<pre class="lang-py prettyprint-override"><code>>>> str.lower('ABC')
'abc'
</code>```

Class Methods:

Remember, in Python, everything is an object. That means the class is an object, and can be passed as an argument to a function.

A class method is a function that is a function of the class. It accepts the class as an argument to it.

A builtin example is dict.fromkeys:

```<code>>>> dict.fromkeys('ABC')
{'C': None, 'B': None, 'A': None}
</code>```

The function implicitly knows its own class, the function uses the class to  affects the output of the function, and it creates a new one of that class from the iterable. An OrderedDict demonstrates this when using the same method:

```<code>>>> from collections import OrderedDict
>>> OrderedDict.fromkeys('ABC')
OrderedDict([('A', None), ('B', None), ('C', None)])
</code>```

The class method uses information about the class (and not an instance of that class) to affect what type of class to return.

We can also look up the method directly from the class namespace (a simple dictionary) and pass the class object explicitly:

>>> vars(dict)['fromkeys'](dict, 'ABC')
{'A': None, 'B': None, 'C': None}
>>> vars(dict)['fromkeys'](OrderedDict, 'ABC')
OrderedDict([('A', None), ('B', None), ('C', None)])
```
<h1>Static Methods</h1>
<p>You mention a method that "doesn't know its class" - this is a static method in Python. It is merely attached for convenience to the class object. It could optionally be a separate function in another module, but its call signature would be the same.</p>
<p>A static method is a function of neither the class nor the object.</p>
<p>A built-in example of a static method is str.maketrans from Python 3.</p>
```>>> str.maketrans('abc', 'bca')
{97: 98, 98: 99, 99: 97}
```
<p>Given a couple of arguments, it makes a dictionary that is not a function of its class.</p>
<p>It is convenient because <code>str</code> is always available in the global namespace, so you can easily use it with the translate function:</p>
```>>> 'abracadabra'.translate(str.maketrans('abc', 'bca'))
'bcrbabdbcrb'
```
<p>In Python 2, you have to access it from the <code>string</code> module:</p>
```>>> 'abracadabra'.translate(str.maketrans('abc', 'bca'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'str' has no attribute 'maketrans'
>>> import string
>>> 'abracadabra'.translate(string.maketrans('abc', 'bca'))
'bcrbabdbcrb'
```
<p>And now, in Python 3.10, thanks to issue 43682 being resolved, we can indeed simply look up the method/function in the class namespace and use it as a function:</p>
<pre class="lang-py prettyprint-override"><code>>>> vars(str)['maketrans']('abc', 'ABC')
{97: 65, 98: 66, 99: 67}
</code>```

Example

```<code>class AClass(object):
    """In Python, a class may have several types of methods:
    instance methods, class methods, and static methods
    """

    def an_instance_method(self, x, y, z=None):
        """this is a function of the instance of the object
        self is the object's instance
        """
        return self.a_class_method(x, y)

    @classmethod
    def a_class_method(cls, x, y, z=None):
        """this is a function of the class of the object
        cls is the object's class
        """
        return cls.a_static_method(x, y, z=z)

    @staticmethod
    def a_static_method(x, y, z=None):
        """this is neither a function of the instance or class to
        which it is attached
        """
        return x, y, z
</code>```

Let's instantiate:

```<code>>>> instance = AClass()
</code>```

Now the instance can call all of the methods:

```<code>>>> instance.an_instance_method('x', 'y')
('x', 'y', None)
>>> instance.a_static_method('x', 'y')
('x', 'y', None)
>>> instance.a_class_method('x', 'y')
('x', 'y', None)
</code>```

But the class is not usually intended to call the instance method, though it is expected to call the others:

```<code>>>> AClass.a_class_method('x', 'y')
('x', 'y', None)
>>> AClass.a_static_method('x', 'y')
('x', 'y', None)
>>> AClass.an_instance_method('x', 'y')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an_instance_method() missing 1 required positional argument: 'y'
</code>```

You would have to explicitly pass the instance to call the instance method:

```<code>>>> dict.fromkeys('ABC')
{'C': None, 'B': None, 'A': None}
</code>```0

Body:
What are “class methods” and “instance methods”, in Python?

An "instance method" uses the information contained in the instance to figure out what value to return (or which side-effect to do). These are very common.

A "class method" uses information about the class (and not an instance of that class) to affect what it does (they're typically used to create new instances as alternative constructors, and thus aren't incredibly common).

A "static method" doesn't use any information about the class or instance to calculate what it does. It is usually just in the class for convenience. (As such, these aren't very common either.)

A Function of X

Remember math class, "y is a function of x, f(x)?" Let's apply that in code:

y = function(x)

Implied by the above is that since x may change, y may change when x changes. This is what is meant when we say that "y is a function of x"

What will y be when z is 1? 2? 'FooBarBaz'?

y is not a function of z, so z can be anything and not affect the outcome of the function assuming our function is a pure function. (If it accesses z as a global variable, then it's not a pure function - this is what is meant by functional purity.)

Keep the above in mind as you read the following descriptions:

Instance Methods

An instance method is function that is a function of an instance. The function accepts the instance implicitly as an argument to it, and the instance is used by the function to determine the output of the function.

A built-in example of an instance method is str.lower:

>>> 'ABC'.lower()
'abc'

str.lower is implicitly called on the instance of the string, and it uses the information contained in the instance to figure out which new string to return.

We can also explicitly pass the instance to the method looked up from the str class:

>>> str.lower('ABC')
'abc'

Class Methods:

Remember, in Python, everything is an object. That means the class is an object, and can be passed as an argument to a function.

A class method is a function that is a function of the class. It accepts the class as an argument to it.

A builtin example is dict.fromkeys:

>>> dict.fromkeys('ABC')
{'C': None, 'B': None, 'A': None}

The function implicitly knows its own class, the function uses the class to  affects the output of the function, and it creates a new one of that class from the iterable. An OrderedDict demonstrates this when using the same method:

>>> from collections import OrderedDict
>>> OrderedDict.fromkeys('ABC')
OrderedDict([('A', None), ('B', None), ('C', None)])

The class method uses information about the class (and not an instance of that class) to affect what type of class to return.

We can also look up the method directly from the class namespace (a simple dictionary) and pass the class object explicitly:

>>> vars(dict)['fromkeys'](dict, 'ABC')
{'A': None, 'B': None, 'C': None}
>>> vars(dict)['fromkeys'](OrderedDict, 'ABC')
OrderedDict([('A', None), ('B', None), ('C', None)])

Static Methods

You mention a method that "doesn't know its class" - this is a static method in Python. It is merely attached for convenience to the class object. It could optionally be a separate function in another module, but its call signature would be the same.

A static method is a function of neither the class nor the object.

A built-in example of a static method is str.maketrans from Python 3.

>>> str.maketrans('abc', 'bca')
{97: 98, 98: 99, 99: 97}

Given a couple of arguments, it makes a dictionary that is not a function of its class.

It is convenient because str is always available in the global namespace, so you can easily use it with the translate function:

>>> 'abracadabra'.translate(str.maketrans('abc', 'bca'))
'bcrbabdbcrb'

In Python 2, you have to access it from the string module:

>>> 'abracadabra'.translate(str.maketrans('abc', 'bca'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'str' has no attribute 'maketrans'
>>> import string
>>> 'abracadabra'.translate(string.maketrans('abc', 'bca'))
'bcrbabdbcrb'

And now, in Python 3.10, thanks to issue 43682 being resolved, we can indeed simply look up the method/function in the class namespace and use it as a function:

>>> vars(str)['maketrans']('abc', 'ABC')
{97: 65, 98: 66, 99: 67}

Example

class AClass(object):
    """In Python, a class may have several types of methods:
    instance methods, class methods, and static methods
    """

    def an_instance_method(self, x, y, z=None):
        """this is a function of the instance of the object
        self is the object's instance
        """
        return self.a_class_method(x, y)

    @classmethod
    def a_class_method(cls, x, y, z=None):
        """this is a function of the class of the object
        cls is the object's class
        """
        return cls.a_static_method(x, y, z=z)

    @staticmethod
    def a_static_method(x, y, z=None):
        """this is neither a function of the instance or class to
        which it is attached
        """
        return x, y, z

Let's instantiate:

>>> instance = AClass()

Now the instance can call all of the methods:

>>> instance.an_instance_method('x', 'y')
('x', 'y', None)
>>> instance.a_static_method('x', 'y')
('x', 'y', None)
>>> instance.a_class_method('x', 'y')
('x', 'y', None)

But the class is not usually intended to call the instance method, though it is expected to call the others:

>>> AClass.a_class_method('x', 'y')
('x', 'y', None)
>>> AClass.a_static_method('x', 'y')
('x', 'y', None)
>>> AClass.an_instance_method('x', 'y')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an_instance_method() missing 1 required positional argument: 'y'

You would have to explicitly pass the instance to call the instance method:

>>> AClass.an_instance_method(instance, 'x', 'y')
('x', 'y', None)

ContentLicense: CC BY-SA 4.0


答:
The short answer

an instance method knows its instance (and from that, its class)

a class method knows its class

a static method doesn't know its class or instance

The long answer

Class methods

A class method is one that belongs to the class as a whole. It doesn't require an instance. Instead, the class will automatically be sent as the first argument. A class method is declared with the @classmethod decorator.

For example:

```<code>class Foo(object):
    @classmethod
    def hello(cls):
        print("hello from %s" % cls.__name__)
Foo.hello()
-> "Hello from Foo"
Foo().hello()
-> "Hello from Foo"
</code>```

Instance Methods

On the other hand, an instance method requires an instance in order to call it, and requires no decorator. This is by far the most common type of method.

```<code>class Foo(object):
    def hello(self):
        print("hello from %s" % self.__class__.__name__)
Foo.hello()
-> TypeError: hello() missing 1 required positional argument: 'self'
</code>```

(note: the above is with python3; with python2 you'll get a slightly different error)

Static methods

A static method is similar to a class method, but won't get the class object as an automatic parameter. It is created by using the @staticmethod decorator.

```<code>class Foo(object):
    @staticmethod
    def hello(cls):
        print("hello from %s" % cls.__name__)

Foo.hello()
-> TypeError: hello() missing 1 required positional argument: 'cls'
</code>```

Documentation links

Here are links to the relevant python3 documentaton:

https://docs.python.org/3.5/library/functions.html#classmethod

https://docs.python.org/3.5/library/functions.html#staticmethod

The data model documentation has this to say about the difference between class methods and static methods:

Static method objects Static method objects provide a way of defeating
  the transformation of function objects to method objects described
  above. A static method object is a wrapper around any other object,
  usually a user-defined method object. When a static method object is
  retrieved from a class or a class instance, the object actually
  returned is the wrapped object, which is not subject to any further
  transformation. Static method objects are not themselves callable,
  although the objects they wrap usually are. Static method objects are
  created by the built-in staticmethod() constructor.

Class method objects
  A class method object, like a static method object, is a
  wrapper around another object that alters the way in which that object
  is retrieved from classes and class instances. The behaviour of class
  method objects upon such retrieval is described above, under
  “User-defined methods”. Class method objects are created by the
  built-in classmethod() constructor.

Related questions

What is the difference between @staticmethod and @classmethod in Python? (stackoverflow)

ContentLicense: CC BY-SA 3.0

Body:
There has been a discussion in chat relating to a question (the question itself being irrelevant to this one), that has revealed I may not know Python whatsoever.

In my mind, although terminology differs across languages, we may generally categorise functions as:

[free] functions

static methods / static member functions

non-static methods / non-static member functions

Apparently in Python there is another kind of function that doesn't fit into the above categories, one that is a method but "doesn't know its class".

What are "class methods" and "instance methods", in Python?

Body:
The short answer

an instance method knows its instance (and from that, its class)

a class method knows its class

a static method doesn't know its class or instance

The long answer

Class methods

A class method is one that belongs to the class as a whole. It doesn't require an instance. Instead, the class will automatically be sent as the first argument. A class method is declared with the @classmethod decorator.

For example:

class Foo(object):
    @classmethod
    def hello(cls):
        print("hello from %s" % cls.__name__)
Foo.hello()
-> "Hello from Foo"
Foo().hello()
-> "Hello from Foo"

Instance Methods

On the other hand, an instance method requires an instance in order to call it, and requires no decorator. This is by far the most common type of method.

class Foo(object):
    def hello(self):
        print("hello from %s" % self.__class__.__name__)
Foo.hello()
-> TypeError: hello() missing 1 required positional argument: 'self'

(note: the above is with python3; with python2 you'll get a slightly different error)

Static methods

A static method is similar to a class method, but won't get the class object as an automatic parameter. It is created by using the @staticmethod decorator.

class Foo(object):
    @staticmethod
    def hello(cls):
        print("hello from %s" % cls.__name__)

Foo.hello()
-> TypeError: hello() missing 1 required positional argument: 'cls'

Documentation links

Here are links to the relevant python3 documentaton:

https://docs.python.org/3.5/library/functions.html#classmethod

https://docs.python.org/3.5/library/functions.html#staticmethod

The data model documentation has this to say about the difference between class methods and static methods:

Static method objects Static method objects provide a way of defeating
  the transformation of function objects to method objects described
  above. A static method object is a wrapper around any other object,
  usually a user-defined method object. When a static method object is
  retrieved from a class or a class instance, the object actually
  returned is the wrapped object, which is not subject to any further
  transformation. Static method objects are not themselves callable,
  although the objects they wrap usually are. Static method objects are
  created by the built-in staticmethod() constructor.

Class method objects
  A class method object, like a static method object, is a
  wrapper around another object that alters the way in which that object
  is retrieved from classes and class instances. The behaviour of class
  method objects upon such retrieval is described above, under
  “User-defined methods”. Class method objects are created by the
  built-in classmethod() constructor.

Related questions

What is the difference between @staticmethod and @classmethod in Python? (stackoverflow)


问:
Force instance methods to use only public members
What do you think about code like this:

```<code>public class ThisClass
{
    // this method uses only public members
    public void DoSomething()
    {
        AccessToPublicMembersOfThisClass.DoSomething(this);
    }
}

// EDIT: this class is not nested!
internal class AccessToPublicMembersOfThisClass
{
    internal void static DoSomething (ThisClass x)
    {
       // we are sure were using only public members because
       // private members are unaccessible from here

        x.Action();
    }
}
</code>```

Is it good or not?

I could do some static methods, but I don't want to pass any arguments to them.

答:
Is it good or not?

It is decidedly not good.

If you don't want some function to access private methods, then that is an overwhelming sign that it shouldn't be a part of the class.

Worse, it's not clear that you are trying to enforce that, meaning the next programmer that comes along is likely to just undo this and work with the private variables directly. If you want a function kinda-sorta on the class, but needs to live elsewhere, use extension methods - that's why they're there.


问:
Does my design break modularity and loose coupling?
I want to know if my implementation is modular and loosely coupled such that pieces can be replaced easily.

Any concrete class that extends the abstract class HexGridLayout will be expected to update the field coords by using the field center of the HexGrid.

Does passing HexGrid to the HexGridLayout break the modularity and cause tight coupling? Is this a good design approach to making the coords and center field updates modular?

I'd be glad to hear any suggestions to improve my implementation as well,
Thanks!

答:
I would not encourage your specific approach; it is modular and does appear totally functional, but I would suggest a slight change.

I would encourage you to invert the relationship between the HexGrid and HexGridLayout such that instead of the HexGridLayout directly accessing and changing the coords and center properties, instead it takes them as parameters and returns a new set of values.

Then there's two choices to getting the coords and center fields updated:

You can give whatever HexGridLayout you want to use to the HexGrid and the HexGrid will call update(coords, center) and receive new values for coords and center which it will set on itself.

If currently HexGrid isn't the one calling update - then whichever class is calling it on HexGridLayout should call update(hexGrid.coords, hexGrid.center) and retrieving the updated coords/center values it updates it's instance of HexGrid itself.

I encourage number 2 above, because this completely decouples HexGridLayout from HexGrid while making available the updated coords and center values to any who wish to use them to update a HexGrid - you could use 1 HexGridLayout to get updated values for any number of HexGrids because of this loose coupling, or just use it to log or even project future updates etc.

So, as it stands, your design is modular, though I wouldn't quite claim it's utterly loosely coupled - because your HexGridLayout is completely reliant on your implementation of HexGrid and cannot be used to layout other types of HexGrid (perhaps a network based HexGrid would be useful for client/server functionality which your HexGridLayout currently wouldn't support for instance).


问:
What decent web-frameworks exists for functional programming?
I would like to do some web programming using functional programming. What decent web-frameworks exists for functional programming languages?</p>

答:
As you have left any languages out of the question, I guess you accept multiple languages...

So for the language F# there exists FSharp.WebTools.

The F# Web Tools augment the F# distribution with tools to author homogeneous client/server/database web applications in one type-checked project. The modal distinctions between client and server are checked through the use of F# workflows, and LINQ can be used for database access. In the first version, parts of the application are dynamically served as JavaScript. Planned extensions include serving client-side portions as Silverlight code.

F# Web Tools: "Ajax" applications made simple

Rich client/server web applications in F#

Ajax-style Client/Server Programming with F#

ContentLicense: CC BY-SA 2.5


答:
An "instance method" is a method that gets passed the instance object as its first parameter, which by convention is called self. This is the default.

A "static method" is a method without the initial self parameter. This is implemented with the @staticmethod decorator.

A "class method" is a method where the initial parameter is not an instance object, but the class object (see this part of the Python docs for what a "class object" is), which by convention is called cls. This is implemented with the @classmethod decorator.

The typical usage of the term "static method" in C/C++/etc applies to both Python "static" and Python "class" methods, since both of those types of methods lack a reference to the instance. In C/C++/etc, methods normally have implicit access to all non-instance members/methods of the class, which is probably why this distinction only exists in languages like Python/Ruby/etc.

Title: What are "class methods" and "instance methods", in Python?


问:
Why doesn't ES6 have thin-arrow functions?
ES6 added fat-arrow functions (=>), which have two major differences from normal functions:

shorter syntax (including implicit return if you use a single-expression body)

inherit this from surrounding scope

These are both very useful features, but seem to me completely separate in their value and application – sometimes I want one, or the other, or both, or neither. It seems odd that if I want to use a short-syntax function, I have to also use the this-modifying behaviour. And vice versa. I don't see why these two capabilities are implemented as a single addition to the language.

What if I want to use a short syntax function for its implicit return and brevity (in some context where a full function (..) { return ...} would be slightly less readable), but I want to use this in my function to refer to the calling context? There's no way to do this.

CoffeeScript has both -> and => style functions, and apparently ES6 borrowed the => style from there. So my question is, why didn't ES6 also borrow the -> style?

答:
See the proposal to add arrow functions: http://wiki.ecmascript.org/doku.php?id=harmony:arrow_function_syntax1

What it says is:

However, we don’t want CoffeeScript’s ->, it’s confusing to have two
  arrows and dynamic this binding is an oft-fired footgun.

You can also see some discussion of a previous version of the proposal which did have the -> syntax as well: https://esdiscuss.org/topic/arrow-function-syntax-simplified

It appears to come down to the following:

Having two arrow syntaxes with subtly different semantics would increase complication and confusion.

The dynamic this binding of function() and -> was deemed rarely useful, and a foot-gun.

If you really need dynamic this binding, you can still use function(), having a shortcut syntax wasn't very helpful.


问:
Implementing an interface when you don't need one of the properties
Pretty straight-forward. I'm implementing an interface, but there's one property that is unnecessary for this class and, in fact, shouldn't be used. My initial idea was to just do something like:

```<code>int IFoo.Bar
{
    get { raise new NotImplementedException(); }
}
</code>```

I suppose there's nothing wrong with this, per se, but it doesn't feel "right". Has anyone else come across a similar situation before? If so, how did you approach it?

答:
Looks fine to me, if this is your situation.

However, it seems to me that your interface (or use thereof) is broken if a deriving class doesn't actually implement all of it. Consider splitting that interface up.

Disclaimer: This requires multiple inheritance to do properly, and I have no idea whether C# supports that.


问:
Why use PHP_AUTH_USER instead of taking credentials under post method
What would be the advantages of using PHP_AUTH_USER and PHP_AUTH_PW instead of the verifying the credentials under method - post .

Why i should use:
$_SERVER["PHP_AUTH_USER"]; and $_SERVER["PHP_AUTH_PW"]

instead of

$_POST["user"]; and $_POST["pass"];

what actual difference does it make ?

what are the advantages and disadvantages of both techniques ?

which one is more vulnerable ?

答:
You want to know the advantages, so here goes: PHP_AUTH_USER is an interface to HTTP Basic Authentication, which is already implemented at protocol level.

This allows a looser coupling between modules (since Basic Auth is a common standard, the modules using authentication needn't know each other), and you can have one authentication system leveraging HTTP Basic Auth, and thus forwarding information to other modules.

It also allows you not to implement authentication at all and rely instead on the server's - e.g. with Apache's .htaccess/htpasswd.

Of course, in this latter case, things like password recovery and editing become proportionately more difficult, and in some setups, impossible unless you get a sysadmin to do it for you.

By the same token, methods using forms and _POST, possibly through AJAX, are often more portable between platforms (suppose you have a CGI configuration that doesn't support PHP_AUTH_*?), and allow more/easier customizability both in behaviour (e.g. logout, password caching) and interface (basic auth is done by the browser, and you usually get a standard browser dialog asking username and password, which might "clash" with your interface).


问:
Overriding Equals in an unbrittle way
I have a class WorkflowItemSearchCriteria whose instances represent a set of values and references that will be used to return a filtered result set of workflow items based on the given search criteria.

```<code>class WorkflowItemSearchCriteria
{
    string ID { get; set; }
    Client TargetClient { get; set; }
    Person Supervisor { get; set; }
    Person WorkingAttorney { get; set; }
    SearchDateKind? TargetSearchDateKind { get; set; }
    DateTime? FromDate { get; set; }
    DateTime? ToDate { get; set; }

    public override bool Equals(object obj)
    {
        if (!(obj is WorkflowItemSearchCriteria)) return false;
        var target = (WorkflowItemSearchCriteria) obj;
        if (!target.ID.Equals(this.ID)) return false;
        if (target.TargetClient != this.TargetClient) return false;
        if (target.Supervisor != this.Supervisor) return false;
        if (target.WorkingAttorney != this.WorkingAttorney) return false;
        if (!target.TargetSearchDateKind.Equals(this.TargetSearchDateKind)) return false;
        if (!target.FromDate.Equals(this.FromDate)) return false;
        if (!target.ToDate.Equals(this.ToDate)) return false;
        return true;
    }

    public override int GetHashCode()
    {
        // According to MSDN, two objects that are equal must return the same hash code,
        // but the same hash code does not mean two objects are equal.  If two value
        // objects are equal, then all property and field values must be equal,
        // so it's sufficient to return the hash code from just ONE field or property
        // because it will equal the hash code from another object that is equal to it.
        return ID.GetHashCode();
    }

    enum SearchDateKind
    {
        DateCreated,
        DateCompleted
    }
}
</code>```

At some point, I want to compare two instances of this class for value-wise equality, so I'm overriding Equals as shown.  I've been reading sources such as this to help me along, but I still feel that doing it the way I have results in brittle code because future developers would have to remember to update the Equals overload if there were ever properties added to WorkflowItemSearchCriteria.

Is there a better approach to this?

答:
One approach to this problem is to add a unit test which checks for proper equality.  The unit test could use reflection to enumerate every property, constructing objects with only one unequal property and verifying that equality handles it properly.

A tool like Microsoft Pex can go a step further, exhaustively (algorithmically, not via brute force) checking such equality.  However, resolving this problem with Pex is probably both difficult and overkill.

An alternative approach is to use some sort of static analysis tool which solves this problem for you, but I'm unsure if any reasonable tooling exists for this scenario.

Title: Overriding Equals in an unbrittle way


问:
Refactoring pattern Split Temporary Variable vs collection variable
We are using Java as a backend development language.

We are using a List variable as

```<code>method() {
  List recordsList = new ArrayList<Record>();
  .
  .
  recordsList.add(records);
  .
  .
  recordsList.flush();
  .
  .
  recordsList.add(new Record());
}
</code>```

Should we consider Split Temporary Variable refactoring pattern in this case, thus creating a new List as

```<code> method() {
  List recordsList = new ArrayList<Record>();
  .
  .
  recordsList.add(records);
  .
  .
  recordsList.flush();
  .
  .
  List newRecordList = new ArrayList<Record>();
  newRecordList.add(new Record());
}
</code>```

答:
Yes. There are three reasons to do this:

it prevents confusion where someone reading the code might think an operation performed on the second group of items was performed on the first or vice versa, because they didn't notice the list being cleared

it encourages you to come up with more specific variable names - you'll have to rename one of them and hopefully you will find a useful way of designating the difference between the two lists

at least in Java, the ArrayList implementation doesn't shrink its backing array when you clear the list, which could result in memory being wasted while the second half of your operation is ongoing.

Furthermore, I would examine your method closely in terms of size and complexity. If your operation generates a list, uses it, then empties and generates a new one, I would question whether it might be wise to split it into two methods encapsulating these two separable phases of the operation.


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

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

答:
In layman's terms:

You cannot.

Compilers and interpreters are unit-tested as any other (professional) software.

A sucessful test doesn't mean a program is bug-free, it only means no bugs were detected.

A wide user base using the compiler during a long time is a pretty indicator of it having very few bugs, because users usually test cases the designers didn't think of.

Being open source is also a good indicator. "Given enough eyeballs, all bugs are shallow... Given a large enough beta-tester and co-developer base, almost every problem will be characterized quickly and the fix will be obvious to someone.". A closed-source compiler could have bugs that arise at very specific times or that generate less-than optimal machine code and the company behind it could just simply not disclose their existence ang give it a very low priority in the product's road map.

Bottom-line:

I'd say go for OOP (Old, Open and Popular). I just made up that acronym.


答:
You can't be certain, but you just assume they are, until you discover they are not. There have been plenty of bugs in compilers and hardware over the years.

The way these are tested, for example a compiler, is that they are very narrowly and rigidly defined, carefully written, then tested with an enormous test suite to verify correctness. Add to that the wide user base of a compiler, and more bugs will be detected and reported. A dentist appointment scheduling app, comparatively, has many fewer users, and fewer still that are capable of detecting defects.

SQLite consists of about 73k lines of code, while its test suite consists of about 91378k lines of code, more than 1250x times that of SQLite itself. I expect compilers and other core tools have similar ratios. Processors today are designed essentially with software, using hardware description languages like Verilog or VHDL, and those have software tests run on them as well, as well as specialized IO pins for running self tests at the point of manufacture.

Ultimately it's a probability game, and repeated and broadly covering testing allows you to push the probability of defects down to an acceptably low level, the same as an other software project.

Title: How can we be certain that the lower components of computer programming like compilers, assemblers, machine instructions, etc. are flawless?

Body:
Since we are becoming more and more reliant on computing, including very critical tasks of day-to-day life, I was just wondering how those vital components are tested.

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


问:
Should I log errors on exception throwing constructors?
I was building an application for a few months and I come to realize a pattern that emerged:

```<code>logger.error(ERROR_MSG);
throw new Exception(ERROR_MSG);
</code>```

Or, when catching:

```<code>try {
    // ...block that can throw something
} catch (Exception e) {
    logger.error(ERROR_MSG, e);
    throw new MyException(ERROR_MSG, e);
}
</code>```

So, whenever I was throwing or catching an exception, I would log it. In fact, that was almost all logging I did on the application (besides something for application initialization).

So, as a programmer, I shun repetition; So I decided to move the logger calls to the exception construction, so, whenever I was building an exception, things would be logged. I could also, certainly, create a ExceptionHelper that throwed the exception for me, but that would make my code harder to interpret and, even worse, the compiler wouldn't deal well with it, failing to realize that a call to that member would throw immediately.

So, is this an anti-pattern? If so, why?

答:
Rethrowing an exception only because you decided to log it using a catch block (meaning the exception has not changed at all) is a bad idea.

One of the reasons we use exceptions, exceptions messages and its handling is so that we know what went wrong and cleverly written exceptions can speed up finding the bug by a great margin.

Also remember, handling exceptions costs way more resources than let's say have an if, so you shouldn't be handling them all to often just because you feel like it. It has impact on the performance of your application.

It is however good approach to use exception as a mean to mark the application layer in which the error appeared.

Consider the following semi-pseudo code:

```<code>interface ICache<T, U>
{
    T GetValueByKey(U key); // may throw an CacheException
}

class FileCache<T, U> : ICache<T, U>
{
    T GetValueByKey(U key)
    {
        throw new CacheException("Could not retrieve object from FileCache::getvalueByKey. The File could not be opened. Key: " + key);
    }
}

class RedisCache<T, U> : ICache<T, U>
{
    T GetValueByKey(U key)
    {
        throw new CacheException("Could not retrieve object from RedisCache::getvalueByKey. Failed connecting to Redis server. Redis server timed out. Key: " + key);
    }
}

class CacheableInt
{
    ICache<int, int> cache;
    ILogger logger;

    public CacheableInt(ICache<int, int> cache, ILogger logger)
    {
        this.cache = cache;
        this.logger = logger;
    }

    public int GetNumber(int key) // may throw service exception
    {
        int result;

        try {
            result = this.cache.GetValueByKey(key);
        } catch (Exception e) {
            this.logger.Error(e);
            throw new ServiceException("CacheableInt::GetNumber failed, because the cache layer could not respond to request. Key: " + key);
        }

        return result;
    }
}

class CacheableIntService
{
    CacheableInt cacheableInt;
    ILogger logger;

    CacheableInt(CacheableInt cacheableInt, ILogger logger)
    {
        this.cacheableInt = cacheableInt;
        this.logger = logger;
    }

    int GetNumberAndReturnCode(int key)
    {
        int number;

        try {
            number = this.cacheableInt.GetNumber(key);
        } catch (Exception e) {
            this.logger.Error(e);
            return 500; // error code
        }

        return 200; // ok code
    }
}
</code>```

Let's assume someone has called the GetNumberAndReturnCode and recieved the 500 code, signaling an error. He would call the support, who would open the log file and see this:

```<code>ERROR: 12:23:27 - Could not retrieve object from RedisCache::getvalueByKey. Failed connecting to Redis server. Redis server timed out. Key: 28
ERROR: 12:23:27 - CacheableInt::GetNumber failed, because the cache layer could not respond to request. Key: 28
</code>```

The developer then immediately knows which layer of the software caused the process to abort and has an easy way of identifying the issue. In this case it is critical, because Redis timing out should never happend.

Perhaps another user would call the same method, also recieve the 500 code, but log would show the following:

```<code>INFO: 11:11:11- Could not retrieve object from RedisCache::getvalueByKey. Value does not exist for the key 28.
INFO: 11:11:11- CacheableInt::GetNumber failed, because the cache layer could not find any data for the key 28.
</code>```

In which case the support could simply respond to the user that the request was invalid because he is requesting a value for a non-existent ID.

Summary

If you are handling exceptions, make sure to handle them in the correct way. Also make sure your exceptions include the correct data/messages in the first place, following your architecture layers, so the messages will help you identify a problem which may occur.

Body:
Rethrowing an exception only because you decided to log it using a catch block (meaning the exception has not changed at all) is a bad idea.

One of the reasons we use exceptions, exceptions messages and its handling is so that we know what went wrong and cleverly written exceptions can speed up finding the bug by a great margin.

Also remember, handling exceptions costs way more resources than let's say have an if, so you shouldn't be handling them all to often just because you feel like it. It has impact on the performance of your application.

It is however good approach to use exception as a mean to mark the application layer in which the error appeared.

Consider the following semi-pseudo code:

interface ICache<T, U>
{
    T GetValueByKey(U key); // may throw an CacheException
}

class FileCache<T, U> : ICache<T, U>
{
    T GetValueByKey(U key)
    {
        throw new CacheException("Could not retrieve object from FileCache::getvalueByKey. The File could not be opened. Key: " + key);
    }
}

class RedisCache<T, U> : ICache<T, U>
{
    T GetValueByKey(U key)
    {
        throw new CacheException("Could not retrieve object from RedisCache::getvalueByKey. Failed connecting to Redis server. Redis server timed out. Key: " + key);
    }
}

class CacheableInt
{
    ICache<int, int> cache;
    ILogger logger;

    public CacheableInt(ICache<int, int> cache, ILogger logger)
    {
        this.cache = cache;
        this.logger = logger;
    }

    public int GetNumber(int key) // may throw service exception
    {
        int result;

        try {
            result = this.cache.GetValueByKey(key);
        } catch (Exception e) {
            this.logger.Error(e);
            throw new ServiceException("CacheableInt::GetNumber failed, because the cache layer could not respond to request. Key: " + key);
        }

        return result;
    }
}

class CacheableIntService
{
    CacheableInt cacheableInt;
    ILogger logger;

    CacheableInt(CacheableInt cacheableInt, ILogger logger)
    {
        this.cacheableInt = cacheableInt;
        this.logger = logger;
    }

    int GetNumberAndReturnCode(int key)
    {
        int number;

        try {
            number = this.cacheableInt.GetNumber(key);
        } catch (Exception e) {
            this.logger.Error(e);
            return 500; // error code
        }

        return 200; // ok code
    }
}

Let's assume someone has called the GetNumberAndReturnCode and recieved the 500 code, signaling an error. He would call the support, who would open the log file and see this:

ERROR: 12:23:27 - Could not retrieve object from RedisCache::getvalueByKey. Failed connecting to Redis server. Redis server timed out. Key: 28
ERROR: 12:23:27 - CacheableInt::GetNumber failed, because the cache layer could not respond to request. Key: 28

The developer then immediately knows which layer of the software caused the process to abort and has an easy way of identifying the issue. In this case it is critical, because Redis timing out should never happend.

Perhaps another user would call the same method, also recieve the 500 code, but log would show the following:

INFO: 11:11:11- Could not retrieve object from RedisCache::getvalueByKey. Value does not exist for the key 28.
INFO: 11:11:11- CacheableInt::GetNumber failed, because the cache layer could not find any data for the key 28.

In which case the support could simply respond to the user that the request was invalid because he is requesting a value for a non-existent ID.

Summary

If you are handling exceptions, make sure to handle them in the correct way. Also make sure your exceptions include the correct data/messages in the first place, following your architecture layers, so the messages will help you identify a problem which may occur.


答:
Has anyone else come across a similar situation before?

Yes, the .Net library designers did.  The Dictionary class does what you're doing.  It uses explicit implementation to effectively hide* some of the IDictionary methods.  It's explained better here, but to summarize, in order to use the Dictionary's Add, CopyTo, or Remove methods that take KeyValuePairs, you first have to cast the object to an IDictionary.

* It's not "hiding" the methods in the strict sense of the word "hide" as Microsoft uses it.  But I don't know a better term in this instance.

Title: Implementing an interface when you don't need one of the properties

Body:
Pretty straight-forward. I'm implementing an interface, but there's one property that is unnecessary for this class and, in fact, shouldn't be used. My initial idea was to just do something like:

```<code>int IFoo.Bar
{
    get { raise new NotImplementedException(); }
}
</code>```

I suppose there's nothing wrong with this, per se, but it doesn't feel "right". Has anyone else come across a similar situation before? If so, how did you approach it?


答:
This is a classical example of how people decide to violate the Liskov Subtitution Principle. I strongly discourage it but would encourage possibly a different solution:

Perhaps the class you're writing doesn't provide the functionality the interface prescribes if it doesn't have use of all the members of the interface.

Alternatively, that interface may be doing multiple things and could be separated per the Interface Segregation Principle.

If the first is the case for you, just don't implement the interface on that class. Think of it like an electrical socket where the ground hole is unnecessary so it doesn't actually attach to ground. You don't plug anything with ground in and no big deal! But as soon as you use something which needs a ground - you could be in for a spectacular fail. Better off not punching a fake-ground hole in. So if your class doesn't actually do what the interface intends, don't implement the interface.

Here are a few quick bits from wikipedia:

Liskov Substitution Principle can be simply formulated as, "Don't strengthen pre-conditions, and don't weaken post-conditions".

More formally, the Liskov substitution principle (LSP) is a particular definition of a subtyping relation, called (strong) behavioral subtyping, that was initially introduced by Barbara Liskov in a 1987 conference keynote address entitled Data abstraction and hierarchy. It is a semantic rather than merely syntactic relation because it intends to guarantee semantic interoperability of types in a hierarchy, [...]

For semantic interoperability and substitutability between different implementations of the same contracts - you need them all to commit to the same behaviours.

Interface Segregation Principle speaks to the idea that interfaces should be separated into cohesive sets such that you don't require an interface that does many disparate things when you only want one facility. Think again of the interface of an electrical socket, it could have a thermostat also, but it would make it harder to install an electrical socket and may make it harder to use for non-heating purposes. Like an electrical socket with a thermostat, large interfaces are hard to implement and hard to use.

The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.[1] ISP splits interfaces which are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them.


问:
Do we need to create local branches for the enhancements we are working on?
We just started implementing the Git source control for our project and the Admin says we should not be creating any new branches for the enhancements that we are working on instead everybody should pull remote master branch into their machine and make changes and push the commits to remote master branch.

I somehow feel this process is wrong and I strongly feel that we should be creating new branch for the each enhancement that we are working on and merge the respective branches into master branch. Something similar to this

I need expert advice on this and which approach do you guys suggest from your past experience.

答: Maybe the admin is simply trying to get you on board with a continuous integration development strategy, to avoid the integration hell usually associated with multiple development branches. </p>


答:
You could always just implement and return a benign value or default value.  After all it's just a property.  It could return 0 (the default property of int), or whatever value makes sense in your implementation (int.MinValue, int.MaxValue, 1, 42, etc...)

```<code>//We don't officially implement this property
int IFoo.Bar
{
     { get; }
}
</code>```

Throwing an exception seems like bad form.

Body:
You could always just implement and return a benign value or default value.  After all it's just a property.  It could return 0 (the default property of int), or whatever value makes sense in your implementation (int.MinValue, int.MaxValue, 1, 42, etc...)

//We don't officially implement this property
int IFoo.Bar
{
     { get; }
}

Throwing an exception seems like bad form.


答:
Your error is logging an exception where you cannot handle it, and thus cannot know whether logging is any part of properly handling it.

There are very few cases where you can or must handle part of the error, which might include logging, but must still signal the error to the caller. Examples are uncorrectable read-errors and the like, if you do the lowest-level reading, but they generally have in common that the info communicated to the caller is severely filtered, for security and usability.

The only thing you can do in your case, and for some reason have to do, is translating the exception the implementation throws into one the caller expects, chaining the original for context, and leaving anything else well alone.

To sum it up, your code arrogated right and duty for partial handling of the exception, thus violating the SRP.

DRY doesn't come into it.

Title: Should I log errors on exception throwing constructors?

Body:
I was building an application for a few months and I come to realize a pattern that emerged:

```<code>logger.error(ERROR_MSG);
throw new Exception(ERROR_MSG);
</code>```

Or, when catching:

```<code>try {
    // ...block that can throw something
} catch (Exception e) {
    logger.error(ERROR_MSG, e);
    throw new MyException(ERROR_MSG, e);
}
</code>```

So, whenever I was throwing or catching an exception, I would log it. In fact, that was almost all logging I did on the application (besides something for application initialization).

So, as a programmer, I shun repetition; So I decided to move the logger calls to the exception construction, so, whenever I was building an exception, things would be logged. I could also, certainly, create a ExceptionHelper that throwed the exception for me, but that would make my code harder to interpret and, even worse, the compiler wouldn't deal well with it, failing to realize that a call to that member would throw immediately.

So, is this an anti-pattern? If so, why?


问:
Why is JSX good, when JSP scriptlets are bad?
React.js provides JSX as an XHTML-like syntax for constructing a tree of components and elements.  JSX compiles to Javascript, and instead of providing loops or conditionals in JSX proper, you use Javascript directly:

```<code><ul>
  {list.map((item) =>
    <li>{item}</li>
  )}
</ul>
</code>```

What I haven't been able to explain yet is, why is this considered good if analogous constructs are considered bad in JSP?

Something like this in JSP

```<code><ul>
   <% for (item in list) { %>
     <li>${item}</li>
   <% } %>
</ul>
</code>```

is considered a readability problem to be solved with tags like <c:forEach>.  The reasoning behind JSTL tags also seem like they could apply to JSX:

it's a little easier to read when you aren't toggling between XHTML-like syntax (angle brackets, nesting) and Java/Javascript (curlies, commas, parens)

when you have the full language and platform available for use inside the rendering function, there's less to discourage you from putting logic in that doesn't belong there.

The only reasons I can think of why JSX is different is:

in Java, you had an incentive to do the wrong thing - JSP would be hot-reloaded, so it was tempting to put code in JSPs to avoid a rebuild/restart cycle.  Maintainability was sacrificed for immediate productivity. Banishing scriptlets and limiting to a fixed set of template constructs was effectively a way of enforcing maintainability.  No such distortion exists in the JS world.

JSP and Java syntax is clunky with the extra <% ... %> to distinguish Java code from element generation, and with Java's native syntax lacking a foreach concept or first-class functions (until recently). The syntax penalty of using native Javascript for loops and conditionals in JSX is non-zero (in my opinion) but not as bad as JSP, and arguably not bad enough to warrant introducing JSX-specific elements for loops and conditionals.

Is there something else I'm missing?

答:
Primarily, the people who created JSX disagreed with the people who disliked JSP. See their discussion here: Why did we build React? as well as Displaying Data

Templates is based on the idea of creating a division between the logic and presentation of a page. On this theory your javascript (or java) code shouldn't be concerned with what markup gets displayed, and your markup shouldn't be concerned with any of the logic involved. This division is essentially why people criticize the various template languages that readily allowed mixing code in with your template (PHP/JSP/ASP).

React is based on components. The authors of react argue that the logic and presentation of a component are tightly connected, and attempting to divide them doesn't make any sense. Instead, a page should be broken by logical pieces. So you might break out the header bar, comments, post, related questions, etc into seperate components. But it doesn't make sense to try and divide the logic for the related questions from the presentation.

The primary difference between something like JSX and something like JSP is that JSP is a template language that includes a bit of java for the logic. JSX is javascript with a syntax extension to make it easy to construct fragments of html. The emphasis is different. Since JSX embraces this approach, it ends up producing a nicer, cleaner approach then done by JSP or friends.

But ultimately, it comes down to the fact that the people who made react didn't like templates. They think they are a bad idea, and that you should put your markup and presentation logic in the same place.


问:
Mapping Domain models to ViewModel
I have an Asp.net MVC5 application structured like this:

Core

Domain project

Infrastructure

DAL project

Utilities

UI

UI project (contains ViewModel at the moment, will probably put that
into separate project as I expect that application will grow through
time)

It works through Unit of work and a generic repository, injected with Unity.

My question is:

I'm strictly trying to use ViewModels for my UI Views, where should I put the logic to map Domain Model <=> ViewModel?

Should I do it in the Controller or perhaps put the mapping logic into the ViewModel itself and create methods ViewModel.FromDomainObject(DomainObject domainObject) or ViewModel.ToDomainObject(ViewModel viewModel) etc.?

答:
Keep mapping implementation out of your controllers. Instead, call the thing responsible for mapping in your controller.

```<code>public ActionResult FetchSomething()
{
    var thingMapper = new ThingMapper();
    var viewModel = thingMapper.ToViewModel(service.FetchSomething());
    return View(viewModel);
}
</code>```

Of course, if your ViewModel is just a property or two, you can skip the mapper.

```<code>public ActionResult FetchSomething()
{
    var thing = service.FetchSomething();
    var viewModel = new ThingViewModel { Prop1 = thing.Prop1 };
    return View(viewModel);
}
</code>```

With a little luck, AutoMapper might help you map objects without writing custom mappers.

I wouldn't store mapping implementation in the ViewModels themselves. This gets awkward when one ViewModel can represent data from more than one source. It also mixes responsibilities a little too much for my tastes.

Title: Mapping Domain models to ViewModel

Body:
Keep mapping implementation out of your controllers. Instead, call the thing responsible for mapping in your controller.

public ActionResult FetchSomething()
{
    var thingMapper = new ThingMapper();
    var viewModel = thingMapper.ToViewModel(service.FetchSomething());
    return View(viewModel);
}

Of course, if your ViewModel is just a property or two, you can skip the mapper.

public ActionResult FetchSomething()
{
    var thing = service.FetchSomething();
    var viewModel = new ThingViewModel { Prop1 = thing.Prop1 };
    return View(viewModel);
}

With a little luck, AutoMapper might help you map objects without writing custom mappers.

I wouldn't store mapping implementation in the ViewModels themselves. This gets awkward when one ViewModel can represent data from more than one source. It also mixes responsibilities a little too much for my tastes.


答:
It's turtles all the way down.

Nothing is certain. You have no choice but to settle on confidence ratings.

You can think of it as a stack:
Math > Physics > Hardware > Firmware > Operating System > Assembler/Compiler/etc

At each level you have tests that you can perform to improve your confidence ratings. Some of these tests have the quality of formal proofs, some of them are based on observation, most are a combination of both.

The tricky part is unravelling the recursion in some of these tests because we use programs to do proofs and observational analysis now where it has become too difficult to do that by hand.

Ultimately though the answer is that you try everything you can think of. Static analysis, fuzzing, simulation, running with purposefully selected extreme inputs or random inputs, running/mapping every control path, formal proofs, etc. Basically your aim in testing should always be to do everything possible to prove that your product (e.g. theory/chip/program) doesn't work as intended. If you make a genuine effort and still fail then you're allowed to improve your confidence rating in your product's correctness.

Testing is at best a semidecision process meaning that given there's a bug you will eventually find it but you can never be sure that you've found them all. Even with formally verified software you're still relying on physics, the tools used to do the formal proofs, and that the thing you proved is necessary and sufficient for your program to do what is (often subjectively) "intended". That's not to mention all the other components you're using that don't have formal proofs.


答:
Flawless? They're not. I recently installed some "updates", and it was months (and several reprogrammed sections of code) later before my ASP.NET site was working properly again, due to unexplained changes in how various basic things worked or failed.

However, they are tested and then used by many very smart detail-oriented people, who tend to notice and report and fix most things. Stack Exchange is a great example (and improvement on) how all the people using those tools help test and analyze how these amazingly complex and low-level tools work, at least as far as as practical use goes.

But flawless, no. Although you can also see people on Stack Exchange gaining impressive insight into performance details and standards compliance and quirks, there are always flaws and imperfections, especially when different people have different opinions of what a flaw is.


答:
I have come across this situation. In fact as pointed out elsewhere the BCL has such instances... I'll try to provide better examples and provide some rationale:

When you have an already shipped interface that you keep for compatibility reasons and...

The interface contains members that are obsolete or discoraged. For instance BlockingCollection<T>.ICollection.SyncRoot (among others) while ICollection.SyncRoot is not obsolete per se, it will throw NotSupportedException.

The interface contains members that are documented to be optional, and that the implementation may throw the exception. For instance on MSDN regarding IEnumerator.Reset it says:

The Reset method is provided for COM interoperability. It does not
  necessarily need to be implemented; instead, the implementer can
  simply throw a NotSupportedException.

By a mistake of the design of the interface, it should have been more than one interface in the first place. It is a common pattern in BCL to implement Read Only versions of containers with NotSupportedException. I have done it myself, it is what is expected now... I make ICollection<T>.IsReadOnly return true so you can tell them appart. The correct design would have been to have a Readable version of the interface, and then the full interface inherits from that.

There is no better interface to use. For instance, I have a class that allows you access items by index, check if it contains an item and on what index, it has some size, you can copy it to an array... it seems a job for IList<T> but my class has a fixed size, and doens't support adding nor removing, so it works more like an array than a list. But there is no IArray<T> in the BCL.

The interface belongs to an API that is ported to multiple platforms, and in the implementation of a particular platform some parts of it are not supported. Ideally there would be some way to detect it, so that portable code that uses such API can decide whatever or not to call those parts... but if you call them, it is totally appropriate to get NotSupportedException. This is particularly true, if this is a port to a new platform that wasn't foreseen in the original design.

Also consider why is it not supported?

Sometimes InvalidOperationException is a better option. For instance one more way to add polymorphism in a class is by having various implementation of an internal interface and your code is choosing which one to instantiate depending on the parameters given in the constructor of the class. [This is particulary useful if you know that the set of options is fixed and you don't want to allow third party classes to be introduced by dependency injection.] I have done this to backport ThreadLocal because the tracking and non-tracking implementation are too far appart, and what does ThreadLocal.Values throw on the non-tracking implementation? InvalidOperationException even tho, it doesn't depend on the state of the object. In this case I introduced the class myself, and I knew that this method had to be implemented by just throwing an exception.

Sometimes a default value makes sense. For instance on the ICollection<T>.IsReadOnly mentioned above, it makes sense to just return ´true´ or ´false´ depending the case. So... what is the semantics of IFoo.Bar? there maybe some sensible default value to return.

Addendum: if you are in control of the interface (and you don't need to stay with it for compatibility) there shouldn't be a case where you have to throw NotSupportedException. Although, you may have to split the interface into two or more smaller interfaces to have the right fit for your case, which may lead to "pollution" in the extreme situations.


问:
How can I create a client for a service without hiding the parameters needed for each endpoint?
I'm creating a client to a third-party soap web service in my application. Here is the way I'm thinking of doing it:

Create a ClientFactory that makes a client based on the wsdl file, and sets needed options on it, then returns it.

Have several Request objects, preferably implementing the Request interface, that take the Client as their constructor argument, and then make requests to the web service through that client.

Here is a short example to illustrate my point.

```<code>class ClientFactory
{

    public function create()
    {
        return new \SoapClient('http://www.example.com/example.wsdl', [
            'trace' => true
        ]);
    }

}

class LockSeatRequest implements RequestInterface
{

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function execute($id, $count, $date)
    {
        $result = $this->client->lockSeat($id, $count, $date);

        // Make some changes to $result here...

        return $result;
    }

}

interface Request
{

    // what should I put in here?

}
</code>```

Client code example:

```<code>$client = $clientFactory->create();
$lockSeatRequest = new lockSeatRequest($client);
$lockSeatRequest->execute(1, 5, '2015-04-04');
</code>```

My problem here is that the number of arguments, and the type of arguments, are different from request to request, and this makes it impossible to define an interface. The way I have seen it done in other PHP libraries is to accept an array of parameters, but my issue with that approach is that it makes the user have to look up the parameters for each function call instead of making it explicit. Also, I would then have to add cruft such as checking whether the right keys are defined in the array, to each Request, instead of having the language ensure each parameter with the right type is passed to the function.

How can I have multiple methods, each of them requiring a different number of arguments, but still have them implement a particular interface?

Or, am I seeing this totally wrong?

答:
I would consider moving the params to the __construct() so each request will do only one thing.

I would also consider decoule the params out using valueobject.

Something like this:

```<code>class LockSeatRequest implements RequestInterface
{

    public function __construct(Client $client, LockSeatRequestValueObject $params)
    {
        $this->client = $client;
        $this->params = $params;
    }

    public function execute()
    {
        $result = $this->client->lockSeat($this->params->getId(), $this->params->getCount(), $this->params->getDate());

        // Make some changes to $result here...

        return $result;
    }

}

interface Request
{

    public function execute();
}

class LockSeatRequestValueObject
{
    private $id;
    ....

    public function __construct ($id, $count, $date)
    // or in php7
    // public function __construct (int $id, int $count, \DateTime $date)
    {
        $this->id = $id;
        $this->validate(); // Might be redundant in php7
    }

    public function getId()
    {
        return $this->id;
    }
    ......
}
</code>```

Body:
I would consider moving the params to the __construct() so each request will do only one thing.

I would also consider decoule the params out using valueobject.

Something like this:

class LockSeatRequest implements RequestInterface
{

    public function __construct(Client $client, LockSeatRequestValueObject $params)
    {
        $this->client = $client;
        $this->params = $params;
    }

    public function execute()
    {
        $result = $this->client->lockSeat($this->params->getId(), $this->params->getCount(), $this->params->getDate());

        // Make some changes to $result here...

        return $result;
    }

}

interface Request
{

    public function execute();
}

class LockSeatRequestValueObject
{
    private $id;
    ....

    public function __construct ($id, $count, $date)
    // or in php7
    // public function __construct (int $id, int $count, \DateTime $date)
    {
        $this->id = $id;
        $this->validate(); // Might be redundant in php7
    }

    public function getId()
    {
        return $this->id;
    }
    ......
}


答:
As a compiler writer for a math language*, from my experience I can say in theory you cannot. And some of the bugs just give wrong results like (from my shame list) calculating 6/3*2 from the right 6/(3*2) and outputting 1 without crashing or giving nonsensical compile errors.

But IMHO many compilers do not have as many bugs as other software because:

Writing unit tests is easy. Each statement is a unit and you can write tests as simple as: test_unit("2+(-2)*(-2+1)*3+1",9);

A program is a combination of statements and for any program to output the correct result each individual statement must give the correct result (mostly). So it is very unlikely to have any bugs while the program gives the correct result.

As the size and number of written programs increase the likelihood of catching bugs dramatically increases.

For assemblers, machine instructions etc, the above also hold; on the other hand verification and validation in chip design and production have a lot more strict processes since it is a huge business: Electronic design automation .

Before going to production each CPU should be tested rigorously because each bug costs nearly a couple of million dollars: there are huge non-recurring production costs in chip production. So companies spend a lot of money and write a lot of simulation code for their design before going production, although this does not give a 100% guarantee - for example: the Pentium FDIV bug.

In short it is very unlikely to have serious bugs in compilers, machine codes etc.

My humble math language *


答:
I think an interesting point here is that the vast majority of commercial software (and indeed open source software) licences specifically specify that you cannot trust the software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

From Microsoft Word Licence agreement

.  Except for the Limited Warranty and to the maximum extent permitted by applicable law, Microsoft and its suppliers provide the Software and support services (if any) AS IS AND WITH ALL FAULTS, and hereby disclaim all other warranties and conditions, whether express, implied or statutory, including, but not limited to, any (if any) implied warranties, duties or conditions of merchantability, of fitness for a particular purpose, of reliability or availability, of accuracy or completeness of responses, of results, of workmanlike effort, of lack of viruses, and of lack of negligence, all with regard to the Software, and the provision of or failure to provide support or other services, information, software, and related content through the Software or otherwise arising out of the use of the Software.

In essence this sentence in the licence  in almost every piece of software that you use specically tells you that you cannot trust the software let alone the compiler used.

Software is like a scientific theory, it is deemed to work as specified until it doesnt.


问:
Do special-cases with fallbacks violate the Liskov Substitution Principle?
Let's say I have an interface FooInterface that has the following signature:

```<code>interface FooInterface {
    public function doSomething(SomethingInterface something);
}
</code>```

And a concrete class ConcreteFoo that implements that interface:

```<code>class ConcreteFoo implements FooInterface {

    public function doSomething(SomethingInterface something) {
    }

}
</code>```

I'd like to ConcreteFoo::doSomething() to do something unique if it's passed a special type of SomethingInterface object (let's say it's called SpecialSomething).

It's definitely a LSP violation if I strengthen the preconditions of the method or throw a new exception, but would it still be an LSP violation if I special-cased SpecialSomething objects while providing a fallback for generic SomethingInterface objects? Something like:

```<code>class ConcreteFoo implements FooInterface {

    public function doSomething(SomethingInterface something) {
        if (something instanceof SpecialSomething) {
            // Do SpecialSomething magic
        }
        else {
            // Do generic SomethingInterface magic
        }
    }

}
</code>```

答:
It's not a violation of the LSP. However, it's still a violation of the "don't do type checks" rule. It would be better to design the code in such a way that the special arises naturally; maybe SomethingInterface needs another member that could accomplish this, or maybe you need to inject an abstract factory somewhere.

However, this isn't a hard and fast rule, so you need to decide whether the trade-off is worth it. Right now you have a code smell, and a possible obstacle to future enhancements. Getting rid of it might mean a considerably more convoluted architecture. Without more information I can't tell which one is better.


问:
Should I treat additional linter restrictions as breaking backwards compatibility?
I'm maintaing a linter library, so this it's basically a set of rules checked against some code one can pass to it. Say, we have rule A which checks some set of cases.

Now imagine that some commit extends this set - by extend I mean that the cardinality of set is bigger but non of "old" members is gone, we've just added some new members.

Regarding the semantic versioning approach, how should I increase minor or major version? The question boils down to should I consider changes of this kind as backwards compatible?

答:
Because it's normal to use linters as part of continuous integration checks, I would say it's correct to think of adding new enabled-by-default linter rules as a potentially breaking change.

Whether it actually is a breaking change depends on how you expect your linter to be used. Or in semver terms, what you defined as your "public API".

If your linter is meant to be used with a config file that enumerates every single rule that should be enabled, then it's reasonable to say that the behavior without a config file has no backwards compatibility guarantees and you can do whatever you want even in patch and minor versions.

If your linter is meant to be used with a config file that enables and disables rules, but does not enumerate the complete set of enabled rules, then any new rules you add in a patch or minor version should be disabled by default.

If your linter has no config file at all and can only be configured via comments in the source code, then any new rules you add in a patch or minor version definitely have to be disabled by default.

For example, one of the linters my team uses at work in our CI setup is JSCS (which fits under the second bullet point), and based on their changelog, they're cool with adding new rules in minor versions, but those new rules are disabled by default (especially since some of them are specific to ES6). They also change their "presets" in minor versions, which are essentially alternative sets of defaults. Since you have to go out of your way to enable a preset, and they'd be a pretty useless feature if they could never ever change once added, it's reasonable to not provide any backwards compatibility guarantee for them.


答:
It might be a violation of LSP depending on what else is in the contract for the doSomething method. But it's almost certainly a code smell even if it doesn't violate LSP.

For example, if part of the contract of doSomething is that it will call something.commitUpdates() at least once before returning, and for the special case it calls commitSpecialUpdates() instead, then that is a violation of LSP. Even if SpecialSomething's commitSpecialUpdates() method was consciously designed to do all of the same stuff as commitUpdates(), that's just preemptively hacking around the LSP violation, and is exactly the sort of hackery one would not have to do if one followed LSP consistently. Whether anything like this applies to your case is something you'll have to figure out by checking your contract for that method (whether explicit or implicit).

The reason this is a code smell is because checking the concrete type of one of your arguments misses the point of defining an interface/abstract type for it in the first place, and because in principle you can no longer guarantee the method even works (imagine if someone writes a subclass of SpecialSomething with the assumption that commitUpdates() will get called). First of all, try to make these special updates work within the existing SomethingInterface; that's the best possible outcome. If you're really sure you can't do that, then you need to update the interface. If you don't control the interface, then you may need to consider writing your own interface that does do what you want. If you can't even come up with an interface that works for all of them, maybe you should scrap the interface entirely and have multiple methods taking different concrete types, or maybe an even bigger refactor is in order. We'd have to know more about the magic you've commented out to tell which of these is appropriate.

Title: Do special-cases with fallbacks violate the Liskov Substitution Principle?

Body:
Let's say I have an interface FooInterface that has the following signature:

```<code>interface FooInterface {
    public function doSomething(SomethingInterface something);
}
</code>```

And a concrete class ConcreteFoo that implements that interface:

```<code>class ConcreteFoo implements FooInterface {

    public function doSomething(SomethingInterface something) {
    }

}
</code>```

I'd like to ConcreteFoo::doSomething() to do something unique if it's passed a special type of SomethingInterface object (let's say it's called SpecialSomething).

It's definitely a LSP violation if I strengthen the preconditions of the method or throw a new exception, but would it still be an LSP violation if I special-cased SpecialSomething objects while providing a fallback for generic SomethingInterface objects? Something like:

```<code>class ConcreteFoo implements FooInterface {

    public function doSomething(SomethingInterface something) {
        if (something instanceof SpecialSomething) {
            // Do SpecialSomething magic
        }
        else {
            // Do generic SomethingInterface magic
        }
    }

}
</code>```


问:
How to determine when to open a new branch or a new repository when using Git?
Currently I am working on a project to make a product for company X. The team I am working with is selling similar service to many company with similar product, where 40% of the code is reused and 60% customized feature made to particular company. Previously there were no version control until I suggest using git recently. We are happy that we don't need to copy and paste each other's work repeatedly after introducing Git, but now we are a bit confused that should the new project be open as a new branch of previous product's repository (i.e. one repository for all products to different company) or as a new stand alone repository (i.e. one repository for different products)

Normally we are not merging the products of different companies, but sometimes when we find some good and commonly-wanted features, we would like to add those features to all the products of different company as a gift(once or twice per year). In this case, will it be better to open a new repository or just start a new branch?

答:
It's actually encouraged to create a branch anytime you want. Here're some tips might be helpful:

when you're experimenting an new idea on the codebase

when you're trying to fix a bug

when you're trying to refactored your code

when you're merging with an external branch

when solving conflicts

your'e making a new release

you just want to make a save-point for the current stage

There might be a long list. You can maintain a list of TOPIC branch for your group.


问:
How to choose python module license as python itself
I would like to publish a python module and would like to publish it as the same license of python

Below is a example of how Perl module does:

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

in Python 2.7 license:

(1) GPL-compatible doesn't mean that we're distributing Python under
          the GPL.  All Python licenses, unlike the GPL, let you distribute
          a modified version without making your changes open source.  The
          GPL-compatible licenses make it possible to combine Python with
          other software that is released under the GPL; the others don't.

So if I use GPL as my modules license, shall I also need to hightlight: let you distribute a modified version without making your changes open source.

答:
What you highlighted out of the Python license documentation is an informal footnote and not actually part of the license itself.

What the footnote says is that it is possible to combine Python and 3rd-party, GPL-licensed, libraries in one product, but that the Python license also allows you to make closed-source modifications to Python itself. The latter is not possible under the GPL license.

If you choose to use the GPL license for your modules, then by that choice you are forbidding other from making closed-source derivatives of your module.


问:
Why are the smart folks who write and adopt react.js okay with the way markup is tightly-coupled/buried inside Javascript?
Quite a while ago there was a concerted trend in the industry to move towards adopting templating to separate markup from logic, or something like that. The result was much more pleasing to the eye and I would argue much easier to develop and debug.

I had no idea what to expect this weekend when I started examining react.js. I had heard it was a "functional reactive" take on web applications and that sounded good to me. I was very surprised by just how different it was than, say, Angular or Backbone or really every other library out there.

It is plainly obvious that the creators of react.js chose to buck the trend of templating and return to the ASP/PHP pattern of writing markup in code. This was a huge surprise to me because it is not as though they found a way to do so that is significantly less ugly than what we had before - they offer React.createElement and React.DOM but it is still what it is.

This means that it would be radically harder to port an existing, say, Angular application with a large custom stylesheet over to react.js in a manner consistent with their philosophy.

I'm having trouble though understanding what that philosophy is, or in other words, why on earth they made this decision. Obviously, they know what they are doing, and I do not, so please enlighten me...

答:
I am also MVC grown. I believe we'll need to dive into FLUX to understand full picture.

My understanding is that as HTML templating moved to browser (with Backbone or Angular frameworks), this single page application can provide much better interactive experience to user than traditional web app with server side tamplating. For example you application can hold the state of application and base on some user action update various HTML elements instantly without roundtrip to server.

But handling state turned to be complicated with Backbone or Angular 1.x (not sure how Angular 2 handles it so far), because MVC or MVx patterns couple data model with view via controller or directly. But what if you want to react in other views on state change of the this model? Angular 1 provides some features for handling this, but you can easily shoot yourself into foot with nested controllers or nested scoping.

So FLUX movement is trying to address this and introduced this unidirectional flow:

----> Dispatcher ----> State Store ------> Component(View) -----> Dispatcher

Component or various components are subscribed to certain model state changes and sends user actions to Dispatcher. Dispatcher based on these actions updates model (State store), which can again trigger one or more View updates. Dispatcher action doesn't have to be triggered from component only. It can be done from server also.
This way sharing the state(models) between views is much easier.

Now, React.JS is component from above diagram. Fundamental part of is that it doesn't mutate DOM directly, but uses shadow DOM concept, where it gathers differences against previous DOM state and applies only them. So you can re-render a lot or even all of your components, without worrying about performance mostly.

Consequence of all this is that React component have these concerns:

Needs to use Shadow DOM to mutate HTML

Needs to subscribe to model (State Store) changes

Needs to dispatch actions against State Store

If you mix all these concerns into single component, you get JavaScript buried inside template as you discribed. I was also horrified about this when I started looking into these areas of UI development.

React ecosystem is evolving rapidly and there are attempts to enhance this. For example look how Dan Abramov (creator one of the hottest State Store libary called Redux) separates these concerns into so called Presentational and Container component types.

So long story short, it looks as step back at first, but if you dive deeper, you may gain much bigger maintainability benefits in long run in form of true decoupling model from view.

BTW, I recommend to check this video on FLUX vs MVC.


答:
Conceptually, there's not much difference between your choices.  As long as you have a common ancestor, you can fetch branches from two repos and freely merge/diff/whatever between them.

The main difference is in access control.  It's pretty easy to control access at the repo level, and pretty difficult at the branch level.  If you want to give clients access to only their code, you should create their own repo.

Of course, you can do both.  Internally you can have a single branch for each customer, and have a script that pushes just that branch to an external repo the customer can access.

However, keeping a separate branch per customer is not generally the best way to architect your code.  It makes it very difficult to maintain later.  It's usually much more maintainable long term to split your code into reusable common modules that are all in master, then each customer gets a small custom part that pulls in the modules.  Try and put as much code as possible into the common modules.

Title: How to determine when to open a new branch or a new repository when using Git?

Body:
Currently I am working on a project to make a product for company X. The team I am working with is selling similar service to many company with similar product, where 40% of the code is reused and 60% customized feature made to particular company. Previously there were no version control until I suggest using git recently. We are happy that we don't need to copy and paste each other's work repeatedly after introducing Git, but now we are a bit confused that should the new project be open as a new branch of previous product's repository (i.e. one repository for all products to different company) or as a new stand alone repository (i.e. one repository for different products)

Normally we are not merging the products of different companies, but sometimes when we find some good and commonly-wanted features, we would like to add those features to all the products of different company as a gift(once or twice per year). In this case, will it be better to open a new repository or just start a new branch?


问:
Implementing a method that never returns the same data twice
I have a mobile application which retrieves x number of ContentItems from a Web API, however I need a way to only display content that the user hasn't seen before on screen. (Just to be clear, the user only ever see's a single item of content once.)

Imagine the content class to be like this:

```<code>public class ContentItem
{
    public int ID {get; set; }
    public string Foo {get; set; }
}
</code>```

I can think of two ways of implementing this, both with serious drawbacks over the long term:

1. Returning x number of contentItems, then comparing it to an internally stored list of content id's the user has already seen.

Return the newest x ContentItems from the API, then compare these items to an internally stored (Mobile side SQLite DB) list of ID's which represent content items the user has already seen. If the ID of any of the returned items matches an ID stored in the database, then remove it from the ContentItem list.

Note: If the API returns 100 items of content, and the user has seen 3 of them, then I'd just display the 97 new items. This is also true for the inverse, (97 seen, 3 new) as I have a mechanism which detects when the user is running out of content, then runs the 'getContent' method asynchronously.

Drawbacks:

What if the user has seen all off the content returned from the API? The obvious answer here is to re-run the method which collects the data, but this has performance implications. (If its a really heavy user, we could possibly end up running the method several times to get new content.) This also seems a little bit redundant as we have no idea what content we are going to get back.

2. Sending a list of seen content ID's to the server to ensure only new content gets returned

In this method, I'd use the internally stored list of content ID's that the user has seen, and send it to the Web API before sending the getData request. The API would then ensure any data it returns does not match an ID that's in the list of the previously seen content.

Drawbacks

Sending two requests: This would mean I initially have to post the ID of every contentItem the user has ever seen to the API, then create a GET request to actually return new data. (Not sure on how much of a drawback this actually is, but one problem with this method would mean id be unable to asynchronously send the requests - How would I know once the server had finished parsing the id list in order to send the get request for example?)

For really heavy users I may be posting a huge list of ID's (especially after 3 years of using the App for example), this could lead to performance problems.

It's worth noting that I have total control over the API and the App, and that the API only serves the App - There are no other dependencies.

If anyone has any feedback on which method they would go with (or any alternate methods) I'd greatly appreciate it!

答:
Why not consider

3. Send a userID and let the server figure out what to send.

This will optimize network traffic in a big way - you're always sending the server a single piece of information of fixed size, and you're only getting back data that you will actually use.

You have the added benefit that if something happens to the user's device (or they want to view your content on more than one device) you can do the right thing.


答:
If you have full control over the ID generation and the order in which content is presented, then it must be possible to guarantee that if I am looking at the ContentItem with ID 42, then I have already seen the ContentItems with IDs 0 to 41.

In that situation, you can use a simple variant of #2: In the GET request to the server, send the ID of the first unseen item (or the last seen one) and let the server return items from that ID onward.

Title: Implementing a method that never returns the same data twice

Body:
I have a mobile application which retrieves x number of ContentItems from a Web API, however I need a way to only display content that the user hasn't seen before on screen. (Just to be clear, the user only ever see's a single item of content once.)

Imagine the content class to be like this:

```<code>public class ContentItem
{
    public int ID {get; set; }
    public string Foo {get; set; }
}
</code>```

I can think of two ways of implementing this, both with serious drawbacks over the long term:

1. Returning x number of contentItems, then comparing it to an internally stored list of content id's the user has already seen.

Return the newest x ContentItems from the API, then compare these items to an internally stored (Mobile side SQLite DB) list of ID's which represent content items the user has already seen. If the ID of any of the returned items matches an ID stored in the database, then remove it from the ContentItem list.

Note: If the API returns 100 items of content, and the user has seen 3 of them, then I'd just display the 97 new items. This is also true for the inverse, (97 seen, 3 new) as I have a mechanism which detects when the user is running out of content, then runs the 'getContent' method asynchronously.

Drawbacks:

What if the user has seen all off the content returned from the API? The obvious answer here is to re-run the method which collects the data, but this has performance implications. (If its a really heavy user, we could possibly end up running the method several times to get new content.) This also seems a little bit redundant as we have no idea what content we are going to get back.

2. Sending a list of seen content ID's to the server to ensure only new content gets returned

In this method, I'd use the internally stored list of content ID's that the user has seen, and send it to the Web API before sending the getData request. The API would then ensure any data it returns does not match an ID that's in the list of the previously seen content.

Drawbacks

Sending two requests: This would mean I initially have to post the ID of every contentItem the user has ever seen to the API, then create a GET request to actually return new data. (Not sure on how much of a drawback this actually is, but one problem with this method would mean id be unable to asynchronously send the requests - How would I know once the server had finished parsing the id list in order to send the get request for example?)

For really heavy users I may be posting a huge list of ID's (especially after 3 years of using the App for example), this could lead to performance problems.

It's worth noting that I have total control over the API and the App, and that the API only serves the App - There are no other dependencies.

If anyone has any feedback on which method they would go with (or any alternate methods) I'd greatly appreciate it!