Pass by value is often safer than pass by reference, because you cannot accidentally modify the parameters to your method/function. This makes the language simpler to use, since you don't have to worry about the variables you give to a function. You know they won't be changed, and this is often what you expect.
However, if you want to modify the parameters, you need to have some explicit operation to make this clear (pass in a pointer). This will force all your callers to make the call slightly differently (&variable
, in C) and this makes it explicit that the variable parameter may be changed.
So now you can assume that a function will not change your variable parameter, unless it is explicitly marked to do so (by requiring you to pass in a pointer). This is a safer and cleaner solution than the alternative: Assume everything can change your parameters, unless they specifically say they can't.
There is one, very important distinction that I think that you're overlooking.
The code you provided is for three things: the declaration of a variable, the instantiation of an object, and initializing that variable with that object.
There is no interface implementation here. Customer
needs to implement ICustomer
(or do one or two other tricks) for that to compile successfully, but there's no actual implementation going on here.
Now that the terminology is out of the way, let's focus on the meat of the problem: is one better?
This sort of thing falls into the realm of program to an interface. When you declare your variable, you need to give it a type. That type should define the sort of things the variable can do. It is a contract you make with future programmers (or yourself) that oCustomer
can only do these sorts of things. You should decide this contract regardless of the source you use to initialize the variable.
If this variable only needs the interface, then using the interface as its type is clearly defining what it can (and can't) do. If this variable really needs to be a full Customer
, then double check that you really need that. If you do, then go ahead and make it a Customer
. This provides clear communication to future programmers (or you) that the variable needs to be of that type. And if the variable is just some placeholder for your initializer; if its type doesn't really matter, then use var
.
The benefits of programming to an interface are described in depth in the link above, but they boil down to allowing you to be flexible. Software inevitably changes. By coding to an interface, you allow this code to remain blissfully unaware when Customer
changes - or if you need tomorrow to initialize oCustomer
with a VipCustomer
instead.
This sort of thing applies in many places throughout programming, not just variable declarations.
Best Answer
The basic reasons come down to this:
Hence, references.