On 12/03/2013 08:32 AM, Herbert Duerr wrote:
On 03.12.2013 13:02, Andre Fischer wrote:
Additionally to this almost correct statement one could mention that
isEmpty() is preferred over getLength()>0 and why.

Yes, it is preferred for checking the emptiness because it directly expresses what it checks.

In general it is a good idea to check for emptiness instead of counting the elements and then comparing against zero. Its the old "interface vs. implementation detail" question. The result will be the same from a mathematical standpoint but the effort to get this result may be different. From an algorithmic complexity standpoint an emptiness check is always equal or better. Maybe a mathematician can provide some insights from the set theory on this question?

By the way: the String class of Java>=6 got its isEmpty() method for the same reasons.

As Herbert said, this directly expresses what it checks. I would add "and it reads better".

There are other reasons, however; for example, depending on the implementation, it may be significantly faster than comparing against the length. For one implementation it may not matter, but, if you change the implementation in the future, it may.

Uniformity is another possible reason (assuming other classes also implement isEmpty()). If you become used to using the expressive form (ie, using isEmpty() rather than comparing size), then you can leave optimizing the call to the class implementer rather than worrying about the correct way to do it. I have seen empty strings checked by comparing the length to zero, and even using a string compare against an empty string.

--
Andrew Pitonyak
My Macro Document: http://www.pitonyak.org/AndrewMacro.odt
Info:  http://www.pitonyak.org/oo.php


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to