How to create two sequences without relying on side effects? - c#

Suppose you have to process a sequence of InputType that produces two sequences one of type OutputType and the other of type ErrorType.
A basic implementation could be:
class SeqProcessor {
private IEnumerable<ErrorType> errorTypes;
public SeqProcessor()
{
this.errorTypes = Enumerable.Empty<ErrorType>;
}
public IEnumerable<ErrorType> Errors
{
get { return this.errors; }
}
public IEnumerable<OutputType> ProcessItems(IEnumerable<InputType> inputTypes)
{
yield return new OutputType();
if (err) this.errorTypes = this.errorTypes.Concat(new ErrorType());
yield return new OutputType();
yield return new OutputType();
if (err) this.errorTypes = this.errorTypes.Concat(new ErrorType());
// ...
yield break;
}
}
I see these two alternatives for example:
Use a common interface (eg. IProduct) between OutputType and ErrorType and let ProcessItems return IEnumerable<IProduct> (than discriminate using Linq).
Define a subclass of ErrorType called NoError and let ProcessItems return tuples IEnumerable<Tuple<OutputType, ErrorType>> (if no error, NoError will be used in the tuple).
Edit:
Since ErrorType are semantically different from OutputType, mixing these types could be a violation of Single Responsibility Principle.
Can the use of a delegate be an acceptable alternative design:
class SeqProcessor {
public IEnumerable<OutputType> ProcessItems(
IEnumerable<InputType> inputTypes,
Action<ErrorType> onError)
{
yield return new OutputType();
// ...
onError(new ErrorType());
}
}
Which approach do you use in such cases?

The second approach suggests that a NoError instance is a specialization of a NoError; this would rarely be true in practice. More likely the shared functionality between the two is small, making the first approach better.

Depending on what exactly you want to achieve, I see multiple possible solutions here:
Stay with the original implementation (where I would replace private IEnumerable<ErrorType> errorTypes but something that allows you to determine the item the error belongs to). In this context, the errors you are encountering would have the significance of a warning (which is why I would also prefer the name Warning) because they are separated from the actual result.
Using a common interface for both result types (that is, output and error) would only make sense if other functions consuming the resulting list could really make use of the error output. I doubt that this is what you intended but imho, this would be valid design choice.
As Pieter pointed out, having a sub-class NoError of ErrorType would really be nasty. However, a nicer solution would be using ResultType as a base for the types NoError and Error. That way, you really have specialization of the base class. Still, I wonder that the output will contain in case of an error. The original element? A processed, but invalid element? Null? Depending on what you want to achieve, this could be reasonable, but this is hard to tell from the given information and, to be honest, I doubt that is what you want.
The OnError is good practice in many contexts because it allows for great flexibility. However, you will still have to think about what will be the corresponding entry in the result in such a case. Imho, it will probably be the best choice to simply leave it out in order to avoid the treatment of either null or either special values.
All in all, it seems like the OnError approach seems to be most promising, even though additional information may drive you towards one of the other mentioned approaches.

Related

Reusing the same function by casting, or duck typing different object types

In a .NET application, I'm consuming two remote WCF services which both have a definition for the "same" object: CoreService.Customer and ProductService.Customer.
The "same" is deliberately put in quotes; from a namespace perspective they are two different entities. However, this is pure because of the way the services are generated/consumed. In this situation it is is a given fact that both objects originate from the same library in the backend system.
In a specific scenario I need to extract stuff from both the object types. I have a single function which is originally built for one particular instance:
private static string _ExtractFoo(CoreService.Customer customer) {
// removed for the sake of brevity
return string.Empty;
}
What I want is actually to reuse the same operation, by providing an overload and by the ways of casting or boxing simply try to convince both compiler and runtime that this will just work (think simply duck typing if you will).
The following scenario's do not work:
private static string _ExtractFoo(ProductService.Customer customer) {
// #1 - Cast, results in error:
// Cannot convert type ... via a built-in conversion
return _ExtractFoo((CoreService.Customer) customer);
// #2 - Safe cast, results in error:
// Cannot convert type ... via a built-in conversion
return _ExtractFoo(customer as CoreService.Customer);
// #3 - Works for compiler, breaks at runtime where 'casted' is null
dynamic d = customer;
var casted = d as CoreService.Customer;
return _ExtractFoo(casted);
}
A simple fix that does work is serializing to json first:
private static string _ExtractFoo(ProductService.Customer customer) {
// awkward hack - but it blends!
var serialized = JsonConvert.SerializeObject(customer);
var deserialized = JsonConvert.DeserializeObject<CoreService.Customer>(serialized);
return _ExtractFoo(deserialized);
}
The fact that this works makes sense, considering the properties and values of both objects are guaranteed to be a match. Albeit, this is expensive and seems quite unnecessary.
Another option would be to use an implicit conversion operator. However, considering the objects are service generated I'm not quite seeing how to extend both objects with an operator.
The main point is not having a debate whether or not this is best practice. Nor how to find alternatives like reusing the same shared objects between different service references. I'm quite aware of the awkwardness of this hack. It suffices to say that I find it an interesting challenge from a language perspective.
And that brings me to the actual question: is there a more elegant way to fool the compiler into swallowing this or, better put, making a less expensive cast/boxing between two "different but the same" objects, allowing me to reuse the _ExtractFoo() implementation?
Update I - Having the external webservice use a common interface is not an option. Also, it might be good to know that the Customer object has quite a deep hierarchy of nested properties and child objects; using something like AutoMapper, or a manual map, would be cumbersome (not to mention error prone).
Update II - For the sake of future reference, I attempted to explain that my problem/question is how I can modify the _ExtractFoo() method - or its implementation - so it can be applied to both CoreService.Customer and ProductService.Customer (taken everything above into consideration). It is definitely not intended as an open question in the sense of "please list all other alternatives", although what is provided as answer is in my opinion certainly viable as options.
Off the top of my head, your options are:
Get both of the source classes to implement the same interface and pass that around instead of the concrete types. This would be the preferable option but I'm guessing not possible here.
Deserialize and serialize back to convert between types. You already have this code, but like you say it may be slow.
Use a mapping library such as AutoMapper to convert between types. This is very fast but requires you bring in an external library from Nuget (I've used AutoMapper many times)
Manually map the properties yourself. This would probably be the fastest code but pretty awful to write.
Use dynamic all the way down the chain, not just at the top. You lose compile time type checking, but it should be reasonably fast. For example, instead of having a function like this:
public static string _ExtractFoo(ProductService.Customer customer)
{
return customer.DoSomethingExciting();
}
You would have this:
public static string _ExtractFoo(dynamic customer)
{
return customer.DoSomethingExciting();
}
You could, if you wanted, add some checking to ensure that customer is either ProductService.Customer or CoreService.Customer if you want some safety.

How does 'out' (parameter) work? [duplicate]

If we want to get a value from a method, we can use either return value, like this:
public int GetValue();
or:
public void GetValue(out int x);
I don't really understand the differences between them, and so, don't know which is better. Can you explain me this?
Thank you.
Return values are almost always the right choice when the method doesn't have anything else to return. (In fact, I can't think of any cases where I'd ever want a void method with an out parameter, if I had the choice. C# 7's Deconstruct methods for language-supported deconstruction acts as a very, very rare exception to this rule.)
Aside from anything else, it stops the caller from having to declare the variable separately:
int foo;
GetValue(out foo);
vs
int foo = GetValue();
Out values also prevent method chaining like this:
Console.WriteLine(GetValue().ToString("g"));
(Indeed, that's one of the problems with property setters as well, and it's why the builder pattern uses methods which return the builder, e.g. myStringBuilder.Append(xxx).Append(yyy).)
Additionally, out parameters are slightly harder to use with reflection and usually make testing harder too. (More effort is usually put into making it easy to mock return values than out parameters). Basically there's nothing I can think of that they make easier...
Return values FTW.
EDIT: In terms of what's going on...
Basically when you pass in an argument for an "out" parameter, you have to pass in a variable. (Array elements are classified as variables too.) The method you call doesn't have a "new" variable on its stack for the parameter - it uses your variable for storage. Any changes in the variable are immediately visible. Here's an example showing the difference:
using System;
class Test
{
static int value;
static void ShowValue(string description)
{
Console.WriteLine(description + value);
}
static void Main()
{
Console.WriteLine("Return value test...");
value = 5;
value = ReturnValue();
ShowValue("Value after ReturnValue(): ");
value = 5;
Console.WriteLine("Out parameter test...");
OutParameter(out value);
ShowValue("Value after OutParameter(): ");
}
static int ReturnValue()
{
ShowValue("ReturnValue (pre): ");
int tmp = 10;
ShowValue("ReturnValue (post): ");
return tmp;
}
static void OutParameter(out int tmp)
{
ShowValue("OutParameter (pre): ");
tmp = 10;
ShowValue("OutParameter (post): ");
}
}
Results:
Return value test...
ReturnValue (pre): 5
ReturnValue (post): 5
Value after ReturnValue(): 10
Out parameter test...
OutParameter (pre): 5
OutParameter (post): 10
Value after OutParameter(): 10
The difference is at the "post" step - i.e. after the local variable or parameter has been changed. In the ReturnValue test, this makes no difference to the static value variable. In the OutParameter test, the value variable is changed by the line tmp = 10;
What's better, depends on your particular situation. One of the reasons out exists is to facilitate returning multiple values from one method call:
public int ReturnMultiple(int input, out int output1, out int output2)
{
output1 = input + 1;
output2 = input + 2;
return input;
}
So one is not by definition better than the other. But usually you'd want to use a simple return, unless you have the above situation for example.
EDIT:
This is a sample demonstrating one of the reasons that the keyword exists. The above is in no way to be considered a best practise.
You should generally prefer a return value over an out param. Out params are a necessary evil if you find yourself writing code that needs to do 2 things. A good example of this is the Try pattern (such as Int32.TryParse).
Let's consider what the caller of your two methods would have to do. For the first example I can write this...
int foo = GetValue();
Notice that I can declare a variable and assign it via your method in one line. FOr the 2nd example it looks like this...
int foo;
GetValue(out foo);
I'm now forced to declare my variable up front and write my code over two lines.
update
A good place to look when asking these types of question is the .NET Framework Design Guidelines. If you have the book version then you can see the annotations by Anders Hejlsberg and others on this subject (page 184-185) but the online version is here...
http://msdn.microsoft.com/en-us/library/ms182131(VS.80).aspx
If you find yourself needing to return two things from an API then wrapping them up in a struct/class would be better than an out param.
There's one reason to use an out param which has not already been mentioned: the calling method is obliged to receive it. If your method produces a value which the caller should not discard, making it an out forces the caller to specifically accept it:
Method1(); // Return values can be discard quite easily, even accidentally
int resultCode;
Method2(out resultCode); // Out params are a little harder to ignore
Of course the caller can still ignore the value in an out param, but you've called their attention to it.
This is a rare need; more often, you should use an exception for a genuine problem or return an object with state information for an "FYI", but there could be circumstances where this is important.
It's preference mainly
I prefer returns and if you have multiple returns you can wrap them in a Result DTO
public class Result{
public Person Person {get;set;}
public int Sum {get;set;}
}
You should almost always use a return value. 'out' parameters create a bit of friction to a lot of APIs, compositionality, etc.
The most noteworthy exception that springs to mind is when you want to return multiple values (.Net Framework doesn't have tuples until 4.0), such as with the TryParse pattern.
You can only have one return value whereas you can have multiple out parameters.
You only need to consider out parameters in those cases.
However, if you need to return more than one parameter from your method, you probably want to look at what you're returning from an OO approach and consider if you're better off return an object or a struct with these parameters. Therefore you're back to a return value again.
I would prefer the following instead of either of those in this simple example.
public int Value
{
get;
private set;
}
But, they are all very much the same. Usually, one would only use 'out' if they need to pass multiple values back from the method. If you want to send a value in and out of the method, one would choose 'ref'. My method is best, if you are only returning a value, but if you want to pass a parameter and get a value back one would likely choose your first choice.
I think one of the few scenarios where it would be useful would be when working with unmanaged memory, and you want to make it obvious that the "returned" value should be disposed of manually, rather than expecting it to be disposed of on its own.
Additionally, return values are compatible with asynchronous design paradigms.
You cannot designate a function "async" if it uses ref or out parameters.
In summary, Return Values allow method chaining, cleaner syntax (by eliminating the necessity for the caller to declare additional variables), and allow for asynchronous designs without the need for substantial modification in the future.
As others have said: return value, not out param.
May I recommend to you the book "Framework Design Guidelines" (2nd ed)? Pages 184-185 cover the reasons for avoiding out params. The whole book will steer you in the right direction on all sorts of .NET coding issues.
Allied with Framework Design Guidelines is the use of the static analysis tool, FxCop. You'll find this on Microsoft's sites as a free download. Run this on your compiled code and see what it says. If it complains about hundreds and hundreds of things... don't panic! Look calmly and carefully at what it says about each and every case. Don't rush to fix things ASAP. Learn from what it is telling you. You will be put on the road to mastery.
Using the out keyword with a return type of bool, can sometimes reduce code bloat and increase readability. (Primarily when the extra info in the out param is often ignored.) For instance:
var result = DoThing();
if (result.Success)
{
result = DoOtherThing()
if (result.Success)
{
result = DoFinalThing()
if (result.Success)
{
success = true;
}
}
}
vs:
var result;
if (DoThing(out result))
{
if (DoOtherThing(out result))
{
if (DoFinalThing(out result))
{
success = true;
}
}
}
There is no real difference. Out parameters are in C# to allow method return more then one value, that's all.
However There are some slight differences , but non of them are really important:
Using out parameter will enforce you to use two lines like:
int n;
GetValue(n);
while using return value will let you do it in one line:
int n = GetValue();
Another difference (correct only for value types and only if C# doesn't inline the function) is that using return value will necessarily make a copy of the value when the function return, while using OUT parameter will not necessarily do so.
Please avoid using out parameters.
Although, they can make sense in certain situations (for example when implementing the Try-Parse Pattern), they are very hard to grasp.
Chances to introduce bugs or side effects by yourself (unless you are very experienced with the concept) and by other developers (who either use your API or may inherit your code) is very high.
According to Microsoft's quality rule CA1021:
Although return values are commonplace and heavily used, the correct application of out and ref parameters requires intermediate design and coding skills. Library architects who design for a general audience should not expect users to master working with out or ref parameters.
Therefore, if there is not a very good reason, please just don't use out or ref.
See also:
Is using "out" bad practice
https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1021
Both of them have a different purpose and are not treated the same by the compiler. If your method needs to return a value, then you must use return. Out is used where your method needs to return multiple values.
If you use return, then the data is first written to the methods stack and then in the calling method's. While in case of out, it is directly written to the calling methods stack. Not sure if there are any more differences.
out is more useful when you are trying to return an object that you declare in the method.
Example
public BookList Find(string key)
{
BookList book; //BookList is a model class
_books.TryGetValue(key, out book) //_books is a concurrent dictionary
//TryGetValue gets an item with matching key and returns it into book.
return book;
}
return value is the normal value which is returned by your method.
Where as out parameter, well out and ref are 2 key words of C# they allow to pass variables as reference.
The big difference between ref and out is, ref should be initialised before and out don't
I suspect I'm not going to get a look-in on this question, but I am a very experienced programmer, and I hope some of the more open-minded readers will pay attention.
I believe that it suits object-oriented programming languages better for their value-returning procedures (VRPs) to be deterministic and pure.
'VRP' is the modern academic name for a function that is called as part of an expression, and has a return value that notionally replaces the call during evaluation of the expression. E.g. in a statement such as x = 1 + f(y) the function f is serving as a VRP.
'Deterministic' means that the result of the function depends only on the values of its parameters. If you call it again with the same parameter values, you are certain to get the same result.
'Pure' means no side-effects: calling the function does nothing except computing the result. This can be interpreted to mean no important side-effects, in practice, so if the VRP outputs a debugging message every time it is called, for example, that can probably be ignored.
Thus, if, in C#, your function is not deterministic and pure, I say you should make it a void function (in other words, not a VRP), and any value it needs to return should be returned in either an out or a ref parameter.
For example, if you have a function to delete some rows from a database table, and you want it to return the number of rows it deleted, you should declare it something like this:
public void DeleteBasketItems(BasketItemCategory category, out int count);
If you sometimes want to call this function but not get the count, you could always declare an overloading.
You might want to know why this style suits object-oriented programming better. Broadly, it fits into a style of programming that could be (a little imprecisely) termed 'procedural programming', and it is a procedural programming style that fits object-oriented programming better.
Why? The classical model of objects is that they have properties (aka attributes), and you interrogate and manipulate the object (mainly) through reading and updating those properties. A procedural programming style tends to make it easier to do this, because you can execute arbitrary code in between operations that get and set properties.
The downside of procedural programming is that, because you can execute arbitrary code all over the place, you can get some very obtuse and bug-vulnerable interactions via global variables and side-effects.
So, quite simply, it is good practice to signal to someone reading your code that a function could have side-effects by making it non-value returning.

Avoiding ambiguous invocation error with generic types

I have a two way dictionary class that I am making to allow me to do a fast lookup in either direction.
My class looks (partially) like this:
public class DoubleDictionary<A,B>
{
private Dictionary<A, B> _forward;
private Dictionary<B, A> _backward;
public A this[B b]
{
get { return _backward[b]; }
set { _backward[b] = value; }
}
public B this[A a]
{
get { return _forward[a]; }
set { _forward[a] = value; }
}
}
I am using the array indexing operator in this example, but just about every method has two generic versions. It works great except in the case where A == B.
If I do
var foo = new DoubleDictionary<int, int>();
int x = foo[3];
It won't even compile because of an ambiguous indexer.
I understand why the compiler has a problem with this, and I agree that it should probably not be legal.
Lets assume I actually have a valid use case for wanting a DoubleDictionary<int,int>, and I arbitrarily choose that the array index should access the forward dictionary.
The solution I have arrived at to work around all of this is to abandon the slick indexing syntax for uniquely named methods for each direction. This makes it much less magic, and much less fun.
Is there any way to give the compiler hints to resolve the ambiguity without having to resort to uniquely named methods? I really like the idea of doing this with overloads and would like to keep it that way. I would prefer to do that in the class so the caller doesn't have to worry about it, but I imagine the caller will have to do some kind of reflection magic to make it work.
If its not possible I would be fine with the restraint that A cannot be the same as B. Is there any way to codify that, so that a declaration of DoubleDictionary<int,int> would not compile? I could throw an exception in the constructor, but it would be nice if it was caught at compile time.
Well, having the two indexers, if it were allowed, would be a monumentally bad design.
Having this dictionary:
var foo = new DoubleDictionary<int, int>();
foo.Add(3, 4);
foo.Add(2, 3);
and then doing:
foo[3]
would you expect to get 2? or 4? and why?
Better make the API clear.
You can always keep the indexers, but add the named methods as an auxiliary API - perhaps even via extension methods so you can bring them into play by adding a using directive...
There isn't any way to resolve the ambiguity as-is, given that it's an indexer that doesn't allow you to specify arguments and that the only way to relate type parameters in generic constraints is by inheritance.
I think that a good compromise would be to use the indexer for forward look-ups and something like a GetKeyForValue(B value) method for backward look-ups.

A problem with exception handling for IEnumerable<T>, it's lazyness-dependent

I used to create interfaces with IEnumerable<T> as return type, whenever I want to specify that a particular output is read-only. I like it as it's minimalistic, hides implementation details and decouples a callee from a caller.
But recently a colleague of mine argued that IEnumerable<T> should be kept for scenarios which involve lazy evaluation only, as otherwise it's unclear for a caller method, where the exception handling should take it's place -- around a method call or around an iteration. Then for the eager evaluation cases with a read-only output I should use a ReadOnlyCollection.
Sounds quite reasonable for me, but what would you recommend? Would you agree with that convention for IEnumerable? Or are there better methods for exception handling around IEnumerable?
Just in case if my question is unclear, I made a sample class illustrating the problem. Two methods in here have exactly the same signature, but they require different exception handling:
public class EvilEnumerable
{
IEnumerable<int> Throw()
{
throw new ArgumentException();
}
IEnumerable<int> LazyThrow()
{
foreach (var item in Throw())
{
yield return item;
}
}
public void Run()
{
try
{
Throw();
}
catch (ArgumentException)
{
Console.WriteLine("immediate throw");
}
try
{
LazyThrow();
}
catch (ArgumentException)
{
Console.WriteLine("No exception is thrown.");
}
try
{
foreach (var item in LazyThrow())
{
//do smth
}
}
catch (ArgumentException)
{
Console.WriteLine("lazy throw");
}
}
}
Update 1. The question is not limited to ArgumentException only. It's about best practices for making friendly class interfaces, that tell you whether they return lazy evaluated result or not, because this influences the exception-handling approach.
The real problem here is the deferred execution. In the case of argument-checking, you can do this by adding a second method:
IEnumerable<int> LazyThrow() {
// TODO: check args, throwing exception
return LazyThrowImpl();
}
IEnumerable<int> LazyThrowImpl() {
// TODO: lazy code using yield
}
Exceptions happen; even for non-deferred result (List<T>, for example) you can get errors (perhaps if another thread adjusts the list while you are iterating). The above approach lets you do as much as possible ahead of time to reduce the unexpected side-effects of yield and deferred execution.
In theory, I agree with your colleague. If there is some 'work' to create the results, and that work may cause an exception, and you don't need lazy evaluation, then indeed making the result lazy will just complicate matters.
However in practice, there's no way you can look at the return type and infer anything too useful. Even if you made the return type ReadonlyCollection, it still might delay the evaluation and throw, for example (ReadonlyCollection is not sealed, so a subclass could explicitly implement the IEnumerable interface and do wacky things).
At the end of the day, the .Net type system is not going to help you reason much about the exception behavior of most objects.
I would, in fact, still choose to return a ReadonlyCollection rather than an IEnumerable, but because it exposes more useful methods (like O(1) access to the nth element) compared to IEnumerable. If you're going to produce a manifest collection backed by an array, you might as well give consumers back useful aspects of that. (You might also just return a 'fresh' array that the caller gets to own.)
I do not agree with your collegue. The documentation of the method shoul follow the standard an document which exceptions it might throw. Declaring the return type as IEnumerable does not make it read only. Whether or not it's read only dependts on the actual implementation of the interface being returned. The caller shouldnt rely on it being writable but that's very different from the collection being read only
Similar problem was discussed in Eric Lippert's posts:
http://blogs.msdn.com/ericlippert/archive/2007/09/05/psychic-debugging-part-one.aspx
http://blogs.msdn.com/ericlippert/archive/2007/09/06/psychic-debugging-part-two.aspx
However, I will not treat it as an argument against IEnumerable in general. To be honest, most times when collection I'm enumerating throws an exception I don't know what to do with it and basically it goes to some global error handler. Of course, I agree that the moment the exception is thrown may be confusing.

Is accepting Object as a parameter acceptable?

Let us say I have a textbox or any other form of input that asks for a social security number. I do want to note that the SSN is a pure example I simply thought of as of right now.
This input will naturally be stored as a string initially.
string s = Console.ReadLine();
Let us say I want to have a method that validates an SSN and it might be used throughout my code in all sorts of places. Heck, I might even call the method on a variable which has not been determined by user-input.
Is this acceptable?
public bool IsValidSSN(Object SSN)
{
int mySSN;
if(Int.Parse(SSN == false)
{
mySSN = Convert.toInt32(SSN);
}
...
}
Or would you guy insist that I ask for a specific datatype, e.g
public bool IsValidSSN(int SSN)
{
...
}
and therefor I am required to convert the input to the correct datatype BEFORE I call the method on it.
BTW: I am not asking how to do a proper IsValidSSN code :) I just wanted to give an example of what I meant when I said: Can I accept the Object datatype as a parameter or should I try to avoid it?
If you must accept an object I would at least have overloads of the method which take strongly typed parameters. Then have the object variants feed into these methods.
public bool IsValidSSN(object ssn) {
...
IsValidSSN(Convert.ToInt32(ssn));
...
}
public bool IsValidSSN(int ssn) {
...
}
It COMPLETELY depends on your design and where you want your validation to occur. It really fundamentally depends upon your overall architecture and your class hierarchy. It's not wrong to do it either way; just be sure that it's the way that fits with your architectural design.
I see no value in accepting an Object in this case. Think through how you expect that function to work. (Clearly you haven't, since the code you posted doesn't work). I think you're planning something like this:
if (SSN is string)
SSN = Convert.toInt32(SSN);
else if (SSN is TextBox)
SSN = Convert.toInt32(SSN.Value);
else /* etc */
How is that better than:
bool isValidSSN(int SSN) { /* real valuation code */ }
bool IsValidSSN(String SSN) { return isValidSSN(Convert.toInt32(SSN)); }
bool IsValidSSN(TextBox SSN) { return isValidSSN(Convert.toInt32(SSN.Value)); }
The overloaded methods are simpler, and faster, since they more the decision on what to do from runtime to compile time.
In your above example it is far easier to create a typed IsValidSSN. Generally I find that typing reduces bugs and flexibility.
Under circumstances in which flexibility if paramount then using Object is probably the best choice, but expect to face a few cast clash exceptions in the logs.
For all other cases be strict with your typing, or write it in python.
Personally, I would make an SSN class and be able to ask that SSN if it was valid or not. It's important to have classes that represent principals in your business logic. This is very much, for example, what you might do with something that requires more validation like a credit card class. Handing around objects is not the best if you can avoid it and handing around something that is a principal in your business logic as a primitive is bad too (your architecture makes SSN1 + SSN2 = SSN3 perfectly valid, even though in business logic, it's nonsense).
In this instance, I would say it was unacceptable. What if the input has dashes, or some other separating character (eg: ###-##-####)? You obviously wouldn't be able to parse the value as an integer, but the value would still be valid. How about using a regular expression instead to ensure the value is what you've desired.
In terms of using the type "Object" as a parameter, this is completely valid in many instances. In fact, it is used throughout the .NET Framework (look at event delegates):
public void Control_MouseOver(object sender, MouseEventArgs e){}
This would be a simple case of Boxing/Unboxing, which was really the only way of performing "Generic" operations on variables until .NET 2.0.
You can also use Generics to solve this problem without the need for casting. If you create an interface that implements something like INumeric (I don't know if that is the actual interface) or IComparable you should be able to perform the operation in a more elegant fashion:
public bool IsValidSNN(INumeric SSN){}

Categories

Resources