OOP Newbie: direct access to fields or passing objects as parameters

Suppose Object1 needs information from Object2. I will say this in the Object2 property, but the information can also be a return value from the Object2 function. When I look at the code of others, I see that sometimes they will have a method in Object1 that will directly access the property. In other cases, I see people pass Object2 as a parameter in a method, and then access the property from the passed Object2 object.

These scenarios seem to me almost the same. Direct access to the property seems simpler. As a newbie, what do you think I should think about when deciding how Object1 should receive information from Object2? (When would I like to have an object parameter instead of directly accessing a property?)

Thanks - Al C.

+5
source share
6 answers

One problem with passing Object2 to Object1 is that you are creating a dependency between Object2 and Object1. The only way that Object1 can get the data it needs is by referencing Object2.

Now, sometimes you want it, but most of the time you do not. Thus, you are most likely better off simply passing the value you need as a parameter to the method rather than passing an instance of Object2.

+9
source

If a method requires only one property value from Object2, it would be better to pass this property value directly. If this method requires access to many properties or other Object2 objects, then calling Object2 would be appropriate.

- (.. ), Object2 , .

- Object1 Object 2 .

+3

.

, ; AppController, DataController MainWindowController. DataController.Data MainWindowController, . DataController MainWindowController DataController MainWindowController. , , AppController MainWindowController, DataController.

+2

, Object1 Object2. , , , . , : Object1 Object2 ( Object2 ) Object2? , , , .

, , , Object1 , Object2, , , Object1, , on Object2; , Object1 Object2 , Object1 Object2, ; .

+1

, , .

, , . , , , , .

, 5, 10, 100 , , .

+1

Encapsulation wikipedia.

[..] , .

+1

All Articles