Hey folks. What is the general consensus on whethe...
# android
h
Hey folks. What is the general consensus on whether property setters in Kotlin for a public API should throw exceptions when given invalid values, or if they should silently handle such cases (e.g., clamping values within a valid range)? For example, an image width property should not be negative.
not kotlin but kotlin colored 1
1
p
I dislike any design based on throwing exceptions. Introduces risk to crash, worsen code readability with try-catches everywhere and repeated exception handling. Expensive to create a stacktrace. Instead, use Result driven design. A result sealed class that could be either a success or an error. Clean, legible, inexpensive. Capping values is ok but it applies in certain cases, the other approach applies everywhere.
j
First, I agree with using Result driven design with Success- or Error-wrappers. Second, I personally don't like changing the input to make it valid, this should be up to the caller. First example that comes to mind is not entirely relevant (security vs UI) bcrypt, where standard implementations cap the input such that only the X first characters is used, causing potential security vulnerabilities. I'll reference this Medium article, inspecting different bcrypt implementations if this is of interest.