0

I have the following line of code:

Dim s As String = _wv.ExecuteJavascriptWithResult("document.links[" & i.ToString() & "].innerHtml;").ToString

Now I have installed DevExpress CodeRush, and it told me I should rather use

Dim s As String = _wv.ExecuteJavascriptWithResult(String.Format("document.links[{0}].innerHTML;", i)).ToString

However, I feel that the String.Format version is less readable than the first line.

Are there any guidelines when to use StringFormat? I would like my code to be professional and easy to read.

Thank you!

tmighty
  • 10,734
  • 21
  • 104
  • 218
  • 1
    String.Format is easier to read in my opinion... here's a great explanation of why. It actually uses a string builder behind which in terms is quicker than concatenation at times... http://stackoverflow.com/questions/4671610/why-use-string-format – Trevor Jun 12 '14 at 11:55
  • 1
    I would suggest that it is not less readable simply less familiar to you. I find the second code snippet more readable. –  Jun 12 '14 at 11:59

2 Answers2

1

I look at that and say that it's unreadable due to so much going on in one line.

I generally prefer string.Format("{0}{1}...", x, y) to any sort of explicit concatenation for two reasons:

  • It makes it easy to identify/define the constant of string. In this case the inner html of some accessed link. (An extension to this is identifying large nested single-double qoute cases)
  • String.Format may implicitly handle conversions, depending on types.

I'd reform your code to multiple lines like so:

Dim jsToExecute as String = String.Format("document.links[{0}].innerHTML;", i)
Dim jsResult = _wv.ExecuteJavascriptWithResult(jsToExecute)
Dim innerHtml as String = jsResult.ToString()
Jono
  • 3,949
  • 4
  • 28
  • 48
0

I agree with Jono's comment that it's too much going on in one line and Gary's comment that it's only less readable because it's less familiar.

So you should familiarize yourself with either method, but I don't think you should let anyone else dictate what you're doing based on a claim of "best practice". Readability is a subjective thing anyway.

My personal rule is to use String.Format when there's 2 or more items. I also make this an extension method on String because that's the way I like it.

Don't accept anyone's "best practice" unless there are very good reasons for you to have to follow their rules.

John Tseng
  • 6,262
  • 2
  • 27
  • 35