I want to get a number from given text (if it exists) which is about work experience in months. I assumed that number is in months when in the text one writes for example "27 miesięcy" or "27 miesiecy" or "27miesięcy" or "27miesiecy, and in years if one writes "3 lat" or "3lat".
Class ExperienceAlg0
is mainly responsible for that. I wanted to make it flexible and open for adding another rules/algorithms "how to find the number of months in the text". I tried to use composite design pattern.
The algorithm works well, but is the design OK according to OOP and Uncle Bob?
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import junit.framework.TestCase;
public class TestExperienceAlg0 extends TestCase {
/*
**
** this test class unit test show how app works
**
*/
@Test
public void testCalc1() {
// Given:
String text = "programuję od 5 lat.";
// When:
List<ExperiencePattern> patternList = new ArrayList<>();
patternList.add(new ExperiencePatternMonths());
patternList.add(new ExperiencePatternYears());
ExperienceAlg0 alg = new ExperienceAlg0(patternList);
int result = alg.calc(text);
// Then:
assertEquals(0, result);
}
}
public interface ExperiencePattern {
public int getPattern(String text);
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExperiencePatternMonths implements ExperiencePattern{
@Override
public int getPattern(String text) {
int result = 0;
Pattern p = Pattern.compile("\\d+miesi[e|ę]cy|\\d+ miesi[e|ę]cy");
Matcher m = p.matcher(text);
while (m.find()) {
String tmp = m.group();
tmp = tmp.replaceAll("\\D", "");
int x = Integer.parseInt(tmp);
if (x < (40 * 12)) { // assuming that the max experience is 40
// years.
result = x;
;
}
}
return result;
}
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExperiencePatternYears implements ExperiencePattern{
@Override
public int getPattern(String text) {
int result = 0;
Pattern p = Pattern.compile("\\d+lat|\\d+ lat");
Matcher m = p.matcher(text);
while (m.find()) {
String tmp = m.group();
tmp = tmp.replaceAll("\\D", "");
int x = Integer.parseInt(tmp);
if (x < 40) { // assuming that the max experience is 40 years.
result = x * 12;
}
}
return result;
}
}
public interface Algorithm <T> {
public T calc(String textToLower);
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ExperienceAlg0 implements Algorithm<Integer> {
List<ExperiencePattern> listPatterns;
public ExperienceAlg0(List<ExperiencePattern> list){
listPatterns = list;
}
@Override
public Integer calc(String text) {
List<Integer> result = new ArrayList<>();
for(ExperiencePattern ep : listPatterns){
result.add(ep.getPattern(text));
}
Collections.sort(result, new DescendingComparator());
return result.get(0);
}
}
import java.util.Comparator;
public class DescendingComparator implements Comparator<Integer>{
@Override
public int compare(Integer x1, Integer x2) {
return x2 - x1;
}
}