After reading this Eric Lippert Article, I understand that the C# compiler doesn't like it if we leave local variables uninitialized.
As I encounter this 'problem' from time to time, I looked at some of my old code and was able to weed out most of the situation where actually don't need uninitialized (SomeClass obj = null) local variables.
But I came up with a situation where I don't know how to refactor the code.
public void DoSomething(string foo) {
SomeClass obj; // = null;
try {
obj = SomeClass.CreateItem(target);
} catch(CustomException ex) {
// notify UI of error
}
if (obj != null) {
// do something with `obj`
}
}
SomeClass.CreateItem may fail due to external factors. If it does, I want to notify the user, if not I want to perform an Action.
The C# compiler doesn't want me to leave obj uninitialized, so I usually assign null to it.
This feels like a 'hack' now and my question is:
Is there a design flaw in the code above?
And if there is, how should I deal with references at compile time, when I can't determine if they are going to point to an existing object at run time?
I would refactor the code like this:
private SomeClass TryToCreateItem()
{
try
{
return SomeClass.CreateItem(target);
}
catch(CustomException ex)
{
// notify UI of error
}
return null;
}
public void DoSomething(string foo)
{
SomeClass obj = TryToCreateItem();
if (obj != null) {
// do something with `obj`
}
"Extract method" is my favourite refactoring.
The // do something withobj`` code should be inside the try block`.
What you're trying to do is run some code that may or may not succeed, and then run some other code only if the previous code succeeded. That's generally a very strong sign that the other code is a part of the same logical block that is dependent on there not being an exception. If there's an exception constructing this object you want this code to be skipped, which is exactly the behavior that you get by including it in the try block.
You could refactor it to encapsulate all your code within the try/catch related to that object and if you really do need to do something if it fails then you can use a bool to relate that to the rest of your code:
public void DoSomething(string foo)
{
bool failedCreation = false;
try
{
SomeClass obj = SomeClass.CreateItem(target);
}
catch (CustomException ex)
{
// notify UI of error
failedCreation = true;
}
if (failedCreation)
{
// do other stuff.
}
}
But this doesn't look like what you have in mind. I would just encapsulate everything within the try/catch and be done with it.
Related
As question asked Here 8 years ago but I think there should be a way(New Patterns , New Designs , New Architectures or anything else.) to enforce method don't return null.
As you know there are some implications with returning null in a method one important for me is:
Handling null in Consuming-Side and understandable semantics like:
Method:
public ClassName Do()
{
...
return null;
}
And calling Do() like (Attention Comments also):
var objVal = Do();
//Accessing property of ClassName raised exception
var pnVal = objVal.PropName;//Exception id objVal is null
//But I should handle if it is not null then do anything I want
if(objVal!= null)
{
//Do something
}
after many problem on product by above way I came to this conclusion to generalize all method to follow a pattern to be readable,clean and preventing ambiguous semantic.
so a very basic Way is using Struct type because structure can't be null , if a return type of methods be structure then they can't return null and We know this in compile time not in runtime.
So I implement that above method like:
1- Make DTO out and in for method, in this case just out:
public struct Do_DTO_Out
{
public ClassName Prop1 { get; set; }
public bool IsEmpty
{
get
{
return Prop1 == null;
}
}
public static Do_DTO_Out Empty
{
get
{
return new Do_DTO_Out() { Prop1 = null };
}
}
}
2- And Do method should be:
public Do_DTO_Out Do()
{
try
{
return manipulatedObj;
}
catch (Exception exp)
{
}
return Do_DTO_Out.Empty;
}
3- In consuming side:
var objVal = Do();
if (!objVal.IsEmpty)
//Do something
Is struct is best way ? is it worth to change all method and create DTO in and out for each of them (I think so).
Is there better way to do that , any idea,help,answer would be truly appreciated.
Your 'reference type' to 'struct with property check' conversion seems useless to me. It also requires intimate knowledge of your intention, while the reference type null check is very obvious to anyone reading it later.
I think code contracts could work for you. It provides you with compile time static analysis and runtime checks. Just make sure you have the appropriate contract as post condition:
public ClassName Do()
{
...
object returnValue = null;
Contract.Ensures(returnValue != null);
return returnValue;
}
Assuming that value can never be null otherwise the if is unavoidable (but for a single method call you can now write Do()?.DoSomething()).
If you can introduce code contracts (see Patrick's answer) then I completely agree with Patrick and you should go with them. If it's not viable (because your codebase is already too big or you're targeting an environment where they aren't supported) then I'd first use assertions:
var obj = Do();
Debug.Assert(obj != null);
// Use obj...
We're however moving this responsibility to calling point and it may be tedious. If you want to make this interface explicit then you can use something a struct as you thought but throwing an exception at calling point (where the error is):
public NotNullable<SomeClass> Do() { }
Where NotNullable<T> is defined as:
public struct NotNullable<T> where T : class
{
public NotNullable(T value)
{
Value = value ?? throw new ArgumentNullException(nameof(value));
}
public T Value { get; }
}
However I do not like to explicitly access .Value at calling point then I'd make it transparent adding:
public static implicit operator T(NotNullable<T> rhs)
=> rhs.Value;
Now caller can be:
MyClass obj = Do();
obj.DoSomthing();
And the proper exception is thrown (at run-time, unfortunately) when object is created. Playing with [Conditional("DEBUG")] you may exclude that check for release builds having then a behavior similar to Debug.Assert() and a minimal (but still present) overhead.
Note that this makes sense only if you want to document interface method about this constraint directly in its signature. If you're not interested in this then keep it as simple as possible:
public SomeClass Do()
{
MyClass somevalue = ...
// ...
return NotNull(somevalue);
}
Where NotNull() is a static method define somewhere and imported with using static or even an extension method for object called as return somevalue.NotNull().
I don't especially like this approach because I think Debug.Assert() is enough in these cases but it's just my opinion. Of course maybe someday we will have Nullable Reference Types in C# then we'll get compile-time enforcement (as object? or the other way round object!).
Returning null is a bad practice - better to implement
NullObject Design Pattern
We have the following construct in our codebase, used to ensure a particular resource is disposed of after use:
using (var disposableThing = DisposableThing.Begin())
{
// do something
disposableThing.Finish(); // must always be called
}
Here's an example of its usage:
List<int> ids;
using (var disposableThing = DisposableThing.Begin())
{
ids = disposableThing.GetSomeIds();
disposableThing.Finish();
}
DoSomethingElseWith(ids);
Since this pattern is so common, we wrote a method on DisposableThing to encapsulate it:
static void ExecuteWithFinish(Action<DisposableThing> action)
{
using (var disposableThing = Begin())
{
action(disposableThing);
disposableThing.Finish();
}
}
which allows us to rewrite the second sample as:
// #4
List<int> ids;
DisposableThing.ExecuteWithFinish(disposableThing =>
{
ids = disposableThing.GetSomeIds();
});
DoSomethingElseWith(ids); // compiler error "Use of unassigned local variable 'ids'"
But the compiler refuses to compile that code because it has no way to know that ids will always be assigned after ExecuteWithFinish has completed (or thrown an exception, which will prevent the execution of DoSomethingElseWith anyway).
I know I could add an overload of ExecuteWithFinish that returns values from a passed-in Func, which is ugly.
I know I could subclass DisposableThing and override its Dispose method to call Finish, which is a cleaner, neater, and faster way than constructing a delegate each time (this is probably what I'll end up doing).
But for my own edification and in the spirit of "what if", is it possible to inform or even trick the compiler into allowing the code in #4 as written?
edit: Yes, I know I could write List<int> ids = null; and circumvent this issue entirely, but (a) I'd prefer not to perform unnecessary assignments (b) I'd like to change the code as little as possible.
I would take a different approach here.
I'm going to make the assumption that for some reason you must have a Finish() method that must always be called before Dispose(), which must also always be called.
That may be a rash assumption, and it does rather beg the question: Why don't you put the functionality of Finish() into the Dispose()? However...
Firstly, create an interface to encapsulate a disposable thing with a Finish() method:
public interface IDisposableThingWithFinish : IDisposable
{
void Finish();
}
and change your DisposableThing class so that it implements IDisposableThingWithFinish.
Then you could write a disposable class that encapsulates calling Finish() and then Dispose() like so:
public sealed class DisposingFinisher : IDisposable
{
readonly IDisposableThingWithFinish _item;
public Disposing(IDisposableThingWithFinish item)
{
if (item == null)
throw new ArgumentNullException(nameof(item));
_item = item;
}
public void Dispose()
{
try
{
_item.Finish();
}
finally
{
_item.Dispose();
}
}
}
You would use Finisher like so:
using (var disposableThing = new DisposingFinisher(DisposableThing.Begin()))
{
// Do something.
}
A simple null-assignment will avoid the compiler warning as explained in the documentation of compiler error CS0165:
List<int> ids = null;
Although this question might sound stupid at first glance, please hear me out.
c#'s get{} and set{} methods are increadibly usefull in situations when you do not know how you porgramming goals will evolve while you build your code. I enjoyed their freedom many a time and now I wonder if there is something similar for methods but in a bit different light.
As I am working in gamedev, it is a very common practice to extend/update/improve existing code day-in day-out. Therefore, one of the patterns I taught myself to follow is to never use "return" statement more than once in the most of my methods.
The reason why I do this is to always be able to write something at the bottom of the method and be sure that the line I have written is always called 100% of the time once my method ENDS.
Here is an example:
public void Update()
{
UpdateMovement();
if (IsIncapacitated)
return;
if (IsInventoryOpened)
{
UpdateInventory();
return;
}
if (Input.HasAction(Actions.Fire))
{
Fire();
return;
}
else if (Input.HasAction(Actions.Move))
{
Move(Input.Axis);
return;
}
}
Now imagine that this method is called dozens of times in many places across the entirety of your project. And then the next day you decide that you need to call UpdatePhysics() method at the very end of your Update() method. In this case there are only 4 returns, it could be much worse in reality.
Then imagine that such decesions happen several times a day every day. Bad planning you may say? I might agree with you, but I do think that freedom of development is essential in modern coding. I don't think you should kill yourself trying to anticipate every turn your project might take before you start writing code.
One way to insure that problems like the one I described above never happen is to rewrite the method as follows:
public void Update()
{
UpdateMovement();
if (!IsIncapacitated)
{
if (IsInventoryOpened)
{
UpdateInventory();
}
else
{
if (Input.HasAction(Actions.Fire))
{
Fire();
}
else if (Input.HasAction(Actions.Move))
{
Move(Input.Axis);
}
}
}
}
In this case you can always add a line at the bottom and be sure it will always get called nomatter what.
So I wanted to ask if there is another approach that could allow for placing "return"-s wherever you wish while still being able to add extra code easily at the bottom of the method any time. Maybe there is any form of syntax in c# that does it for you? Or maybe there is a better coding practice that eliminates such problem?
UPDATE: As I started receiving answers, I realized that I need to clarify things a bit.
'try/catch/finally' is an overkill - I will never use them. They have severe performance penalty on catch(), they screw up 'Edit and continue' feature in Visual Studio and they just look ugly.
Idealy I need to be able to access local variables in the Update() method from any code I decide to add at the end of the method,
When I wrote the question, I already had an answer - nesting. My second code sample has no returns and, therefore I can add code to the very bottom of the method and it will work 100% of the time, while I will be able to use local variables. Nesting is bad though, and that is why I am here searching for a BETTER solution.
UPDATE 2: I was actually mistaken about try/catch because I did not know that you can skip catch alongside it's performance penalties and only have finally. However, this solution is still worse than the nesting solution provided in the question, because in your newly added finally block you no longer can use return statements. So basically you can do whatever you want when you write the method the first time, but once you extend it - you are back to nesting.
One simple suggestion is to wrap your function. For example:
public void UpdateCall()
{
Update();
AfterUpdate code goes here.
}
Using a try/finally block should work;
public void Update()
{
try
{
UpdateMovement();
if (IsIncapacitated)
return;
if (IsInventoryOpened)
{
UpdateInventory();
return;
}
if (Input.HasAction(Actions.Fire))
{
Fire();
return;
}
else if (Input.HasAction(Actions.Move))
{
Move(Input.Axis);
return;
}
}
finally
{
//this will run, no matter what the return value
}
}
The performance costs of using try/finally (not try/catch!) are minimal
You cannot use return in the finally block;
If you were able to return a different value from the Finally block,
this value would always be returned, whatever the outcome of the
instructions above. It just wouldn't make sense..
I suggest wrapping the code into try..finally block:
public void Update() {
try {
...
// you can return
if (someCondition)
return;
...
// throw exceptions
if (someOtherCondition)
throw...
...
}
finally {
// However, finally will be called rain or shine
}
}
You can use try-catch-finally (C#-Reference) without a catch block.
try
{
//your business logic here
}
finally
{
//will be called anytime if you leave the try block
// i.e. if you use a return or a throw statement in the try block
}
With the modern c# 8 syntax you may introduce some disposable 'ScopeFinalizer' object or name whatever you want:
public class ScopeFinalizer : IDisposable
{
private Action delayedFinalization;
public ScopeFinalizer(Action delayedFinalization)
{
this.delayedFinalization = delayedFinalization ?? throw new ArgumentNullException(nameof(delayedFinalization));
}
public void Dispose()
{
delayedFinalization();
}
}
//usage example
public async Task<bool> DoWorkAsyncShowingProgress()
{
ShowActivityIndicator();
using var _ = new ScopeFinalizer(() =>
{
// --> Do work you need at enclosure scope leaving <--
HideActivityIndicator();
});
var result = await DoWorkAsync();
HandleResult(result);
//etc ...
return true;
}
Useful link:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations
Don't use the returns as it makes your code smelly.
public void Update()
{
UpdateMovement();
if (IsIncapacitated){
return;
}
if (IsInventoryOpened)
{
UpdateInventory();
}
else if (Input.HasAction(Actions.Fire))
{
Fire();
}
else if (Input.HasAction(Actions.Move))
{
Move(Input.Axis);
}
}
Also, your second solution has too much nesting, also confusing and smelly.
A problem with the current approach is that it requires changes to the Update() method whenever we want to add a new action.
Another approach is to remove the hard-coding of the update actions and configure the class with a set of update actions.
From the code given here we have
Actions that always happen (e.g. UpdateMovement)
Actions that happen if a test is passed (e.g. UpdateInventory)
Actions that cause a return if they are executed (e.g. Fire())
We can encapsulate these in an interface
public interface IUpdateAction
{
bool ShouldUpdate();
// return true if we want this to be the last action to be executed
bool Update();
}
and wrap various actions and decisions in the class using
public class DelegateUpdateAction : IUpdateAction
{
private Func<bool> _updateAction;
private Func<bool> _shouldUpdateCheck;
public DelegateUpdateAction(Action action, bool isLastAction = false, Func<bool> shouldUpdateCheck = null)
: this(() =>
{
action();
return isLastAction;
},
shouldUpdateCheck)
{ }
public DelegateUpdateAction(Func<bool> updateAction, Func<bool> shouldUpdateCheck = null)
{
if(updateAction == null)
{
throw new ArgumentNullException("updateAction");
}
_updateAction = updateAction;
_shouldUpdateCheck = shouldUpdateCheck ?? (() => true);
}
public bool ShouldUpdate()
{
return _shouldUpdateCheck();
}
public bool Update()
{
return _updateAction();
}
}
To replicate the example we could use
public class Actor
{
private IEnumerable<IUpdateAction> _updateActions;
public Actor(){
_updateActions = new List<IUpdateAction>{
new DelegateUpdateAction((Action)UpdateMovement),
new DelegateUpdateAction((()=>{ }), true, () => IsIncapacitated),
new DelegateUpdateAction((Action)UpdateInventory, true, () => IsInventoryOpened),
new DelegateUpdateAction((Action)Fire, true, () => Input.HasAction(Actions.Fire)),
new DelegateUpdateAction(() => Move(Input.Axis), true, () => Input.HasAction(Actions.Move))
};
}
private Input Input { get; set; }
public void Update()
{
foreach(var action in _updateActions)
{
if (action.ShouldUpdate())
{
if (action.Update())
break;
}
}
}
#region Actions
private bool IsIncapacitated { get; set; }
private bool IsInventoryOpened { get; set; }
private void UpdateMovement()
{
}
private void UpdateInventory()
{
}
private void Fire()
{
}
private void Move(string axis)
{
}
#endregion
}
The actions are executed in the order in which they are registered, so this gives us the ability to inject a new action into the execution sequence at any point.
UpdateMovement() always happens and doesn't return
IsIncapacitated() is a test with a null action. It returns if executed so we get our 'do-nothing-else-if-incapacitated' behaviour
UpdatedInventory() occurs if the inventory is open and then returns
Each of the HasAction checks return if executed.
Note If I have read the question better before writing the code I would have reversed the defaults as most actions seem to be 'return if executed'.
If we need to add 'UpdatePhysics()', we add a method to the class and add an entry in the appropriate place in the list of update actions. No changes to the Update method.
If we have derived classes with different actions we can add the facility to add (or remove) actions in the derived classes and either inherit and modify the default actions or replace them with a different set.
After seeing the other solutions I can't think of a truly dynamic solution that has only the functions you want to call in the update loop.
Here are some ideas though I doubt any of them are better than making a good design. Joe C has the correct idea of how you should structure this kind of thing.
You could make a container of actions that need to be performed each update loop. Remove and add specific actions depending on the changes to circumstances. Such as a IsNowIncapacitated event that remove the Handling action from the list. Though I have little experience with actions, I believe you can set up delegates that the actions point to. Not sure what the cost to performance is.
A temporary thing you could do so you can keep adding logic is have your return statements return a void function with some constant logic you want performed, though all it really will do is separate your update code between two methods. It is not very neat or as efficient as structuring your code appropriately like in Joe C's example.
public void PostUpdate()
{
//stuff that always happens
PhysicsUpdate();
}
public void Update()
{
UpdateMovement();
if (IsIncapacitated)
return PostUpdate();
if (IsInventoryOpened)
{
UpdateInventory();
return PostUpdate();
}
}
I'm working on a method which uses reflection to call another method. That "other method" can, however, throw an exception and I'd like to propagate that exception with it's original stack information and InnerException. That is simply because the method that uses reflection is not supposed to handle the exception, the caller should.
Here's a simplified version of the code:
public static bool Test() {
try {
return (bool) typeof(Program).GetMethod("OtherMethod").Invoke(null, null);
} catch(TargetInvocationException ex) {
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
}
public static bool OtherMethod() {
throw new InvalidOperationException();
}
That code obviously won't compile, since the Test method (according to the compiler) doesn't always return a value.
I could add a return false after the ExceptionDispatchInfo.Capture but I was wondering if there's a nicer way of achieving the same thing. Without writing the redundant return false.
I know it's kind of a nitpick question, but I can't help wondering. Plus, redundant code gives me an itch :P
There is one other option: instead of adding a redundant return false; you could add a redundant throw;.
You then don't need to make up a return value. (OK, not a big deal for a bool)
The simplest solution that doesn't give you redundant or duplicated code is to only put things inside your try that are actually going to throw. Creating your bool, assigning it false and returning it are all "safe" operations, so leave them outside the try.
public static bool Test()
{
bool returnValueOfInvoke = false;
try
{
returnValueOfInvoke = (bool)typeof(Program).GetMethod("OtherMethod").Invoke(null, null);
}
catch(TargetInvocationException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
return returnValueOfInvoke;
}
public static void OtherMethod()
{
throw new InvalidOperationException();
}
I ran across a pattern in a codebase I'm working on today that initially seemed extremely clever, then later drove me insane, and now I'm wondering if there's a way to rescue the clever part while minimizing the insanity.
We have a bunch of objects that implement IContractObject, and a class InvariantChecker that looks like this:
internal class InvariantChecker : IDisposable
{
private IContractObject obj;
public InvariantChecker(IContractObject obj)
{
this.obj = obj;
}
public void Dispose()
{
if (!obj.CheckInvariants())
{
throw new ContractViolatedException();
}
}
}
internal class Foo : IContractObject
{
private int DoWork()
{
using (new InvariantChecker(this))
{
// do some stuff
}
// when the Dispose() method is called here, we'll throw if the work we
// did invalidated our state somehow
}
}
This is used to provide a relatively painless runtime validation of state consistency. I didn't write this, but it initially seemed like a pretty cool idea.
However, the problem arises if Foo.DoWork throws an exception. When the exception is thrown, it's likely that we're in an inconsistent state, which means that the InvariantChecker also throws, hiding the original exception. This may happen several times as the exception propagates up the call stack, with an InvariantChecker at each frame hiding the exception from the frame below. In order to diagnose the problem, I had to disable the throw in the InvariantChecker, and only then could I see the original exception.
This is obviously terrible. However, is there any way to rescue the cleverness of the original idea without getting the awful exception-hiding behavior?
I don't like the idea of overloading the meaning of using in this way. Why not have a static method which takes a delegate type instead? So you'd write:
InvariantChecker.Check(this, () =>
{
// do some stuff
});
Or even better, just make it an extension method:
this.CheckInvariantActions(() =>
{
// do some stuff
});
(Note that the "this" part is needed in order to get the C# compiler to look for extension methods that are applicable to this.) This also allows you to use a "normal" method to implement the action, if you want, and use a method group conversion to create a delegate for it. You might also want to allow it to return a value if you would sometimes want to return from the body.
Now CheckInvariantActions can use something like:
action();
if (!target.CheckInvariants())
{
throw new ContractViolatedException();
}
I would also suggest that CheckInvariants should probably throw the exception directly, rather than just returning bool - that way the exception can give information about which invariant was violated.
This is a horrid abuse of the using pattern. The using pattern is for disposing of unmanaged resources, not for "clever" tricks like this. I suggest just writing straight forward code.
If you really want to do this:
internal class InvariantChecker : IDisposable
{
private IContractObject obj;
public InvariantChecker(IContractObject obj)
{
this.obj = obj;
}
public void Dispose()
{
if (Marshal.GetExceptionCode() != 0xCCCCCCCC && obj.CheckInvariants())
{
throw new ContractViolatedException();
}
}
}
Instead of this:
using (new InvariantChecker(this)) {
// do some stuff
}
Just do this (assuming you don't return from do some stuff):
// do some stuff
this.EnforceInvariants();
If you need to return from do some stuff, I believe some refactoring is in order:
DoSomeStuff(); // returns void
this.EnforceInvariants();
...
var result = DoSomeStuff(); // returns non-void
this.EnforceInvariants();
return result;
It's simpler and you won't have the problems you were having before.
You just need a simple extension method:
public static class InvariantEnforcer {
public static void EnforceInvariants(this IContractObject obj) {
if (!obj.CheckInvariants()) {
throw new ContractViolatedException();
}
}
}
Add a property to the InvariantChecker class that allows you to suppress the check/throw.
internal class InvariantChecker : IDisposable
{
private IContractObject obj;
public InvariantChecker(IContractObject obj)
{
this.obj = obj;
}
public bool Suppress { get; set; }
public void Dispose()
{
if (!this.Suppress)
{
if (!obj.CheckInvariants())
{
throw new ContractViolatedException();
}
}
}
}
internal class Foo : IContractObject
{
private int DoWork()
{
using (var checker = new InvariantChecker(this))
{
try
{
// do some stuff
}
catch
{
checker.Suppress = true;
throw;
}
}
}
}
If you current problem is to get original exception - go to Debug -> Exceptions and check "thrown" for all CLR exceptions. It will break when exception is thrown and as result you'll see it first. You may need to also turn off tools->options->debug->"my code only" option if exceptions are throw from "not your code" from VS point of view.
What is needed to make this nice is a clean means of finding out whether an exception is pending when Dispose is called. Either Microsoft should provide a standardized means of finding out at any time what exception (if any) will be pending when the current try-finally block exits, or Microsoft should support an extended Dispose interface (perhaps DisposeEx, which would inherit Dispose) which would accept a pending-exception parameter.