Páginas

Friday, July 23, 2010

Using HERE documents to do repetitive programming

In recent work I had to write Factories for a lot of classes in diferent packages, these factories all had the same general format and so, because it would be really boring to code this by hand, I wrote a little script that takes advantage of HERE documents. There were two types of files, the interfaces and the actual implementations, recognized by having the Impl sufix.

The first thing is to get the paths of the interfaces, we do this with an inverted grep:

for path in $(find . -type f | grep -v Impl)

Then we get the path to directory, excluding the name of the actual file:

factoryPath=${path%/*.java}

After that we get the file name:

javaFile=${path##*/}

and the class name (the name of the file without the .java)

className=${javaFile%.java}

We now have all the basic blocks needed to build our script. From now on it's just a matter of how to combine them. From the class name we get the factory file name:

factoryFile=${className}Factory.java

The package name for the interfaces is the factoryPath variable, but changing the / for .

packageName=$(echo ${factoryPath##./} | tr '/' '.')

and the one for the actual implementation is:

packageImpl=${packageName}.impl

The next step is to create the file we are going to write into:

touch ${factoryPath}/impl/${factoryFile}

And finally let's write the file using the HERE document:

cat >${factoryPath}/impl/${factoryFile} <<HERE
package ${packageImpl};  
  

import ${packageName}.${className};
import tsl.jaxb.${className}XMLImpl;    
  
public class ${className}Factory {
    public static ${className} getInstance(String instance)

    {
        if(instance.equals("XML"))
            return new ${className}XMLImpl();
        if(instance.equals("DER"))

            return new ${className}DERImpl();
  
        return null;
    }
}  

HERE

No comments: