While working on a project I have come a开发者_如何转开发cross a way of not having to check if a string isnull
or empty
dim sb as new stringbuilder
dim bob as string
sb.append((bob & string.empty).padLeft(10, " "))
Here, bob
is not instantiated but doesn't throw a null reference error. In situations like this, is it more readable to do the above code or the below code?
if string.isnullorempty(bob) then
sb.append(string.empty.padleft(10, " ")
else
sb.append(bob.padleft(10," "))
endif
I personally think method #1 is more readable and maintainable. What does the community feel?
Use If() with two parameters to select the first non-null value, e.g.
If(bob, string.empty).padLeft(10, " ")
It depends on your audience. If you have experienced developers such tricks are acceptable. A new developer will definitely get confused by the first example.
A good guide is this:
- Would you know a week from now what the code does? Yes -> Ok
- Do you need to comment what it does? Yes -> Not Ok
- Will there be new developers in the team that might not understand this code? Yes -> Not Ok
In the end its your call. I would understand and accept the first example.
An even better solution.
if not string.isnullorempty(bob) then
sb.append(bob)
endif
sb.append(New String(" "c, 3)) ' ten spaces
精彩评论