2 ms·
Many functions return foo AND the error. This is occasionally very useful.
by akira2501 5y ago
Many functions return foo AND the error. This is occasionally very useful.
- kadoban 5y agoOcassionally, but pretty rarely in my experience. Both types of functions should exist, it should not be so hard to return an either/or.
- tialaramex 5y agoThat's not an error then, or, that's not what I'd consider a result, or both. Compare Rust's https://doc.rust-lang.org/std/str/fn.from_utf8.html https://doc.rust-lang.org/std/str/fn.from_utf8.html If you've got a buffer full of bytes, which you hope are UTF8 text but maybe aren't, call std::str::from_utf8 and you either get back a string slice with your text in it, or you get a std::str::Utf8Error structure which explains what the problem was in an actionable format. You can write code to process this Utf8Error and your bytes - maybe you're reading blocks of data and it's all valid UTF8 but the last character is continued in the next block for example, you can discern that from Utf8Error and just turn the valid part into UTF8 and keep the rest until the next block is available.
- baby 5y agoNot an error then, it doesn't make semantic sense.
- __s 5y agoWhen it's occasionally useful return (type, err), but generally the two results are distinct so there's no need to return two results in the general case when one suffices Indeed, I recently updated some code to return a relevant value in the error case: https://github.com/wal-g/wal-g/pull/1143/files#diff-d896e5d50cc3693c055fd9a6cfbfaccd1cc82fc3aaea3881c38cf9eb15a63b50R240 https://github.com/wal-g/wal-g/pull/1143/files#diff-d896e5d5... where true means the error is rooted in a corrupted page, & false means that the error isn't due to a corrupted page. It does feel a little dirty & a comment is probably necessary to make this case clear Still, Result can work here. For example, Rust's binary_search https://doc.rust-lang.org/std/vec/struct.Vec.html#method.binary_search https://doc.rust-lang.org/std/vec/struct.Vec.html#method.bin... which returns Ok(idx) when that's the location of the element, or Err(idx) when that's the location the element would be if it were there (this can be a bit annoying when you just want to insert, since you end up writing `let idx = match result { Ok(idx) => idx, Err(idx) => idx }`)
- marcosdumay 5y agoYeah, and without sum types those functions declare the exact same type as the ones that return either one or the other.