When exactly does a method have side effects?

梦想与她 提交于 2019-12-04 05:01:00
runako

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.

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).

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".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!