I have a method which returns a string. It can be in normal operating conditions that a blank string or null is returned. However, is it a good coding practise to return null or "" from this method?
Yes, in that situations I prefer returning null to show that string is not found. Empty string has usually used for showing empty result.
Alternative way is to throw some Exception, but as programmer I don't find usable to work with Exceptions. Returning null is much better.
There is a semantic difference between null and the empty string. One says "it is not defined for that input", the other says "the correct value for that input is the empty string".
Imagine you have written a compiler for a subset of C that allows for a main-function that returns nothing. Your compiler returns a string with some fantasy assembly language.
// Testcode 0
void main() {
For this you would return null, the code is not well-formed because of the missing closing brace (no, do not throw an exception, errors in user written code are expected). There is no valid output.
// Testcode 1
void main() { printf("hello!"); }
For this you would return "push 'hello!'\ncall printf"
// Testcode 2
void main() {}
For this you might return "", the code does nothing and returns nothing, but is valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With