During the code review, there was a source that I was interested in, so I will list it. It's not a big deal, but it can't be helped.
int? inputValue = null;
//NG I couldn't think of such an implementation method, so I thought it was a little amazing.
if (string.IsNullOrWhiteSpace(inputValue.ToString()))
{
}
//Use the OK property
if (!inputValue.HasValue)
{
}
// OK !Nullable.This is fine because it is equivalent to HasValue.
if (inputValue == null)
{
}
2. Extract value from nullable type.
int? inputValue = 1;
int value;
if (inputValue.HasValue)
{
//NG Let's stop the idea that anything should be a character string
value = int.Parse(inputValue.ToString());
//NG useless cast 1
value = Convert.ToInt32((object)inputValue);
//Use OK property
value = inputValue.Value;
//OK Looks like a useless cast, but inputValue.Value is called.
value = (int)inputValue;
}
object objectValue = 1;
int castValue;
if (objectValue != null)
{
//Casting as an NG string is wasteful
castValue = int.Parse(objectValue.ToString());
// OK .Use the conversion process provided by Net Framework
castValue = Convert.ToInt32(objectValue);
//OK normal cast
castValue = (int)objectValue;
}
Many people think that it should be a character string. Even if there is no problem with the operation, the reviewer can not help it.
/**Null check**/
Integer inputValue = null;
//No one would write this in NG java.
//By the way, C#Int?Is a Nullable structure, so no Null check was needed before ToString.
if (inputValue == null || inputValue.toString().length() == 0) {
}
//OK For Java, it is correct to compare with null.
if (inputValue == null) {
}
/**Nullable type**/
Integer inputValue = 1;
int value;
if (inputValue != null) {
//NG Let's stop the idea that anything should be a character string
value = Integer.parseInt(inputValue.toString());
//NG useless cast
value = (int) inputValue;
// OK Integer.intValue is called.
value = inputValue;
// OK
value = inputValue.intValue();
}
/**Object type**/
Object objectValue = 1;
int castValue;
if (objectValue != null) {
//NG If you know the original type, you don't need to convert it to a string.
castValue = Integer.parseInt(objectValue.toString());
//OK Cast to original mold
castValue = (int) objectValue;
}
Previous article (confusing conditional branching)
[Next article (flowing interface)] (http://qiita.com/csharpisthebest/items/403d40374acc70ef24e3)
Recommended Posts