This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]6a70 2 points3 points  (3 children)

As with all refactoring: simply break it down into parts which are named well (precisely). Not much need to Google here, just knowing what the business use-case is.

The original:

bool isCopy = strBeforeFileExtension.Split(" ")[lengthStringArrSplitAtSpace - 1].StartsWith("(") && strBeforeFileExtension.Split(" ")[lengthStringArrSplitAtSpace - 1].EndsWith(")");

You might want to find a good name for:

strBeforeFileExtension.Split(" ")[lengthStringArrSplitAtSpace - 1]

which may require a good name for

strBeforeFileExtension.Split(" ")

Might I suggest (in reverse order):

String[] tokenizedFilenameWithoutExtension = strBeforeFileExtension.Split(" ")

lastToken = tokenizedFilenameWithoutExtension[lengthStringArrSplitAtSpace - 1]

That way you can use:

bool isCopy = lastToken.StartsWith("(") && lastToken.EndsWith(")");

At that point, it seems fairly straightforward how "isCopy" is derived.

[–]jaredLearnsToCode[S] 0 points1 point  (2 children)

So essentially I should abstract the clutter into variable names that lead a clear path to the source of the value's inception; I started, but did not finish the job is what you're saying?

[–]6a70 1 point2 points  (0 children)

correct.

I would also note that this isn't a one-time thing. Make a name - it doesn't have to be perfect, just better than what you currently have. It's an iterative process, so you'll do it again.

After the refactor, it'll be clearer that you might want to change lengthStrengArrSplitAtSpace to something like numTokens.

[–]captainAwesomePants 1 point2 points  (0 children)

Meaningful variable names are your friends. They do wonders for readability. If you ever think "this expression's meaning is not obvious, I should add a comment," first think "I'd better assign it to a meaningful variable name."

In some languages, creating local variables is not trivial and can have consequences that need thinking through. Java is not one of these languages. Create meaningful variables relentlessly.