Pregunta

in Java/Groovy, afaik, a package has to be defined in the corresponding folder. This results in all class files which are stored in /a/b/c start with the line package a.b.c. Is this still necessary? With regards to convention over configuration, this isn't DRY...

What kind of problems would arise when this package definition would be optional`?

¿Fue útil?

Solución

While it is conventional for the directory structure to match the package structure, and certain problems arise if they don't match, it is in fact not a requirement that they match. This is also true of Java (though a lot of folks don't realize that).

Below is an example which demonstrates this.

groovydemo $ mkdir classes
groovydemo $ 
groovydemo $ cat src/groovy/com/demo/SomeClass.groovy 
package com.somethingotherthandemo

class SomeClass {}
groovydemo $ 
groovydemo $ groovyc -d classes/ src/groovy/com/demo/SomeClass.groovy 
groovydemo $ find classes -type f
classes/com/somethingotherthandemo/SomeClass.class

Otros consejos

The reasons for using packages in Groovy (and Grails) are some of the same reason why they are used in Java.

  1. Packages serve to organize classes into logical namespaces, typically by grouping collaborating classes together.

  2. It helps avoid naming conflicts with other classes (either Java or Groovy).

In any non-trival system where you have hundreds or thousands of classes, packages provide a very useful mechanism for organization and structure.

I think what you're saying is that the package name is implied by the directory the class is in, so why do you need to state it explicity? This is only true in some cases (like Grails) where there's a convention that establishes the root of the source files (e.g. src/groovy).

But imagine I'm writing a Groovy app and have a file at /a/b/c/D.groovy, how can we tell if the root of the source files is /a and thus the package name is b.c or the root of the source files is /a/b and therefore the package name is just c? As far as I can see, we can't, so the package name needs to be stated in the source file explicitly.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top