官术网_书友最值得收藏!

Rethinking Java development with packages

Think about why we use packages in Java. We could very well write entire Java applications without creating any packages and, thereby, using just the default unnamed package. It would work! However, unless it's a simple or throwaway application, that's not a good idea. The idea of packages is to group your Java types into namespaces that signify the relationship, or perhaps a common theme among those types. It makes code easier to read, understand, and navigate.

The following diagram shows an example of classes organized in packages. Adding all classes to a single package (left) is not good practice. We typically group related classes into well-named packages that describe the nature of the classes in them (right):

There's really no rule about what types belong together in a package. However, it's generally understood that when you create a package and put a bunch of Java types in it, the types are usually related in some way. You could very well write any random set of types in the same package and the compiler wouldn't care. However, anyone else who ends up working on your code could potentially hate you forever, so this is not a wise thing to do! Having related types in common packages also has the benefit of those types being able to access the protected members of each other. This is another level of encapsulation--any protected members or methods are encapsulated within types of a package. (Although, there's an exception to this, as inherited classes are able to access private members across packages.)

So, if the idea of modular programming is to break code and functionality into encapsulated units, there's a sense in which you can do some kind of modular programming in Java well before Java 9.

The following table shows the various ways in which you can encapsulate code in Java before Java 9:

 

Isn't that good enough? Well, not really. The preceding table is where a limitation in the modular ability of the language becomes apparent. Notice the What to encapsulate column. Most of the encapsulation features provided by these modifiers focus on controlling access to member variables and methods. The only way you can really protect access to a type is by making it package-protected. That, unfortunately, ends up making access difficult for even your own library code to access the type, and you are forced to move all the code that accesses that type into the same package. What if you want more?

Why, you ask? There are a couple of problems with approaching modularity with just the preceding paradigm available in Java 8 and earlier. Let me explain both those problems with two stories.

主站蜘蛛池模板: 井研县| 礼泉县| 买车| 托克托县| 古交市| 永泰县| 宁阳县| 东阳市| 方正县| 阿拉善盟| 微山县| 上虞市| 清水河县| 桃园市| 安国市| 台湾省| 澄迈县| 庆元县| 墨玉县| 犍为县| 奉新县| 开江县| 龙岩市| 天津市| 乐业县| 合水县| 涡阳县| 田东县| 黎平县| 石景山区| 磴口县| 南城县| 宁都县| 廉江市| 合阳县| 凉城县| 石景山区| 嫩江县| 自治县| 苗栗县| 咸丰县|