in Java-8, we can have a method, say, for masking a string, in multiple ways :
Interface Implementation
public interface StringUtil {
static String maskString(String strText, int start, int end, char maskChar)
throws Exception{
if( Strings.isNullOrEmpty(strText))
return "";
if(start < 0)
start = 0;
if( end > strText.length() )
end = strText.length();
if(start > end)
throw new Exception("End index cannot be greater than start index");
int maskLength = end - start;
if(maskLength == 0)
return strText;
StringBuilder sbMaskString = new StringBuilder(maskLength);
for(int i = 0; i < maskLength; i++){
sbMaskString.append(maskChar);
}
return strText.substring(0, start)
+ sbMaskString.toString()
+ strText.substring(start + maskLength);
}
}
this can be accessed via:
StringUtil.maskString("52418100", 2, 4, 'x')
Now same can be implemented via classes as below
public class StringUtil {
public String maskString(String strText, int start, int end, char maskChar)
throws Exception{
if( Strings.isNullOrEmpty(strText))
return "";
if(start < 0)
start = 0;
if( end > strText.length() )
end = strText.length();
if(start > end)
throw new Exception("End index cannot be greater than start index");
int maskLength = end - start;
if(maskLength == 0)
return strText;
StringBuilder sbMaskString = new StringBuilder(maskLength);
for(int i = 0; i < maskLength; i++){
sbMaskString.append(maskChar);
}
return strText.substring(0, start)
+ sbMaskString.toString()
+ strText.substring(start + maskLength);
}
}
this can be accessed as :
StringUtil su = new StringUtil()
String mask = su.maskString("52418100", 2, 4, 'x')
Question:
Which has to be preferred in which case? So far I understand that interface
function are non-testable via mock
, so I have to have a wrapper function on top of my interface function - in nutshell - its not unit test friendly and also, being static
, you can not override interface methods.
So what other use cases do you consider, if, having an option to write a function?