Let's suppose we want to throw if we try to assign null to something, what about this trick:
public static class ExceptionExtension
{
public static T Throw<T>(this Exception exc)
{
throw exc;
}
}
that we can use for example like this:
return possibleNull ?? new Exception("Unspecified something....").Throw<string>();
do you think it is a good/worst/useless practice ?
It makes no sense to me - not very readable. I would expect the second argument of the ?? operator to be of the same type of possibleNull, not to throw an excpetion.
I would much rather see:
if(possibleNull == null)
{
throw new Exception("Unspecified something....");
}
return possibleNull;
It could be better and more readable to create some kind of static helper class that throws
Like this
public static class ThrowHelper
{
public static TException ThrowIfNull<TException>(object value)
where TException : Exception, new()
{
if (value == null) //or other checks
{
throw new TException();
}
}
}
You could always stick it in some sort of short-named static helper class:
public static class Never
{
public static T Null<T>(T value)
where T : class
{
if (value == null) throw new ArgumentNullException();
return value;
}
}
myClass.AProperty = Never.Null(somePotentiallyNullValue);
Your other example wouldn't make much sense, I'd opt for calling it "useless" practice.
Adding a bit of "fluency" to helper classes tends to focus on making things more readable.
http://en.wikipedia.org/wiki/Fluent_interface
I wouldn't consider it a good practice.
First, the extension method itself just introduces a method for something we already have a keyword for: throw. This might be confusing. It declares a return type though it will never return a value, just to please the compiler in the context where you want to use it. Referring to what others already pointed out, that's rather a "principle of most astonishment".
Then, looking on how you would employ this method, the resulting code seems not very clear to read. Even worse: you can only use this approach in an expression, so you would always end up with code that uses an object in some way (in your example: just return it) and checks it for null as a side effect in the same line. I'd prefer doing null checks explicitly and not mixed with something else. A library like CuttingEdge.Conditions can help to reduce the amount of code you have to type for this. You would use it in your example this way
Condition.Requires(possibleNull , "possibleNull ").IsNotNull();
return possibleNull;
Related
Using dynamic pattern perhaps? You can call any method/property using the dynamic keyword, right? How to check whether the method exist before calling myDynamicObject.DoStuff(), for example?
You could write something like that :
public static bool HasMethod(this object objectToCheck, string methodName)
{
var type = objectToCheck.GetType();
return type.GetMethod(methodName) != null;
}
Edit : you can even do an extension method and use it like this
myObject.HasMethod("SomeMethod");
via Reflection
var property = object.GetType().GetProperty("YourProperty")
property.SetValue(object,some_value,null);
Similar is for methods
It is an old question, but I just ran into it.
Type.GetMethod(string name) will throw an AmbiguousMatchException if there is more than one method with that name, so we better handle that case
public static bool HasMethod(this object objectToCheck, string methodName)
{
try
{
var type = objectToCheck.GetType();
return type.GetMethod(methodName) != null;
}
catch(AmbiguousMatchException)
{
// ambiguous means there is more than one result,
// which means: a method with that name does exist
return true;
}
}
Wouldn't it be better to not use any dynamic types for this, and let your class implement an interface.
Then, you can check at runtime wether an object implements that interface, and thus, has the expected method (or property).
public interface IMyInterface
{
void Somemethod();
}
IMyInterface x = anyObject as IMyInterface;
if( x != null )
{
x.Somemethod();
}
I think this is the only correct way.
The thing you're referring to is duck-typing, which is useful in scenarios where you already know that the object has the method, but the compiler cannot check for that.
This is useful in COM interop scenarios for instance. (check this article)
If you want to combine duck-typing with reflection for instance, then I think you're missing the goal of duck-typing.
To avoid AmbiguousMatchException, I would rather say
objectToCheck.GetType().GetMethods().Count(m => m.Name == method) > 0
I've got a custom assertion that always throws an exception inside of it, but it is being used in a C# function which requires a return value. In the example below, CustomAssert.Fail() always throws an exception, and so "return null" will never execute. Code coverage marks this as untested, and I'd like to work around this.
public string GetSomething()
{
CustomAssert.Fail();
return null;
}
I've thought about refactoring CustomAssert.Fail() to return a null object and doing something like this, but it seems a bit hackish. Any other way to accomplish this, or do I have to sacrifice code coverage?
public string GetSomething()
{
return CustomAssert.Fail() as string;
}
First off, I wouldn't consider code coverage as the most important metric in testing. This is a perfect example where it is obvious that everything might be perfectly tested and still not get 100% coverage. I'd live with not having full coverage in this case.
That said, one way around the issue is refactoring CustomAssert.Fail() to return an Exception and then simply write:
public string GetSomething()
{
throw CustomAssert.Fail();
}
Disadvantages? Your CustomAssert will have inconsistent behavior, which is something that should be avoided if possible. As you well say in comments, conditional asserts can't return an exception for obvious reasons so you'll have CustomAssert.IsNotNull(...) not returning anything and throwing if the assert fails while CustomAssert.Fail() will return an exception that must be explicitly thrown by the consumer. The solution seems a little yucky.
One way to slightly improve this inconvenience, is to refactor CustomAssert the following way:
public static class CustomAssert
{
public static void IsNotNull<T>(this T target)
{
if (ReferenceEquals(target, null)) throw new ArgumentNullException();
}
public static void IsTrue<T>(this T target, Predicate<T> validator)
{
if (!validator(target)) throw new ArgumentException();
}
public static void IsInRange<T, Q>(this T target, Q inclusiveLowerBound, Q exclusiveUpperBound) where T: IComparable<Q>
{
...
}
//etc.
public static T Fail<T>() where T :Exception, new()
{
return new T();
}
}
Now, the usage is different for Fail and any conditional assertion and the inconsistency is somewhat resolved:
public void Foo(Bar arg)
{
//Conditional usage
arg.IsNotNull();
arg.IsNotTrue(t => t != null);
arg.IsInRange(0, 2);
//Unconditional fail
throw CustomAssert.Fail<NotSupportedException>();
}
All that said, I'd seriously consider changing the name of CustomAssert. Assert has a pretty established meaning to most programmers and it can cause misunderstandings. Maybe something similar to CustomValidator would be a better idea.
Looking for some best-practice guidance. Let's say I have a line of code like this:
Color color = someOrder.Customer.LastOrder.Product.Color;
where Customer, LastOrder, Product, and Color could be null under normal conditions. I'd like color to be null if any one of the objects in the path is null, however; in order to avoid null reference exceptions, I'd need to check for the null condition for each one of the objects, e.g.
Color color = someOrder == null ||
someOrder.Customer == null ||
someOrder.Customer.LastOrder == null ||
someOrder.Customer.Product == null ?
null : someOrder.Customer.LastOrder.Product.Color;
or I could do this
Color color = null;
try {color = someOrder.Customer.LastOrder.Product.Color}
catch (NullReferenceException) {}
The first method clearly works, but it seems a bit more tedious to code and harder to read. The second way is a bit easier but probably not a good idea to use exception handling for this.
Is there another shortcut way of checking for nulls and assigning null to color if necessary? Or any thoughts on how to avoid NullReferenceExceptions when using such nested references?
You are looking for the null-safe dereferencing operator.
Color color = someOrder?.Customer?.LastOrder?.Product?.Color;
Unfortunately C# doesn't support it. Maybe it will be added later, but there are no plans to do that at the moment.
Related
Deep null checking, is there a better way?
Best practice is to follow Law of Demeter which sounds as: don't talk to strangers. I.e. object should avoid invoking methods of a member object returned by another method. This allows to write less coupled, more maintainable and readable code.
So, avoid using 'train wrecks' like someOrder.Customer.LastOrder.Product.Color, because they completely violate Law of Demeter. It's even hard to understand what business meaning this code has. Why are you getting color of product of some other order, which is not the current one?
Possible way to remove train wreck - push functionality closer to interesting end of wreck. In your case, also consider passing last product to your method, instead of using some order.
where you need to achieve this do this.
Usage
Color color = someOrder.ComplexGet(x => x.Customer.LastOrder.Product.Color);
or
Color color = Complex.Get(() => someOrder.Customer.LastOrder.Product.Color);
Helper Class Implementation
public static class Complex
{
public static T1 ComplexGet<T1, T2>(this T2 root, Func<T2, T1> func)
{
return Get(() => func(root));
}
public static T Get<T>(Func<T> func)
{
try
{
return func();
}
catch (Exception)
{
return default(T);
}
}
}
I would definitely prefer the first method... the second one exploits the exception mechanism for program flow which is bad practice IMHO...
AFAIK there is no shortcut or "null-safe dereferencing operator" in C# .
Define unique method for accessing nested properties.
For example like this
private Customoer GetCustomer(Order order)
{
return order != null ? order.Customer : null;
}
private Order GetLastOrder(Customer customer)
{
return customer != null ? customer.LastOrder : null;
}
Using the defined method access your properties across the application
You can also use the Null-conditional operator in an if statement. Really useful if there is a lot of nested values.
Example:
public class DummyDto
{
public string Name { get; set; }
public DummyDto Parent { get; set; }
}
class Program
{
static void Main(string[] args)
{
var dummyDto = new DummyDto();
//Both if statements will be true below
if(dummyDto.Parent?.Name == null)
{
Console.WriteLine("DummyDto is null");
}
if (dummyDto.Parent == null || dummyDto.Parent.Name == null)
{
Console.WriteLine("DummyDto is null");
}
}
}
I am tired of writing:
if(objectA!=null)
return;
or:
if(objectB==null)
return;
So I was hope to shorten this snippet, to something like this:
Returns.IfNull(objectA);
it is pretty match the same length but usually there are few objects to check and adding params as parameter can shorten:
if(objectA==null || objectB!=null || objectC!=null)
return;
to:
Returns.IfNull(objectA,objectB,objectC);
Basically function IfNull have to get access to function one step higher in stack trace and finish it. But that's only idea, I don't know if it's even possible. Can I find simililar logic in some lib?
No, you are essentially asking the function to exit the function higher than itself which isn't desirable nor really possible unless you throw an exception (which isn't returning per se).
So, you can either do your simple and concise if-null-return checks, or what you may want to do there instead is to throw a well defined exception, but I don't recommend exceptions for flow-control. If these are exceptional (error) circumstances, though, then consider throwing an ArgumentNullException() and handling it as appropriate.
You could write some helper methods to throw ArgumentNullException() for you, of course, to clean it up a bit:
public static class ArgumentHelper
{
public static void VerifyNotNull(object theObject)
{
if (theObject == null)
{
throw new ArgumentNullException();
}
}
public static void VerifyNotNull(params object[] theObjects)
{
if (theObjects.Any(o => o == null))
{
throw new ArgumentNullException();
}
}
}
Then you could write:
public void SomeMethod(object obj1, object obj2, object obj3)
{
ArgumentHelper.VerifyNotNull(obj1, obj2, obj3);
// if we get here we are good!
}
But once again, this is exceptions and not a "return" of the previous method in the stack, which isn't directly possible.
You are asking for something that only the language designer can fix for you.
I have proposed one thing by myself.
The .? operator does return from the current method with the default return value when the argument left to it is null.
return appSettings.?GetElementKey(key).?Value ?? "";
Perhaps we will see it some day in C# 6?
To do similar comparison checks I once defined the following extension method:
/// <summary>
/// Returns whether the object equals any of the given values.
/// </summary>
/// <param name = "source">The source for this extension method.</param>
/// <param name = "toCompare">The objects to compare with.</param>
/// <returns>
/// True when the object equals any of the passed objects, false otherwise.
/// </returns>
public static bool EqualsAny( this object source, params object[] toCompare )
{
return toCompare.Any( o => o.Equals( source ) );
}
It can simplify redundant checks, e.g.:
string someString = "bleh";
bool anyEquals = someString.EqualsAny( "bleh", "bloeh" );
In your case where you check for multiple null checks you could use it as follows:
if ( EqualsAny( null, objectA, objectB, objectX ) ) return;
On another note, your code reminds me of Code Contracts which allows you to define pre and post conditions. In case this is your scenario - perhaps not as I don't see why you call return - it might interest you. Part of it is available for free in .NET 4.0.
You can not invoke another method and expect it to return to the callee of the current method (you could if we had something like continuation passing style; alas, we do not).
You could say:
if(new[] { objectA, objectB, objectC }.Any(x => x != null)) {
return;
}
Or:
if(new[] { objectA, objectB, objectC }.AnyAreNotNull()) {
return;
}
Here, AnyAreNotNull is:
public static class EnumerableExtensions {
public static bool AnyAreNotNull<T>(this IEnumerable<T> source) {
Contract.Requires(source != null);
return source.Any(x => x != null);
}
}
But really, there is nothing wrong with just writing the usual code for this situation.
No, a method can't return the method above it.
Best you could do is create a method that returned true if any of its params were null, then do if (ReturnHelper.AllNull(obj1, obj2, obj3)) return; but i'd say this is much less readable.
Could you help me please.
I have one idea but don't know how can I implement it.
So the question is:
Can we interrupt creating an object in constructor
i.e.
//Code
SomeClass someClass = new SomeClass(someCriteria);
So if someCriteria doesn't answer on our requirements we shouldn't create an object and should return null, instead of new object.
Is it possible to implement it in C#?
Best way is a factory class but if your class is so small you can use this:
class SomeClass
{
private string _someCriteria;
private SomeClass(string someCriteria)
{
_someCriteria = someCriteria;
}
public static SomeClass CreateInstance(string someCriteria)
{
if (someCriteria.Length > 2)
{
return new SomeClass(someCriteria);
}
return null;
}
}
class Program
{
static void Main(string[] args)
{
// returns null
SomeClass someClass = SomeClass.CreateInstance("t");
// returns object
SomeClass someClass2 = SomeClass.CreateInstance("test");
}
}
You may want to use a factory class that creates instances of SomeClass returning null if the someCriteria is invalid.
It is quite usual that you check the constructor parameters if they are valid. If not, you usually throw an exception.
I also read a nice advice to provide static methods for validating constructor parameters. This enables the user of your class to check if whatever he is going to pass in the constructor will succeed or not. Those who are certain the parameters are ok (they made some sort of their validation) will go directly with the constructor.
Also consider what the user of your class will possibly do with null instead of the object (if some sort of factory class was used). Would this typically result in an NullPointerException on the next line? It's usually good idea to stop the wrong things as soon as possible, in this case throw the exception and finish. It is cleaner solution than returning null and if someone really wants to (this definetly won't be best practise) he can still catch this exception ...
If the parameters to your constructor are invalid, consider throwing ArgumentException or one of its descendant classes (e.g. ArgumentOutOfRangeException).
The new construct guarantees that an object will be returned (or an exception thrown). So as bleeeah recommended, a factory or similar concept will allow you to apply your logic.
That would be possible. Another way would be to put your checking in before you create the object. Like so
SomeClass someClass = null;
if (someCriteria == VALID)
{
someClass = new SomeClass(someCriteria);
}
Hope this helps.
No it is not possible directly.
You could throw an exception and add the required code to check for the exception and assign null to you variable.
A better solution would be to use a Factory that would return null if some condition fail.
var someClass = SomeClassFactory.Create(someCriteria);
if(someClass != null)
{
}