📜 ⬆️ ⬇️

Stretching the OP on the PLO

Some time ago, after returning after a six-month vacation in a functional world, back to the PLO, I once again stepped on the usual rake: I accidentally changed my state.


private double fBm(Vector2D v, int y) { double result = 0f; double freq = Frequency; for (int i = 0; i < Octaves; ++i) { result += NoiseFn(permutation, v * freq) * Amplitude; freq *= Lacunarity; Amplitude *= Gain; // <--  . } return result; } 

In FP, you need to especially try to get such a bug, and in some languages ​​it is impossible in principle. Salad from the useful work and the state of the class is not pleased, the scope for errors even in this four lines is too wide. I began to think how to reduce the area of ​​these rakes and derived the following:


First you need to make this mandatory. Putting the field on the wrong side of the expression is too easy. If I had clearly indicated the context everywhere, most likely I would immediately have noticed that I had stepped. Unfortunately, the C # compiler cannot be forced to require this , and in the studio's static checks there is only a rule that works the other way around, that is, forces you to remove this . So, apparently you have to write your own.


Secondly, it is necessary to exclude the use of class fields from the method body, and to record all changes at the end of the method, if any. We have three paragraphs. In the first we declare everything we need, in the second we do useful work, in the third we save the state.


 public void DoAThing(int input) { //   int a = this.A; int b = this.B; int result = 0; //   for (int i = 0; i < input; ++i) result += (a + b) * i; //   this.Thing = result; } 

In the first paragraph, all the state we need is saved locally.
In the second, this does not appear.
In the third this should always be the first word. Other methods that change state will be called immediately.


return can be added to any place, it will not affect the behavior of the method.


pros



Minuses



 { int a = this.A; int b = this.B; return a + b; } 

Instead of conclusion


What do you think? Does this make sense or am I worried? If you are already doing this or are stretching other parts of the OP to the PLO, please share.


')

Source: https://habr.com/ru/post/318908/


All Articles