Skip to content

Instantly share code, notes, and snippets.

@ITR13
Last active February 7, 2025 15:41
Show Gist options
  • Select an option

  • Save ITR13/86dd044e009166223b213a45377b5aff to your computer and use it in GitHub Desktop.

Select an option

Save ITR13/86dd044e009166223b213a45377b5aff to your computer and use it in GitHub Desktop.
Impure vs Pure function example.
class Foo {
private int _someVariable, _someOtherVariable;
void Update() {
DoSomething(); // No way of knowing what this mutates without reading it :(
// The set variables are only used in the same flow
Log(_someVariable, _someOtherVariable);
}
private void Inner() {
if(true) InnerInner();
else {
// Easy to miss that you're resetting variables here,
// what if you're adding another variable later?
_someVariable = 0;
_someOtherVariable = 0;
}
}
private void InnerInner() {
if(true) _someVariable = 1;
else _someVariable = 2;
_someOtherVariable = 3;
}
}
class Bar {
void Update() {
// Nice short, and functional
var (someVariable, someOtherVariable) = DoSomething();
Log(someVariable, someOtherVariable);
}
private (int, int) Inner() {
// A lot less to read
if(true) return InnerInner();
return (0, 0);
}
private (int, int) InnerInner() {
int someVariable;
if(true) someVariable = 1;
else someVariable = 2;
return (someVariable, 3);
}
}
class Baz {
void Update() {
// Works just as well (and can be burst compiled!)
DoSomething(out var someVariable, out var someOtherVariable);
Log(someVariable, someOtherVariable);
}
private void Inner(out int someVariable, out int someOtherVariable) {
if(true) {
InnerInner(out someVariable, out someOtherVariable);
return
};
// Being able to see what's assigned to what is a plus!
someVariable = 0;
someOtherVariable = 0;
}
private (int, int) InnerInner(out int someVariable, out int someOtherVariable) {
if(true) someVariable = 1;
else someVariable = 2;
someOtherVariable = 3;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment