Extension functions
All big Java projects have utility classes, such as StringUtils
, ListUtils
, and AndroidUtils
. They are so popular because util functions capture common patterns and allow them to be tested and used in a simple way. The problem is that Java really poorly supports the creation and usage of such functions because they have to be implemented as static functions of some class. Let's discuss this problem with an example. Every Java Android developer knows well following code which is used to show Toast
:
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
It is commonly used in Android projects to show errors or short messages, and often it is presented at the beginning of most Android tutorials. Code that implements this functionality is verbose because it uses a static function that is used like a builder. Probably every Java Android developer has forgotten at least once to invoke the show
method on a returned object, which made him check all the surrounding conditions...