Is my code too repetitive?… here is a solution to the problem.
Is my code too repetitive?
I
was developing my word adventure game and wondered if there was an easier way to write duplicate code blocks, such as the one I had below.
In this block, the user is presented with N, E, S, W for North, East, South, and West. So I wrote each listener separately and included a try/catch block in each listener. But the whole block of code now does look like a duplicate.
Here is the code block:
btnNorth.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tvIntro.setText("You go north");
String testString = "nothing";
try {
testString = Encounter.EncounterGeneratorText();
} catch (Exception e) {
e.printStackTrace();
}
testString = Encounter.EncounterGeneratorText();
tvIntro.setText(testString);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
TODO Auto-generated catch block
e.printStackTrace();
}
tvIntro.setText(testString);
}
});
btnEast.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tvIntro.setText("You go east");
String testString = "nothing";
try {
testString = Encounter.EncounterGeneratorText();
} catch (Exception e) {
e.printStackTrace();
}
testString = Encounter.EncounterGeneratorText();
tvIntro.setText(testString);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
TODO Auto-generated catch block
e.printStackTrace();
}
tvIntro.setText(testString);
}
});
btnSouth.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tvIntro.setText("You go south");
String testString = "nothing";
try {
testString = Encounter.EncounterGeneratorText();
} catch (Exception e) {
e.printStackTrace();
}
testString = Encounter.EncounterGeneratorText();
tvIntro.setText(testString);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
TODO Auto-generated catch block
e.printStackTrace();
}
tvIntro.setText(testString);
}
});
btnWest.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tvIntro.setText("you go west");
String testString = "nothing";
try {
testString = Encounter.EncounterGeneratorText();
} catch (Exception e) {
e.printStackTrace();
}
testString = Encounter.EncounterGeneratorText();
tvIntro.setText(testString);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
TODO Auto-generated catch block
e.printStackTrace();
}
tvIntro.setText(testString);
};
});
Solution
You can create an OnClickListener that all buttons will use, in which you will detect which button was clicked and perform direction-specific tasks in the switch statement.
Like this:
private OnClickListener DirectionClickListner = new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.north:
Set your strings for North
break;
case R.id.west:
Set your strings for West
break;
case R.id.east:
Set your strings for East
break;
case R.id.south:
Set your strings for South
break;
}
}
};