Minitip #1: Static imports
by
, May 28th, 2011 at 02:18 PM (6635 Views)
So I'm going to try something new here: small, miniature tips which can help people improve their code. The focus will probably be towards the beginner/intermediate level, though there may be a few advanced tips every now and then.
So let's get started!
Static imports allow you to import static members of another class into your class. The main reason for this is to allow you to use those members without the long, drawn-out declaration of where that static member came from.
That's a lot of typing of System which was unnecessary. Let's re-organize the code to use static imports.
A more common use of static imports would be to import constants or common helper functions from a particular class, say from the Math class. Rather than have to go and specify every method or constant you want to import statically, you can use the * notation to import all static members.
In general, you should try to import as few things statically as possible. Static imports can make your code confusing to read if used excessively. PI is a good static import because it generally has a well defined value (3.141592...). Statically importing cos, sin, and tan are also generally ok because it's understood that these are the trigonometric functions cosine, sine, and tangent.
Happy coding