HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Refactoring String manipulating method with TDD

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
refactoringmanipulatingmethodwithtddstring

Problem

I'd like to refactor my extractSimplePromptName test so it does the same but it's "prettier", hence less code. As far as looking at it, it seems like it could be refactored so it does the same thing, but it's just less code. I'm just fairly new to programming so having a hard time seeing where I should make the changes.

Guessing it has something to do with putting some stuff out of the first if sentence or perhaps just removing something that doesn't do anything.

I just ain't that certain, and I'd really like some help so I can get better at doing decent code.

```
@Test
public void makeSimpleName1() {
String promptNameOrg = "20129142\\1234";

String simplePromptName = extractSimplePromptName(promptNameOrg);
Assert.assertEquals("1234", simplePromptName);
}

@Test
public void makeSimpleName2() {
String promptNameOrg = "80808080\\159;20129142\\1234";

String simplePromptName = extractSimplePromptName(promptNameOrg);
Assert.assertEquals("1234", simplePromptName);
}

@Test
public void makeSimpleName3() {
String promptNameOrg = "159;1234";

String simplePromptName = extractSimplePromptName(promptNameOrg);
Assert.assertEquals("1234", simplePromptName);
}

private String extractSimplePromptName(String promptNameOrg) {
String simplePromptName = "";
if (promptNameOrg != null) {
if (promptNameOrg.contains(";") || promptNameOrg.contains("\\")) {
List splitPrompts = Arrays.asList(promptNameOrg.split(";"));

String promptName = splitPrompts.get(splitPrompts.size() - 1);
if (promptName.contains("\\")) {
String[] split = promptName.split("\\\\");
List splitPromptName = Arrays.asList(split);
simplePromptName = splitPromptName.get(splitPromptName.size() - 1);
} else {
simplePromptName = promptName;
}

} else {
simplePromptName = promptNameOrg;
}

}
return simplePromptNam

Solution

Often, when performing text manipulation, Regular Expressions can do the work for you. Your solution is essentially manually building a text parser and stripper, when a regular expression will do the work in a much more concise way.

The regular expression would be to remove all text up to the last \ or ; character, which would be written as:

private String extractSimplePromptName(String promptNameOrg) {
    return promptNameOrg == null ? "" : promptNameOrg.replaceAll("^.*(\\\\|;)", "");
}

Code Snippets

private String extractSimplePromptName(String promptNameOrg) {
    return promptNameOrg == null ? "" : promptNameOrg.replaceAll("^.*(\\\\|;)", "");
}

Context

StackExchange Code Review Q#61188, answer score: 10

Revisions (0)

No revisions yet.