12

There Currently is a local debate as to which code is more readability

We have one programmer who comes from a c background and when that programmer codes it looks like

string foo = "bar";

if (foo[foo.Length - 1] == 'r')
{

}

We have another programmer that doesn't like this methodology and would rather use

if (foo.EndsWith("r"))
{

}

which way of doing these types of operations is better?

ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
  • Not to be looking for a needle in a haystack, but isn't "legible" the right word, instead of readable or readbly? – mare Apr 06 '10 at 14:50
  • 9
    The first example shouldn't be used at all - even if it was more readable than the second example - since no null or length check is made on foo. – Patrik Svensson Apr 06 '10 at 15:09
  • The second, wouldn't the first one crash if the string was empty? – NibblyPig Apr 06 '10 at 15:19
  • @patrik, @SLC You are correct it will crash with an empty string. This code is ment to illustrate programming styles and not to reflect production code –  Apr 06 '10 at 15:22

19 Answers19

39

EndsWidth is more readable to someone who has never seen C or C++, C#, or any other programming language.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
  • 4
    True, but why would someone who's never seen C, C++, C#, Objective-C, Java, Perl, PHP, or any other C derivative be trying to decipher your code? And remember, anyone who's been coding in Python or VB these days will have seen one of these languages at some point. – Dinah Apr 06 '10 at 15:05
  • 4
    +1 because this ain't C, and I even like C. – Chris Marisic Apr 06 '10 at 15:13
  • @Dinah, consider a person who's done Java but looking at some C#. A string's == is not the same between the two languages. "EndsWith" is less ambiguous. – statenjason Apr 06 '10 at 15:22
  • 1
    @statenjason: fair enough. But I wonder if this fringe case is enough to merit a guideline. For the record, I agree that EndsWith() is more readable and intuitive. I disagree that it should be done for people who have "C or C++, C#, or any other programming language". Even more so because the OP stated that the conflict of opinion is with someone who comes from a C background. Mostly, I like Chris Marisic's above rationale. – Dinah Apr 06 '10 at 15:51
  • 1
    @statenjason: This just shows how unclear that can be, since the example isn't even doing string comparison, it is doing character comparison. – Chris Pitman Apr 06 '10 at 16:04
12

The second one is more declarative in style but I can't tell you objectively if it is more readable sine readability is very subjective. I personally find the second one more readable myself but that is just my opinion.

Here is an excerpt from my article:

Most C# developers are very familiar with writing imperative code (even though they may not know it by that name). In this article, I will introduce you to an alternative style of programming called declarative programming. Proper declarative code is easier to read, understand, and maintain.

As professionals, we should be striving to write better code each day. If you cannot look at code you wrote three months ago with a critical eye and notice things that could be better, then you have not improved and are not challenging yourself. I challenge you to write code that is easier to read and understand by using declarative code.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
9

Number 2 is better to read and to mantain. Example: Verify the last 2 characters ...

Option 1)

if (foo[foo.Length - 1] == 'r' && foo[foo.Length - 2] == 'a')
{

}

Option 2)

if (foo.EndsWith("ar"))
{

}

last 3? last 4?...

Colorator
  • 159
  • 6
8

I come from a C/C++ background and I vote for Endswith!

37Stars
  • 2,489
  • 20
  • 23
7

Readability rules, especially if it implies intent.

With the first example I must discover the intent - which is left for interpretation. If it appears to have a bug, how do I know that's not intentional?

The second example is telling me the intent. We want to find the end character. Armed with that knowledge I can proceed with evaluating the implementation.

Chuck Conway
  • 16,287
  • 11
  • 58
  • 101
3

I think the second way is better because it is more easy to read and because the first one duplicates logic of EndsWith method which is bad practice.

Andrew Bezzub
  • 15,744
  • 7
  • 51
  • 73
3

I think the right answer would be the one that is actually correct. EndsWith properly returns false for empty string input whereas the other test will throw an exception trying to index with -1.

Ron Warholic
  • 9,994
  • 31
  • 47
3

Not only is EndWith more readable, but also more 'correct'. As a rule, if there is a framework method provided to do the job ... use it.

What if foo == string.Empty?

MaLio
  • 2,498
  • 16
  • 23
2

IMO, the intent of the original author is clearer in the second example. In the first, the reader must evaluate what the author is trying to accomplish by pulling the last index. It is not difficult, but requires more effort on the part of the reader.

Thomas
  • 63,911
  • 12
  • 95
  • 141
2

EndsWith is probably safer. But the indexer is probably faster.

Endswith probably checks to see if the input string is empty. They will probably both throw null reference exceptions. And the indexer will fail is the length is 0.

As for readability, they both say the same thing to me, but I have been programming for a while. The .EndsWith(...) is probably faster to grasp without considering context.

Matthew Whited
  • 22,160
  • 4
  • 52
  • 69
  • 2
    Thanks down voter. How about a comment. I was making the point that the code isn't really the same (and I was revising my statement as you down voted.) – Matthew Whited Apr 06 '10 at 14:51
2

Both approaches are valid, but the endswith method is easier to read in my opinion. It also does away with the potential to make typing mistakes etc with the more complicated form..

Martin Milan
  • 6,346
  • 2
  • 32
  • 44
0

It pretty much does the same thing. However, it gets more complicated with more than one character in the endswith argument. However, the first example is slightly faster as it uses no actual functions and thus requires no stack. You might want to define a macro which can be used to simply make everything uniform.

Maz
  • 3,375
  • 1
  • 22
  • 27
  • Are you certain #1 is faster? I would expect the C# compiler to do automatic [inlining](http://en.wikipedia.org/wiki/Inline_expansion) in #2. – Jørn Schou-Rode Apr 06 '10 at 14:49
  • The question is about maintainability. Choosing one of these "styles" for performance is a micro-optimization that will never pay off as soon as a programmer spends an extra few seconds trying to understand what it does. – Chris Pitman Apr 06 '10 at 14:50
  • @Jørn Schou-Rode: The compiler won't inline anything. The JITer may, but it depends on many things including how much code is behind the method call. – Matthew Whited Apr 06 '10 at 14:52
  • @Matthew: Indeed, but that really does not change my point :) – Jørn Schou-Rode Apr 06 '10 at 15:00
0

I think the main criteria should be which of these most clearly says what the developer wants to do. What does each sample actually say?

1)Access the character at position one less than the length, and check if it equals the character 'r'

2)Check if it ends with the string "r"

I think that makes it clear which is the more maintainable answer.

Chris Pitman
  • 12,990
  • 3
  • 41
  • 56
0

Unless and until it does not affect the program performance, no problem you can use either way. But adding code comments is very important for conveying what is being accomplished.

zapping
  • 4,118
  • 6
  • 38
  • 56
0

"Code is written to be read by humans and incidently run by computers" SICP

EndsWith FTW!!

halfer
  • 19,824
  • 17
  • 99
  • 186
Daniel Elliott
  • 22,647
  • 10
  • 64
  • 82
0

From an error handling standpoint, EndsWith.

Josh
  • 590
  • 3
  • 4
0

I much prefer the second (EndsWith) version. It's clear enough for even my manager to understand!

SethO
  • 2,703
  • 5
  • 28
  • 38
0

The best practice is to write code that is easily readable. If you used the first one, developers that are debugging your code may say, "What is this dev trying to do?" You need to utilize methods that are easily explained. If a method is too complicated to figure out, retract several methods out of it.

I would definitely say the second one, legibility and simplicity are key!

Also, if the "if" statement has one line, DONT BOTHER USING BRACES, USE A SINGLE INDENTION

Mike
  • 1,412
  • 16
  • 24
  • `if the "if" statement has one line, DONT BOTHER USING BRACES, USE A SINGLE INDENTION` - this is really arbitrary advice you didn't even justify. You don't know when the "if" block will grow into more lines. If it does on another branch, you can get a merge conflict. Skipping braces can also lead to bugs - see http://stackoverflow.com/questions/359732/why-is-it-considered-a-bad-practice-to-omit-curly-braces for a bunch of examples. Coding style is a matter of taste, but we shouldn't present our preferences as a dogma, especially without backing them up with any rationale. – Konrad Morawski Jan 10 '14 at 10:54
  • yeah....this was almost 4 years ago. I've learned so much since then. thanks though! – Mike Jan 10 '14 at 15:55
  • I know, it can be a long time in programming :) – Konrad Morawski Jan 10 '14 at 15:59
0

Remember that in classic C, the only difference between a "string" and an array of characters is that terminating null character '\0', so we had to more actively treat them accordingly and to make sure that we did not run off the end of the array. So the first block of code bases its thought process on the concept of an array of characters.

The second block of code bases the thought process on how you handle a string more abstractly and with less regard to its implementation under the covers.

So in a nutshell, if you are talking about processing characters as the main idea behind your project, go with the first piece. If you are talking about preparing a string for something greater and that does not necessarily need to focus on the mechanics of the ways that strings are built -- or you just want to keep it simple -- go with the second style.

Some of this might summarize others' contributions at this point, but more analogously put, are you playing "Bingo();" or are you "playing a game with a two-dimensional array of random integers, etc.?"

Hopefully this helps.

Jim