Extract some duplicated code
Use when instead of if