After that I
came up with some solutions so that my code rework can be minimised even if
the token orders are changed. So I did
the following:
1) Add all
the tokens in the List. Let’s say, in the tokenizer parser method, just add all
the token in the List.
2) Do not
write any core logic in the token parser method.
3) Now
create a enum or any such structure which will hold the token position. In my
case I use the enum.
e.g.
public enum ElementPositionEnum
{
ELEMENT_1(0), ELEMENT_2(1), ELEMENT_3(2), ELEMENT_4(3);
private int position;
ElementPositionEnum(int position) {
this.position = position;
}
public int getPosition() {
return this.position;
}
}
4) Now while
creating the object or setting the value to my object, just fetch the elements
from the List based upon the Enum position.
E.g. If I have to fetch the
value, I will do it
like this:
String myVal =
List.get(MyElementPositionEnum.ELEMENT_1.getPosition());
5) So, even
if the tokens sequence is changed, then
we only need to change the enum's value. Rest of the code will be same.
Java Code
for Same :
public class TokenizerParser {
public TokenElementTO
parseToken(String token)
{
List
listOfTOken = new ArrayList();
String[]
tokens = token.split(";");
for(String val : tokens)
{
listOfTOken.add(val);
}
return
createTokenElementObject(listOfTOken);
}
private TokenElementTO
createTokenElementObject(List listOfTOken) {
TokenElementTO
to = new TokenElementTO();
if(listOfTOken.size()
> ElementPositionEnum.ELEMENT_1.getPosition())
to.setElement_1(listOfTOken.getElementPositionEnum.ELEMENT_1.getPosition()));
if(listOfTOken.size()
> ElementPositionEnum.ELEMENT_2.getPosition())
to.setElement_2(listOfTOken.get(ElementPositionEnum.ELEMENT_2.getPosition()));
if(listOfTOken.size()
> ElementPositionEnum.ELEMENT_3.getPosition())
to.setElement_3(listOfTOken.get(ElementPositionEnum.ELEMENT_3.getPosition()));
if(listOfTOken.size()
> ElementPositionEnum.ELEMENT_4.getPosition())
to.setElement_4(listOfTOken.get(ElementPositionEnum.ELEMENT_4.getPosition()));
return to;
}
public static void main(String[] args)
{
TokenizerParser
main = new TokenizerParser();
String
tokens = "AAA;BBB;CCC;DDDD";
main.parseToken(tokens);
}
}
public class TokenElementTO {
private String element_1;
private String element_2;
private String element_3;
private String element_4;
public String
getElement_1() {
return element_1;
}
public void setElement_1(String
element_1) {
this.element_1 = element_1;
}
public String
getElement_2() {
return element_2;
}
public void setElement_2(String
element_2) {
this.element_2 = element_2;
}
public String
getElement_3() {
return element_3;
}
public void setElement_3(String
element_3) {
this.element_3 = element_3;
}
public String
getElement_4() {
return element_4;
}
public void setElement_4(String
element_4) {
this.element_4 = element_4;
}
}