0

I have a set of validators, which are used for various comparisons, such as if 2 strings are equal or not, If String A contains String B or not, If a list of strings contain substrings or not and so on... For each comparison there exists a separate method.

I need to write a sanitization module, which will clean the strings , i.e. remove special characters, use lucene analysers, etc. before the comparison and then give back the strings.

Is there any way I can directly call the same function for sanitization in all the methods ? What design patterns can be used here?

Explaining the same using an example:

compareStringsContainsSubstring(str1, str2) {
   //sanitizeStrings API should be called here 
   //comparison
}

compareStringsAreEqual(str1, str2) {
   //sanitizeStrings API should be called here 
   //comparison
}

compareListContainsSubstring(ListOfstr, str1) {
   //sanitizeStrings API should be called here 
   //comparison
}

Is there a way to avoid calling it in every method ? All these comparison validators are present in the same class. Can I use some design pattern to solve this?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Mahima
  • 178
  • 8
  • Why don't you sanitize before calling your validators? Other solution would be to create a class for each validator and a base class that handles the sanitization. – TomStroemer May 01 '20 at 18:38
  • There are a lot many classes calling the same validators as well. Instead of changing the upper level, it should be handled in the downstream modules, else anyone adding a new class will always have to add a sanitization call. There are about 20 validators, creating a separate class for each doesn't make sense. – Mahima May 01 '20 at 18:44
  • You can very well create a separate class for each validator. Research about factory pattern. In your case, it is quite difficult to provide a solution without knowing the high-level design of your application. As @TomStroemer suggested why not sanitize before validators are called? – meesun May 01 '20 at 19:27
  • Are there different types of sanitization too?. Does different types of validations have different type of sanitization ? – James May 02 '20 at 05:59
  • Does different types of validations have different type of sanitization ? Based on the argument i.e. List, Map, String. But at the end, it will just sanitizing a string only. – Mahima May 02 '20 at 11:49
  • I found something similar here. I guess it can be used for achieving the above. https://stackoverflow.com/questions/37701020/java-is-it-possible-to-always-execute-a-certain-function-before-other-functions – Mahima May 05 '20 at 18:57

0 Answers0