views:

207

answers:

5
+13  A: 

The function checkAge should only take in the minimum amount of information needed to perform it's job. Adding anything else just creates an artificial dependency. If only an int is needed then that is the solution I should take.

JaredPar
Excelent Jared, so I should keep in mind give the minimun information needed.- Sometimes I need to pass 2 ints, I should then give to the function 2 ints and so on right?
MRFerocius
@MRFerocious, I would create 2 functions. The version that only needs 1 `int` and another which accepts 2 `int`s and has a distinctly different behavior
JaredPar
This principle is called the Law of Demeter: http://en.wikipedia.org/wiki/Law_of_Demeter
Mike Daniels
Thanks Mike!!! I will take a look at it :D
MRFerocius
+11  A: 

I would argue that in this case, the answer is probably neither. Either "Age" would be factored out into its own class, or if the operation is context-specific with Person, it would be found inside the Person class itself.

Dave Markle
+1  A: 

Follow the law of demeter for functions. Basically the law states that entities should be loosely coupled. Ask yourself the following question, should a computer object know about a person object? In this case, maybe all you are doing inside checkAge is checking an int value. If that is the case then what makes you think passing the entire object is needed? Simply pass the person age and take it in as an int in this case.

So prefer

public void checkAge(int n)
JonH
+3  A: 

with the information given, neither solution is good

the first solution requires the Computer class to know about Person.Age, for no apparent reason

the second attaches a method to the Computer class that has nothing to do with the properties of the Computer object

some context would be helpful - if this is a validation, then CheckAge belongs to the Person class (with possibly an IsAgeAcceptable property)

Why is the Computer checking the age of a Person? The answer to this determines what makes sense...

Steven A. Lowe
@Steven A. Lowe - I think the OP is just giving an example. I'm *sure* or hope that he doesn't really have a `checkAge` function within the Computer class.
JonH
hahaha Guys, of course this is just an example. I´m asking this because Im using Linq and I need to pass some ids, but in some cases I have 3, so I decided to pass the objects.- So I will go for passing just the ints.
MRFerocius
A: 

I would like to point out that when passing a reference, the reference is a 32 bit integer while a data type is copied. So if your value type is larger that a 32bit int, pass by reference if performance or memory is any sort of issue.

Brian Leahy