Programing tip: Developing without exceptions.
1 15 Mar 2016 18:25 by u/roznak
Life without exceptions can be simple and easy.
And I can guarantee you that if you get out of your comfort zone and get rid of exceptions in your project, then your project will massively simplify and become way more stable.
The trick is this:
~~~ public class BasicError { public int ErrorCode {get; set} public string ErrorDescription {get:; set}
public bool HasError{ get { if (ErrorCode!=0) return true; return false; }
public bool IsSuccess{ get { return !HasError; } }
~~~
This is how you you use it.
~~~ public BasicError SomeMethod() { // Do something that fails return new BasicError() {ErrorCode=1, ErrorDescription = ""}
else return new BasicError(); } ~~~
And an extended example
~~~ var result = SomeMethod() if (result.IsSuccess) result = SomeMethod2() if (result.IsSuccess) result = SomeMethod3() if (result.IsSuccess) result = SomeMethod4() return result; ~~~
Making it more interesting
~~~ public BasicError OtherMethod() {
BasicError result; do { BasicError CleanupResult;
result = SomeMethod() if (result.HasError) CleanupResult=Cleanup(); if (CleanupResult.HasError) { result=CleanupResult; break; } } while (result.HasError) return result; } ~~~
More variations
~~~ public BasicError GetDateoverShakyConnction()
var result = OpenURL() if (result.HasError) result = OpenBackupURL()
if (result.IsSuccess) result = DetectServiceType1() if (result.HasError) result = DetectServiceType2()
if (result.IsSuccess) result = ExecuteWhateverYouNeed()
return result; ~~~
And the grand FINALY!!!
~~~ public void Getdata() { var result= GetDateoverShakyConnection() if (result.HasError) Log.Error("We tried hard but failed with error: "+ result.ErrorCode+" , result.Description: "+) } ~~~
Clear and readable code, that can be easily extended, modified, recycled, reshaped...
Don't take my word for it, try it yourself.
0 comments
No comments archived.