Scala Constructor/Method Parameter Checking -
i wanted check best practices of scala programming, since new scala. read online how scala doesn't typically use exceptions except "exceptional" circumstances (which doesn't include parameter checking). right in project using lot of require
, wondering better way of type checking be.
for example, if have class
class foo(string bar){ require(stringutils.isnotempty(bar), "bar can't empty") }
what alternatives checking bar? create companion object so
object foo { def apply(bar: string) = try[foo] { bar match = { case null => failure("can't null") //rest of checks case _ => success[foo] } }
or should use option instead?
in addition, scala methods, how check parameter of method? if return option, return empty option if bad parameter? wouldn't mean have check empty option when use return of method , wouldn't throwing exception allow more specific message? (e.g. runtime exception can't use nulls).
i think success part of companion object return foo() object well?
object foo { def apply(bar: string) = try[foo] { bar match = { case null => failure("can't null") //rest of checks case _ => success[foo](new foo(bar)) } }
to use might success
foo(bar):
val hehe = foo(bar).map(foo => foo.somestring()).getorelse('failed')
the try methods automatically wrap exceptions generated somestring() or whatever else you're doing inside inside failures. if wanted check parameters of foo.somestring()
, you'd similar apply()
method. isn't different throwing exceptions on conditions think it's nicer cause "catch blocks" in recover()
or recoverwith()
. can exit try
using getorelse()
if code wasn't designed chain try
s top bottom.
Comments
Post a Comment