Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for passing object

Tags:

c#

I have a little simple question.

Let's say I have a data object with about 10 properties, and I want to pass data from my object to a function. Most of the time I only need one of these values in the receiving function, and could just as well pass only that value (let's say an int). So what is the pros and cons with always sending the whole object vs only sending one of the contained values?

Is there a best practice?

like image 667
Markus Avatar asked Mar 13 '12 12:03

Markus


1 Answers

From a performance perspective, it's no problem to pass a whole object. In C# you only pass a reference to an object so there is no copying.

But compare the following two methods from a Unit Testing perspective:

decimal CalculatePrice(Customer customer);

or

decimal CalculatePrice(decimal productPrice, int numberOfItems);

The second one is much easier to understand and to test. This principle is called the Law Of Demeter.

The Law Of Demeter states that an object should only know about the things it really needs. So passing a complete Customer object only to access the Order property on it violates the Law Of Demeter.

like image 85
Wouter de Kort Avatar answered Oct 04 '22 05:10

Wouter de Kort