Note that there are some explanatory texts on larger screens.

plurals
  1. POuse runtime type (in c#) for logic flow
    primarykey
    data
    text
    <p>This question is similar to (a subset of) <a href="https://stackoverflow.com/questions/447947/is-type-checking-ever-ok">this question</a></p> <p>In this case it is using runtime type to distinguish between a success and a failure returned results.</p> <p>Quite often I see following pattern:</p> <pre><code>public struct Result { public boolean IsSuccess { get;set;} public string ErrorMessage {get;set;} public int Value {get;set;} } ... Result result = someObject.SomeMethod(); if (result.IsSuccess) DoSomething(result.Value); else handleError(result.ErrorMessage); </code></pre> <p>I think that following is more natural, and expresses the intention more clear (in my opinion):</p> <pre><code>public abstract class Result { } public sealed class Failure : Result { public string ErrorMessage { get; set; } } public sealed class Success : Result { public int Value { get; set; } } ... Result result = someObject.SomeMethod(); if (result is Success) DoSomething((result as Success).Value); else if (result is Failure) handleError((result as Failure).ErrorMessage); </code></pre> <p>Also note that .Net (and many other languages) use this pattern in try-catch block with multiple catch clauses (where exception type selects a catch block).</p> <p><strong>EDIT:</strong> this pattern (i.e. relying on runtime type) is identical to discriminated unions of F#, the difference is that in F# it is native, and in C# it is emulated using constructs meant for different purposes.</p> <p><strong>EDIT:</strong> I think my main issue with first code is a code smell "partially initialized object". In 100% of cases only half of the object will be initialized. It also <em>almost</em> violates ISP, "almost" because once .IsSuccess is evaluated only part of the object will be used henceforth (if it is success only .Result is used, if it is an error - only error properties are used). Run-type checking solution does not have those issues.</p> <p><strong>So the question is:</strong> what are the issues with using this pattern? I am especially interested in issues from following perspectives: maintainability, readability, testability, conceptual purity, and OOP/OOD.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload