Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP Newbie: Accessing Fields Directly vs. Passing Objects as Parameters

Tags:

oop

Suppose Object1 needs information from Object2. I'll say it's in an Object2 property, but the info could as easily be the return value from an Object2 function. When I look at others' code I see sometimes they will have a method in Object1 directly accessing the property. Other times I see people pass Object2 as a parameter in a method, and then access the property from the passed Object2.

These scenarios seem almost the same to me. Directly accessing the property seems simpler. As a newbie, what do you think I should think about when deciding how Object1 should get information from Object2? (When would I want to have an object parameter rather than directly accessing the property?)

Thanks -- Al C.

like image 734
Al C Avatar asked May 27 '09 17:05

Al C


1 Answers

One problem with passing Object2 to Object1 is that you create a dependency between Object2 and Object1. The only way that Object1 can obtain the data it needs is to have a reference to Object2.

Now, sometimes you want that, but most of the time you don't. So you're most likely better off simply passing the value you need as a parameter to the method, rather than passing the instance of Object2.

like image 148
Randolpho Avatar answered Sep 28 '22 01:09

Randolpho