+ 2

What is side-effect in programming?

Really hard to understand as a beginner, found this horrible term while learning programming paradigms which is nightmare.

4th Jun 2021, 7:09 PM
Himansh
Himansh - avatar
3 ответов
+ 7
Himansh Reviewing the differences between the Add and Multiply methods below might help. ---- class Foo { public int Sum {get; private set;} void Add(int a, int b) { var result = a + b; Sum = result; //Side effect WriteLine(sum); //Side effect return result; } int Multiply(int a, int b) { return a * b; } } ---- The 2 side effects in the Add method are: 1) Updates state that's reflected and persisted outside the scope of the Add method. 2) Writes to the console. There are no side effects in the Multiply method since the code in that method makes no changes to state outside it's scope. Rather, it returns a value. Here's an example of using these two methods: ---- void Main() { var foo = new Foo(); foo.Add(3, 6); WriteLine(foo.Sum); WriteLine(foo.Multiply(3, 6)); } ---- I hope this makes sense.
5th Jun 2021, 5:48 AM
David Carroll
David Carroll - avatar
+ 5
A side effect could be considered as any modification or change in state of an expression or a function. For example 1) Impure functions in JavaScript - which modifies the value of the parameters before returning. 2) useEffect() hook in React - can be used to perform any asynchronous task during screen loading. It could be anything, from the name do not be misguided as it is not something that is unnecessary or not expected. It could be a very much expected behaviour and could still be called a side-effect.
4th Jun 2021, 8:24 PM
Avinesh
Avinesh - avatar
0
David Carroll Avinesh Thanks for helping;) It depicted this term so well:)
5th Jun 2021, 9:06 AM
Himansh
Himansh - avatar