Using If...Else vs If() - vb.net

Does cleanliness trump performance here:
Version 1:
Function MyFunc(ByVal param as String) As String
Dim returnValue as String
If param Is Nothing Then
returnValue = "foo"
Else
returnValue = param
return returnValue
Version 2:
Function MyFunc(ByVal param as String) As String
return If(param,"foo")
Version 1 deals directly with unboxed Strings. Version 2 deals with all boxed Objects. [If() takes a TestExpression as Object, a FalsePart as Object and returns an Object]
[can't add comments]
COMMENT: ja72, fixed my naming.
COMMENT: Marc, so you would go with Version 2?

I think clarity trumps anything.
The If(obj1,obj2) function is the null coalescing operator of VB.NET. It functions the same as obj1 ?? obj2 in C#. As such, everyone should know what it means, and it should be used where conciseness is important.
Although the If/Else statement is clean, simple, and obvious, in this particular case, I would favor the If function.

The compiler would optimize these two to the same code or nearly the same depending on the optimization level (See project properties).
Write two methods this way, compile them and use Reflector to look into the VB.Net decompiled code (or even MSIL) and you will see that there is very little (some billionth of a second) or none difference in exectuion.
Compiler optimizations generally handle normal patterns that allows you to write if-statements and loops in different ways. For instance in .Net for, foreach, while, do, etc do not actually exist. They are language specific features that are compiled down to goto-statement logic in the assembly level. Use Reflector to look at a few of these and you'll learn a lot! :)
Note that it is possible to write bad code that the compiler can't optimize to its "best state", and it is even possible to do better than the compiler. Understanding .Net assembly and MSIL means understanding the compiler better.

Really? I don't think this function is going to be a bottleneck in any application, and so just go with brevity/clarity.
I would recommend:
Public Function TXV(ByVal param As String) As String
Return If(param Is Nothing, "foo", param)
End Function
and make sure the function returns a string (to keep type safety). BTW, why is your Function called MySub ? Shouldn't it be MyFunc ?

I believe that these two implementations are nearly the same, I would use the second one because it's shorter.

Since I come from a C background, I would opt for the ternary operator most times where it is clear what is happening - in a case like this where there is repetition and it can be idiomatic. Similarly in T-SQL where you can use COALESCE(a, b, c, d, e) to avoid having a bunch of conditionals and simply take the first non-null value - this is idiomatic and easily read.
Beware that the old IIf function is different from the new If operator, so while the new one properly handles side-effects and short-circuits, it's only one character away from a completely different behavior which people have long been wary of.
http://secretgeek.net/iif_function.asp
http://visualbasic.about.com/od/usingvbnet/a/ifop.htm
I don't think it's going to matter in terms of performance, because the optimizer is pretty good about these kind of transforms.

Related

Should I give up grammatical correctness when naming my functions to offer regularity?

I implement several global functions in our library that look something like this:
void init_time();
void init_random();
void init_shapes();
I would like to add functions to provide a check whether those have been called:
bool is_time_initialized();
bool is_random_initialized();
bool are_shapes_initialized();
However, as you can see are_shapes_initialized falls out of the row due to the fact that shapes is plural and therefore the function name must start with are and not is. This could be a problem, as the library is rather large and not having a uniform way to group similiar functions under the same naming convention might be confusing / upsetting.
E.g. a user using IntelliSense quickly looking up function names to see if the libary offers a way to check if their initialization call happened:
They won't find are_shapes_initialized() here unless scrolling through hundreds of additional function / class names.
Just going with is_shapes_initialized() could offer clarity:
As this displays all functions, now.
But how can using wrong grammar be a good approach? Shouldn't I just assume that the user should also ask IntelliSense for "are_initialized" or just look into the documentation in the first place? Probably not, right? Should I just give up on grammatical correctness?
The way I see it, a variable is a single entity. Maybe that entity is an aggregate of other entities, such as an array or a collection, in which case it would make sense to give it a plural name e.g. a set of Shape objects could be called shapes. Even so, it is still a single object. Looking at it that way, it is grammatically acceptable to refer to it as singular. After all, is_shapes_initialized actually means "Is the variable 'shapes' initialized?"
It's the same reason we say "The Bahamas is" or "The Netherlands is", because we are referring to the singular country, not whatever plural entity it is comprised of. So yes, is_shapes_initialized can be considered grammatically correct.
It's more a matter of personal taste. I would recommend putting "is" before functions that return Boolean. This would look more like:
bool is_time_initialized();
bool is_random_initialized();
bool is_shapes_initialized();
This makes them easier to find and search for, even if they aren't grammatically correct.
You can find functions using "are" to show it is plural in places such as the DuckDuckGo app, with:
areItemsTheSame(...)
areContentsTheSame(...)
In the DuckDuckGo app, it also uses "is" to show functions return boolean, and boolean variables:
val isFullScreen: Boolean = false
isAssignableFrom(...)
In OpenTK, a C# Graphics Library, I also found usage of "are":
AreTexturesResident(...)
AreProgramsResident(...)
In the same OpenTK Libary, they use "is" singularly for functions that return boolean and boolean variables:
IsEnabledGenlock(...)
bool isControl = false;
Either usage could work. Using "are" plurally would make more sense grammatically, and using "if" plurally could make more sense for efficiency or simplifying Boolean functions.
Here's what I would do, assuming you are trying to avoid calling this function on each shape.
void init_each_shape();
bool is_each_shape_initialized();
Also assuming that you need these functions, it seems like it would make more sense to have the functions throw an exception if they do not succeed.

cli/c++ increment operator overloading

i have a question regarding operator overloading in cli/c++ environment
static Length^ operator++(Length^ len)
{
Length^ temp = gcnew Length(len->feet, len->inches);
++temp->inches;
temp->feet += temp->inches/temp->inchesPerFoot;
temp->inches %= temp->inchesPerFoot;
return temp;
}
(the code is from ivor horton's book.)
why do we need to declare a new class object (temp) on the heap just to return it?
ive googled for the info on overloading but theres really not much out there and i feel kinda lost.
This is the way operator overloading is implemented in .NET. Overloaded operator is static function, which returns a new instance, instead of changing the current instance. Therefore, post and prefix ++ operators are the same. Most information about operator overloading talks about native C++. You can see .NET specific information, looking for C# samples, for example this: http://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx
.NET GC allows to create a lot of lightweight new instances, which are collected automatically. This is why .NET overloaded operators are more simple than in native C++.
Yes, because you're overloading POST-increment operator here. Hence, the original value may be used a lot in the code, copied and stored somewhere else, despite the existance of the new value. Example:
store_length_somewhere( len++ );
While len will be increased, the original value might be stored by the function somewhere else. That means that you might need two different values at the same time. Hence the creation and return of a new value.

Boolean method naming readability

Simple question, from a readability standpoint, which method name do you prefer for a boolean method:
public boolean isUserExist(...)
or:
public boolean doesUserExist(...)
or:
public boolean userExists(...)
public boolean userExists(...)
Would be my prefered. As it makes your conditional checks far more like natural english:
if userExists ...
But I guess there is no hard and fast rule - just be consistent
I would say userExists, because 90% of the time my calling code will look like this:
if userExists(...) {
...
}
and it reads very literally in English.
if isUserExist and if doesUserExist seem redundant.
Beware of sacrificing clarity whilst chasing readability.
Although if (user.ExistsInDatabase(db)) reads nicer than if (user.CheckExistsInDatabase(db)), consider the case of a class with a builder pattern, (or any class which you can set state on):
user.WithName("Mike").ExistsInDatabase(db).ExistsInDatabase(db2).Build();
It's not clear if ExistsInDatabase is checking whether it does exist, or setting the fact that it does exist. You wouldn't write if (user.Age()) or if (user.Name()) without any comparison value, so why is if (user.Exists()) a good idea purely because that property/function is of boolean type and you can rename the function/property to read more like natural english? Is it so bad to follow the same pattern we use for other types other than booleans?
With other types, an if statement compares the return value of a function to a value in code, so the code looks something like:
if (user.GetAge() >= 18) ...
Which reads as "if user dot get age is greater than or equal to 18..." true - it's not "natural english", but I would argue that object.verb never resembled natural english and this is simply a basic facet of modern programming (for many mainstream languages). Programmers generally don't have a problem understanding the above statement, so is the following any worse?
if (user.CheckExists() == true)
Which is normally shortened to
if (user.CheckExists())
Followed by the fatal step
if (user.Exists())
Whilst it has been said that "code is read 10x more often than written", it is also very important that bugs are easy to spot. Suppose you had a function called Exists() which causes the object to exist, and returns true/false based on success. You could easily see the code if (user.Exists()) and not spot the bug - the bug would be very much more obvious if the code read if (user.SetExists()) for example.
Additionally, user.Exists() could easily contain complex or inefficient code, round tripping to a database to check something. user.CheckExists() makes it clear that the function does something.
See also all the responses here: Naming Conventions: What to name a method that returns a boolean?
As a final note - following "Tell Don't Ask", a lot of the functions that return true/false disappear anyway, and instead of asking an object for its state, you tell it to do something, which it can do in different ways based on its state.
The goal for readability should always be to write code the closest possible to natural language. So in this case, userExists seems the best choice. Using the prefix "is" may nonetheless be right in another situations, for example isProcessingComplete.
My simple rule to this question is this:
If the boolean method already HAS a verb, don't add one. Otherwise, consider it. Some examples:
$user->exists()
$user->loggedIn()
$user->isGuest() // "is" added
I would go with userExists() because 1) it makes sense in natural language, and 2) it follows the conventions of the APIs I have seen.
To see if it make sense in natural language, read it out loud. "If user exists" sounds more like a valid English phrase than "if is user exists" or "if does user exist". "If the user exists" would be better, but "the" is probably superfluous in a method name.
To see whether a file exists in Java SE 6, you would use File.exists(). This looks like it will be the same in version 7. C# uses the same convention, as do Python and Ruby. Hopefully, this is a diverse enough collection to call this a language-agnostic answer. Generally, I would side with naming methods in keeping with your language's API.
There are things to consider that I think were missed by several other answers here
It depends if this is a C++ class method or a C function. If this is a method then it will likely be called if (user.exists()) { ... } or if (user.isExisting()) { ... }
not if (user_exists(&user)) .
This is the reason behind coding standards that state bool methods should begin with a verb since they will read like a sentence when the object is in front of them.
Unfortunately lots of old C functions return 0 for success and non-zero for failure so it can be difficult to determine the style being used unless you follow the all bool functions begin with verbs or always compare to true like so if (true == user_exists(&user))
Why not rename the property then?
if (user.isPresent()) {
Purely subjective.
I prefer userExists(...) because then statements like this read better:
if ( userExists( ... ) )
or
while ( userExists( ... ) )
In this particular case, the first example is such horrible English that it makes me wince.
I'd probably go for number three because of how it sounds when reading it in if statements. "If user exists" sounds better than "If does user exists".
This is assuming it's going to be to used in if statement tests of course...
I like any of these:
userExists(...)
isUserNameTaken(...)
User.exists(...)
User.lookup(...) != null
Method names serves for readability, only the ones fit into your whole code would be the best which most of the case it begins with conditions thus subjectPredicate follows natural sentence structure.
Since I follow the convention to put verb before function name, I would do the same here too:
//method name
public boolean doesExists(...)
//this way you can also keep a variable to store the result
bool userExists = user.doesExists()
//and use it like a english phrase
if (userExists) {...}
//or you can use the method name directly also and it will make sense here too
if (user.doesExists()) {...}

How to convert this code to LINQ?

I'm trying to write this as LINQ,
Original code:
For Each CurrentForm As Form In MyForms
AddLink(CurrentForm.GetLink())
Next
I'm a LINQ beginner, so far I'm not quite sure where to use and where not to. If in this case LINQ will do more harm then help, feel free to flame me.
Edit : You can assume that there is an overload for AddLink() which takes IEnumerable
Unless there is an overload of AddLink which takes a collection, LINQ won't avoid the loop.
Is there is such an overload then something like:
AddLinks(MyForms.Select(f => f.GetLink())
would do it.
How the above expression works (briefly):
LINQ is about expressions, taking some object (for LINQ to Objects used here, always a collection)
Select extension method takes a collection and a function and returns a collection. The function is passed each element of the input collection. And then Select returns the collection made up of all the function return values.
I have used a lambda expression to create an anonymous function that takes one argument called f (its type will be determined by the compiler) and returns the value of the expression (now corrected).
AddLinks is an assumed variant of your AddLink which takes a collection of links.
There is a lot going on, this is one of the advantages of LINQ, it is a compact way of expressing data manipulation without the usual overheads of explicit loops and temporary variables.
No flames here, but LINQ won't really help here. If LINQ had a ForEach method (as has been discussed in a previous question, as well as elsewhere) then you could use that - but it's not built into LINQ, and in this case there doesn't really seem to be much use for it.
Of course, it depends exactly what AddLink does - if it adds a link to a list, and you could instead use (say) List.AddRange, then you could use LINQ. But this code seems pretty simple and readable already, so I wouldn't worry in this case.

IsNothing versus Is Nothing

Does anyone here use VB.NET and have a strong preference for or against using IsNothing as opposed to Is Nothing (for example, If IsNothing(anObject) or If anObject Is Nothing...)? If so, why?
EDIT: If you think they're both equally acceptable, do you think it's best to pick one and stick with it, or is it OK to mix them?
If you take a look at the MSIL as it's being executed you'll see that it doesn't compile down to the exact same code. When you use IsNothing() it actually makes a call to that method as opposed to just evaluating the expression.
The reason I would tend to lean towards using "Is Nothing" is when I'm negating it becomes "IsNot Nothing' rather than "Not IsNothing(object)" which I personally feel looks more readable.
I find that Patrick Steele answered this question best on his blog: Avoiding IsNothing()
I did not copy any of his answer here, to ensure Patrick Steele get's credit for his post. But I do think if you're trying to decide whether to use Is Nothing or IsNothing you should read his post. I think you'll agree that Is Nothing is the best choice.
Edit - VoteCoffe's comment here
Partial article contents: After reviewing more code I found out another reason you should avoid this: It accepts value types! Obviously, since IsNothing() is a function that accepts an 'object', you can pass anything you want to it. If it's a value type, .NET will box it up into an object and pass it to IsNothing -- which will always return false on a boxed value! The VB.NET compiler will check the "Is Nothing" style syntax and won't compile if you attempt to do an "Is Nothing" on a value type. But the IsNothing() function compiles without complaints. -PSteele – VoteCoffee
You should absolutely avoid using IsNothing()
Here are 4 reasons from the article IsNothing() VS Is Nothing
Most importantly, IsNothing(object) has everything passed to it as an object, even value types! Since value types cannot be Nothing, it’s a completely wasted check.
Take the following example:
Dim i As Integer
If IsNothing(i) Then
' Do something
End If
This will compile and run fine, whereas this:
Dim i As Integer
If i Is Nothing Then
' Do something
End If
Will not compile, instead the compiler will raise the error:
'Is' operator does not accept operands of type 'Integer'.
Operands must be reference or nullable types.
IsNothing(object) is actually part of part of the Microsoft.VisualBasic.dll.
This is undesirable as you have an unneeded dependency on the VisualBasic library.
Its slow - 33.76% slower in fact (over 1000000000 iterations)!
Perhaps personal preference, but IsNothing() reads like a Yoda Condition. When you look at a variable you're checking its state, with it as the subject of your investigation.
i.e. does it do x? --- NOT Is xing a property of it?
So I think If a IsNot Nothing reads better than If Not IsNothing(a)
I agree with "Is Nothing". As stated above, it's easy to negate with "IsNot Nothing".
I find this easier to read...
If printDialog IsNot Nothing Then
'blah
End If
than this...
If Not obj Is Nothing Then
'blah
End If
VB is full of things like that trying to make it both "like English" and comfortable for people who are used to languages that use () and {} a lot.
And on the other side, as you already probably know, most of the time you can use () with function calls if you want to, but don't have to.
I prefer IsNothing()... but I use C and C#, so that's just what is comfortable. And I think it's more readable. But go with whatever feels more comfortable to you.
I'm leaning towards the "Is Nothing" alternative, primarily because it seems more OO.
Surely Visual Basic ain't got the Ain't keyword.
I initially used IsNothing but I've been moving towards using Is Nothing in newer projects, mainly for readability. The only time I stick with IsNothing is if I'm maintaining code where that's used throughout and I want to stay consistent.
Is Nothing requires an object that has been assigned to the value Nothing. IsNothing() can take any variable that has not been initialized, including of numeric type. This is useful for example when testing if an optional parameter has been passed.