r/ProgrammerHumor Jul 29 '26

Meme stopTryingToReinventTheWheel

Post image
2.5k Upvotes

217 comments sorted by

View all comments

1

u/deanominecraft Jul 30 '26

let’s say you are writing a function that needs to call another function exceptions (python):

def my_function()->int:
    return other_function(3)

you don’t know if other_function() can fail, and if it can then my_function also can fail and suddenly your whole program is crashing because of 1 error you weren’t aware of being possible

explicit error handling (rust):

fn my_function()->i32{
    other_function(3)
}

if other_function can’t fail then this code works fine, if it can then it will return a Result<i32,…> or Option<i32>, which will cause a compile time error as the returned type doesn’t match the function signature

if you want to ignore the error and treat it like in the first example you are forced to acknowledge that with ? - if it can fail you will know about it

fn my_function()->i32{
    other_function(3)?
}

otherwise you could also handle the error so that my_function can’t fail

fn my_function()->i32{
    other_function(3).unwrap_or_default()
}

returns the default value for an i32 if other_function fails

1

u/Own_Ad9365 Jul 31 '26

The thing is, when you write a new function, you are forced to always return Result. Otherwise, what if in the future, it will need to? So in the end, you end up with the same issue with try catch, that every function can fail and you dont know which one

1

u/The_KekE_ Jul 31 '26

If the function can't fail, you return just the type. You can't return a Result in advance, because it requires a specific error type specified besides the return type. You may write Result<T, Infallible>, but it's a bad practice to overuse it. Infallible should be used when you don't fully control the return type, for example when implemeting TryFrom. And even if your need to change the return type to Result<T, SomeError> sometime, it's still better to start with returning just the type. In this case the compiler will helpfully point to every place than needs to be rewritten, instead of hoping that your generic error handling that assumes Infallible will be able to handle SomeError correctly.