It depends, and I try to discuss this by using a more real-world example.
For example, lets say you have a Person
object with attributes like FirstName
, Surname
, NameAffix
, DateOfBirth
, Gender
. And you are going to create some methods to process that data (for example, for a formatted report).
First, lets think of a method GetFullPersonNameFormatted
, which should return a combination of FirstName
, Surname
and NameAffix
in a specificially formatted string (assume that it does not make sense to put that method directly into the Person
class for some reasons). Shall you pass the attributes one-by-one or the whole Person
object? Well, I probably would pass the Person
object at a whole, since this method creates an abstractions on persons, and if the Person changes internally, I only want to change GetFullPersonNameFormatted
internally, not the calling code.
Now lets think of a method GetDateOfBirthFormatted
, it should return the date-of-birth in a specificially formatted way. Shall you pass the attribute, or the whole Person object? I probably would start with a more general method FormatDate(date)
, not specificially for Persons, which would be much more reusable that a method GetDateOfBirthFormatted(person)
, but it may also make sense to have additionally a
string GetDateOfBirthFormatted(Person person)
{
return FormatDate(person.DateOfBirth);
}
method for the same reason as in the first example: to create an abstraction on persons. If you really need that method, depends (for example, if there would be just one call to GetDateOfBirthFormatted
in your whole program, you may better avoid creating that method and directly use FormatDate(person.DateOfBirth)
instead.
So the answer for "should your method take the whole object or not?" depends mostly on "how much does your method need from that object?", but also on "what kind of abstraction you are going to create?". A big indicator for better using objects is when you have lots of methods getting the same group of attributes over and over again, for example, when you pass FirstName
, Surname
, NameAffix
into several methods. This may also be an indicator that these attributes belong to a newly-to-create class (think of a program where you don't have a Person class so far: methods like that may be an indicator that you should create one).
There can be another reason not to pass objects, but only attributes: decoupling. Lets say the GetFullPersonNameFormatted
is in module A, and the class definition of Person
is in module B, and the call to GetFullPersonNameFormatted
is in module C which references A and B. If you do not want to reference B from A, to keep those two modules completely independent from each other, then you need to define GetFullPersonNameFormatted
without any Person
parameter.
To summarize: it is not always a simple black-and-white decision, and there are different shades of grey.