When exactly does a method have side effects?

2019-04-06 23:31发布

As I always understood it, any change to the programs state (or anything to do with IO) is a side effect. It does not matter, whether the change occurs in a global variable or in a private field of the object the method is called on. It follows that all methods which do not return anything either do nothing at all or have a side effect.
My confusion comes from one of our university's instructors (who is still a student and thus not omniscient yet;) ) telling me setters don't have side effects.

3条回答
你好瞎i
2楼-- · 2019-04-06 23:46

Your instructor is mistaken. With apologies to the SO editors for not pasting the entire article here, this is what Wikipedia has to say:

http://en.wikipedia.org/wiki/Side_effect_(computer_science)

Money Quote #1:

In computer science, a function or expression is said to have a side effect if, in addition to producing a value, it also modifies some state or has an observable interaction with calling functions or the outside world.

Money Quote #2:

In the presence of side effects, a program's behavior depends on past history; that is, the order of evaluation matters.

Non-NOP Setters always satisfy that criteria.

查看更多
不美不萌又怎样
3楼-- · 2019-04-06 23:46

Getters and setters are just syntactic sugar for get_ and set_ methods. They can absolutely have side effects (though it's probably a bad idea to start tweaking lots of fields when all the caller wanted was to increment a counter or something).

查看更多
家丑人穷心不美
4楼-- · 2019-04-06 23:53

First of all: I am aware of the language agnostic tag! "runako" answered the question quite correctly. But often you want to apply your knowledge to the real world so I think I would be nice to also provide an answer that addresses this problem in a more pragmatic way.

When dealing with real world languages like c++,c# or java then even a nop function has actual side effects which can cause code to be executed!

Just think about static-constructors. Even though the specs don't always specify the time a static constructor is ran for a class, most of the time it will be the point in time where a method or member of the class is first accessed.

Example in C#:

class NotSoObvious
{
    static NotSoObvious()
    {
        CauseSomeSideEffects();
    }

    // calling this can cause the constructor to run first!
    public static void DoNothing()
    {
        return;
    }
}

What's more is that even a method that isn't being called at all can cause side effects! Think of reflection (the ability of a program to query information about its own structure). When a method is present but not being called it can still be detected by reflection.

A method with no calls to it surely has a side effect on a program that outputs the number of methods inside!

It all boils down to this: If you want to know about the actual side effects of a method, you first have to determine what you even consider to be a "side effect".

查看更多
登录 后发表回答