Say I have a method like so:

public boolean extract(String string)
  // return true if string can be extracted, false otherwise

And a caller

if (!StringUtils.isBlank(myString))
boolean isExtracted = extract(myString);
// do something else

Does it make more sense to move checking the string is empty or null inside the method? What is the best practice here?

  • 2
    Always make things easy for the consumer -- if necessary, at the expense of implementation (here of extract). We want our abstractions to be useful as well as simple to use.
    – Erik Eidt
    Jun 14, 2020 at 19:02
  • 1
    Does this answer your question? Best way to handle nulls in Java?
    – gnat
    Jun 14, 2020 at 19:15
  • The bigger question I have is what does the caller do in place of // do something else? Jun 14, 2020 at 20:15
  • What does extract do when presented with a blank string? Does it have generally undesirable behaviour (e.g. crash or null pointer exception) or does the function handle it properly but with a result that is not useful for this particular call site? Jun 15, 2020 at 6:17
  • You have received a number of downvotes likely because your question provides too little background and is asking about best practices. I suggest retracting the question and asking it again with more background as to what you are specifically attempting to achieve. You can see from the answers you have received that people need more information in order to provide you a useful answer.
    – Jason K.
    Jun 17, 2020 at 16:19

1 Answer 1


One of the most useful principles in object oriented programming is the Tell-don’t-Ask principle.

In short it remembers us to tell an object what to do and let the object itself do the validation, instead of asking an object it’s state and have the caller do the validation. The caller shouldn’t have knowledge on the inner workings of the method it calls.

So in your example, the null-check should be handled inside the method, but then the ‘extract’ method itself also seems to violate the Tell-don’t-Ask principle. The method is probably called before another operation on the same object, if so, the extract method can be made private and called from the method that really does the work.

In case the extract method is the method that does the work, it violates the CQS principle, by returning a bool. That principle is really useful too, because we can get a quick idea of what a method does by looking at it’s signature. If it returns something, it’s a query, otherwise a command. The name of your extract method sounds like a command, but the signature looks like a query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.