#precondition constructor

1 messages · Page 1 of 1 (latest)

long violet
#

is it a common practice to have preconditions in constructors to make sure your object is in a valid state?

terse scarabBOT
#

<@&987246399047479336> please have a look, thanks.

terse scarabBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

long violet
#

i don't see a precondition for non null that often. is there any reason? i see nullable way more often

long violet
# inland hedge wdym

like a you have a class like this. B can be null

public class A {
   private final B;

   public A(B b) {
   
   }
}

terse scarabBOT
inland hedge
mortal rapids
#

its always common practice in ur constructors, setters and all other methods to validate ur arguments

#

dont assume, fail-fast

#

if u have a setAge method, put some code like if (age < 0) throw new IllegalArgumentException("Age must be positive, was :" + age); in it

#

for nullability, there are tools

#

such as @NotNull and @Nullable

#

and also a way to put former per-default implicitly

#

for actual verification, u have Objects.requireNonNull(foo)

#

or just invoking any method on it foo.bar() would trigger an exception immediately as well

#

any "proper real project" would do these checks everywhere

#

otherwise people are just lazy and maybe dont know the benefits of fail-fast

lethal lily
#

💯