Question

I have a doubt about if there are some recommendations for call directly an attribute in a class

I think that in OOP you always should call an attribute by the get method.

For example:

On set

public setAtribute(Atribute atr){ this.atr = atr;}

On get

 public Atribute getAtribute(){ return this.atr;}

On the constructor

public Constructor(Attribue atr){
    setAttribute(atr);
}

If the attribute is injected in the super class I use this way to call it, on inherits class:

@Inject
protected Attribute atr;

public Attribute getAttribute(Attribute atr){
    return atr;
}

I.E. I prefer to use always get and set in OOP to get access to the attributes.

But in my work there is a debate because there are people that not like this way. Because you can wrote the following code:

getAttribute().callSomeFunctionality();

But I prefer these instead of:

this.callSomeFunctionality();

And I think that this not break the Demeter´s Law because is a variable class.

What do you think about that?

Is the best use always the get and set function, or there are other cases to call directly to attribute.

There is some of the literature about this?

Thanks

Was it helpful?

Solution

Generally, the point of OOP is that you don't need access to the attribute.
Think about what you want to do with the attribute - whatever that is, should potentially be a method of the class, so you should call that method to do it, instead of getting the attribute value and doing it yourself.

There are exceptions, of course, but if all your 'classes' are only collections of related attributes, and the usage is coded outside of them, it's not OOP.

Licensed under: CC-BY-SA with attribution
scroll top