Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@property or self.property to set a property with an accessor?

Tags:

ruby

Which is better practice; manipulating properties with accessors by @property or self.property?

like image 742
Johannes Gorset Avatar asked Sep 26 '10 12:09

Johannes Gorset


People also ask

What is @property in Python used for?

The @property is a built-in decorator for the property() function in Python. It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.

What is an accessor property?

A data property has a value, which may or may not be writable, whereas an accessor property has a getter-setter pair of functions to set and retrieve the property value. The attributes of a data property are value , writable , enumerable , and configurable .

What does @property do in Objective C?

The goal of the @property directive is to configure how an object can be exposed. If you intend to use a variable inside the class and do not need to expose it to outside classes, then you do not need to define a property for it. Properties are basically the accessor methods.

What is the most pythonic way to use getters and setters?

Getters and Setters in python are often used when: We use getters & setters to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user.


1 Answers

If you are just using straight accessors, then stick to @property (unless you come from Python and are turned off by the @ sigil hehe) otherwise:

It's entirely up to you. But self.property can be useful in some circumstances where you need to ensure the property is initially set up:

def property
    @property ||= []
end

# don't need to check if @property is `nil` first
self.property << "hello"

Also beware that there is a slight overhead to using self.property over @property as self.property is a method call.

NOTE: The reason i'm using self.property over just property is because the corresponding setter method property= requires an explicit receiver: self.property=, so I choose to use the explicit receiver with both.

like image 161
horseyguy Avatar answered Sep 23 '22 22:09

horseyguy