I am using contracts in my Java project. (Contract = doing checks at the start and end of methods)
I am wondering if there is a nice way/pattern to write a contract for a generic method. For example:
public abstract class AbstractStringGenerator{
/**
* This method must return a new line as it's last char
* @return string output
*/
public abstract string generateLine(String input);
}
What I want is a nice way to check that the output of generateLine satisfies the contract (in this case, that last char must be a new line char).
I guess I could do this (but I wonder if there is a better way);
public abstract class AbstractStringGenerator{
public string generateLine(String input){
string result = generateLineHook(input);
//do contract checking...
//if new line char is not the last char, then throw contract exception...
return result;
}
/**
* This method must return a new line as it's last char
* @return string output
*/
protected abstract string generateLineHook(String input);
}
Hope this is not too vague. Any help appreciated.
This looks like the place to use the Template Method design pattern. With the template method pattern, the general algorithm can be implemented and finalized in the abstract class, whereas some of the specifics can be implemented in the child classes.
In order to implement the Template method:
The Template method can be implemented in your example as