3 ms·
I don't think everyone should always use explicit namespaces everywhere. But in this case "Math" isn't even a namespace! It's a class of which cos() is a stati
by marshray 15y ago
I don't think everyone should always use explicit namespaces everywhere.
But in this case "Math" isn't even a namespace! It's a class of which cos() is a static member.
http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#cos%28double%29 http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html...
- pauldino 15y agoThankfully Java 5 added 'import static' which lets you pretend classes are namespaces. http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html http://docs.oracle.com/javase/1.5.0/docs/guide/language/stat...
- marshray 15y agoThanks for that info. Anyone know if C# has something similar? From the linked docs: So when should you use static import? Very sparingly! To me, it sort of confirms the point that these inelegant features are necessary because the language doesn't support fundamental primitives like plain functions and named constants without a superfluous object definition.
- pauldino 15y agoThe CLI itself actually supports unadorned functions, but C# doesn't provide a way of writing them, or using directly them without resorting to reflection. I'm pretty sure C++/CLI lets you use and write standalone functions in managed code, and come to think of it I imagine F# would too. Also it's not an exact equivalent, but C# extension methods can often be used instead of static methods.
- atesti 15y agoYou can mark a class as static, then it will only allow static functions or members: static class Math { static int Pow(int a,int b) {...} }
- sukuriant 15y agoIn a recent article on Hacker News regarding the evils of classes, one of the valid uses of classes were for makeshift namespaces. I would have to agree with this. The model of Java requires all functions to be inside classes. If you have a class full of statics, it functionally becomes a unique namespace. It's semantics, but at that point, they're interchangeable.
- qu4z-2 15y agoExcept that you can't import a class using "using" or "import", so you have to write Math.cos() everywhere. EDIT: I see below that Java has added "import static", but at that point you're in the situation where you have two things that are almost the same but not quite, which is not a particularly clean design in my opinion.
- SeanLuke 15y agoYou are conflating namespaces (a general and abstract concept) with Java packages. While it's true that static methods can have private static (essentially global) data, in in the Java standard libraries static methods largely exist as a mechanism to keep function names from polluting a common global namespace. And Math is a particularly special case of this. Ponder this: have you ever had to say import java.lang.Math ?