C# – Pass the whole object to a method or just parts

cdesign-patternsobject-oriented-design

I have an object that has about 50 properties, but one of my methods only uses about 3 of these properties. Is it still better to pass the whole object or parts. A scenario would be were I am using Dapper to query a database to map data into a POCO object, but I only need a few of the properties, so I am faced with these two scenarios:

var car = db.Query<Car>("SELECT * FROM Car Where Id = @Id", new {Id}).FirstOrDefault();

Process(car);

Or

var car = db.Query<car>("SELECT VIN, Year, Color FROM Car Where Id = @Id", new {Id}).FirstOrDefault();

Process(car.VIN, car.Year, car.Color);

In the above case, does the fact that I am using Dapper matter? I know the less properties it has to map to the less time it takes. But at the same time, by only bringing back a set of properties, if I ever need something else, I will have to modify the query or add a new method to bring back what I want.

Best Answer

I have an object that has about 50 properties,

Stop! Go - right now - and fix this.

Of course you're going to run into functions that only use part of your object, when your object is doing everything under the sun. No object needs 50 independent properties. Certainly some of them can be organized into sub-objects. Those three that your function takes are a good candidate set.

should I pass the whole object to a function or just parts?

In the more general case, it depends. Best practices say to pass in just what you need. Best practices also say to code to an interface (in this case, the signature of the method). So this is one of those cases where you need to weigh the two best practices against the likelihood that they will come into play.

Does the method make sense to take the whole thing (since you might use other parts later)? Does the method make sense to the parts and not care that they are from independent sources?

And the other consideration is similar to the above advice: if you often find yourself taking bits from an object, it is a sign that those bits are their own cohesive object. Consider making them their own sub-object, or otherwise divvying up responsibilities to better align with how you're actually using the stuff.

Also, this answer is specifically about functions. If you're working across communication boundaries, you will often want to/need to cut down your data size. Sending 50 fields across the wire when you only need 3 is more troublesome there.

Related Topic