Tuesday, February 27, 2007

Pattern Class

Finite Automata ! Remember ! We used to make a lot of Automata at college time. Making Pattern is one of the most tricky jobs and we need to take care of lot of things.Best Part of the whole story is JDK 1.4.2 onwards support Pattern Class and believe me its simply awesome.
So, I decided to make a check for Class name, if a class name starts with Caps its a perfect one else not as per Java coding guideline. So, here is my simple class which I need to check :

class box {
int width = 0;
int height = 0;
}

Now look at the checks (all these are valid )

class Box
class (space) Box
(space) class
Box
public class Box

So, Decided to make a pattern ".*class[ \t\n\f\r]+[A-Z].*" means anything before the String class is fine, there can be space,tab in between class and classname(more than one,so +) , classname should start with a Caps. I am not checking any other character except the first one, with the assumption that file is already a compiled class.

There can be a lot more optimized pattern and more you optimize,more you feel happy :). Here goes my simple,ugly written code that checks the coding standard(only for class name, and that even for one class only :D) box.java file.

See hoe easy to make a option say java -checkstandard which checks for the correct coding guideline in .java file. And if its not according to coding guideline, we can throw the error and why to throw the error, we can replace it with right name(right according to Java Standard). So the code will change

class box {
int width = 0;
int height = 0;
}

into

class Box {
int width = 0;
int height = 0;
}


// Here goes the code //

import java.io.*;
import java.util.regex.*;

class ClassNameChecker {
public static void main(String[] args)
{
String line;
String sub;
try {
BufferedReader in = new BufferedReader(new FileReader(" box.java"));
line = in.readLine();
Pattern p = Pattern.compile(".*class[ \t\n\f\r]+[A-Z].*");
Matcher m = p.matcher(line);
if(m.matches())
{
System.out.println("Class Name follow Java Coding Guidelines");
}
else
{
System.out.println("Not a Java coding Standard");
}
}
catch(Exception e)
{
//something something
}
}
}

No comments: