Comment on How to properly document code?
aluminium@lemmy.world 11 months ago
For new code I’m writing I’m using mostly JsDoc function headers where on public methods of classes and exported functions. With one or two sentences explaining what function does.
Also try to explain what to expect in edge cases, like when you pass am empty string, null, … stuff of that nature - for which I then create unit tests.
I also always mention if a function is pure or not or if a method changes the state of a class. On a sidenote I find it odd that almost no language has a keyword for pure functions or readonly methods.
TellusChaosovich@lemmy.world 11 months ago
What is a pure function? Never heard that before.
aluminium@lemmy.world 11 months ago
Essentially a function that doesn’t produce side effects, like modifying variables outside of its scope or modifying the function parameters. This something you should always try to incorporate into your code as it makes it much easier to test and makes the function’s use less risky since you don’t relay on external unrelated values.
To give you an example in JavaScript, here are two ways to replace certain numbers from an other list of numbers with the number 0
first a way to do it with a non pure function :
let bannedNumbers = [4,6] const nums = [0,1,2,3,4,5,6,7,8,9]
here the function replaceWithZero does two things that make it impure. First it modifies its parameter. This can lead to issues, for example if you have Second it uses a non-constant variable outside of its scope (bannedNumbers). Which is bad because if somewhere else in the code someone changes bannedNumbers the behavior of the function changes.
A proper pure implementation could look like this :
Here we are not modifying anything outside of the function’s scope or its parameters. This means that no matter where, when and how often we call this function it will always behave the same when given the same inputs! This is the whole goal of pure functions.
Miaou@jlai.lu 11 months ago
I really wouldn’t call anything that hits the network pure, because errors are quite likely. But I guess we all put the bar at a different level, I would not count logging as a side effect yet I’ve been bitten by overly verbose logs in hot loops.
const-ness gives a mini version of purity, although nothing prevents someone from opening
/etc/lol
in a const function… I think GCC has a pure attribute but I don’t think it’s enforced by the compiler, only used for optimizations