Reputation: 883
In my current Net Framework 4 project, I did this:
This looks in a following manner:
MyClassName obj = MyClassName.GetObject("Name").DoJob().Close();
where
this
and will throw a System.NullReferenceException
when GetObject fails, or anything inbetween fails.Problem is: Is it possible to design this in the way I want, without try-catch blocks? I want to have many, many one liners versus try - lineOfCode - catch
. Every line will be another object doing its specific task and destroying itself / being forgotten. I don't really need to use MyClassName obj =
part either.
Upvotes: 2
Views: 88
Reputation: 12849
Second option suggested by zerkms is to use some kind of Option
type instead of nullable value.
So, using Option library for C#. Your code could look something like:
// simplified skeleton
class MyClassName
{
private MyClassName() {}
public MyClassName GetObject(string name)
{
return new MyClassName();
}
public MyClassName DoJob() { return this; }
public MyClassName Close() { return this; }
}
Option<MyClassName> obj = MyClassName.GetObject("Name").ToOption().Select(x=>x.DoJob()).Select(x=>x.Close());
if (obj.HasValue)
{
// can work with obj.Value
}
else
{
// somewhere was null
}
Yeah, I agree there is some noise, but those are limits of the language.
Upvotes: 0
Reputation: 12849
Instead of returning null
value, you could return a null object as part of Null Object pattern.
In this case, this object would do nothing when DoJob
and Close
is called and just return itself.
The possible problem might be need to define some kind of simple class hierarchy to implement this pattern. Which might seem like overkill when you have just one class right now.
Upvotes: 3