What is the motivation of the properties?

I am a little confused why they have these languages. I am a Java programmer at the beginning of my career, so Java is the only language I wrote in, since I actually started, you know, get it.

So, in Java, of course, we have no properties, and we are writing the getThis () and setThat (...) methods.

What do we get with properties?

Thanks.

EDIT: another query: what naming conventions arise in languages ​​with properties?

+3
source share
12 answers

Which one looks more natural to you?

// A
person.setAge(25)
// B
person.age = 25;
// or
person.Age = 25; //depending on conventions, but that beside the point

Most people will answer B.

, ; , .

# , :

class Person
{
    public int Age
    {
        set
        {
            if(value<0)
                throw new ArgumentOutOfRangeException();

            OnChanged();
            age = value;
        }

        get { return age; }
    }

    private int age;
    protected virtual void OnChanged() { // ... }
}

, , , get/set; , .

+9

:

button.Location += delta;

:

button.setLocation(button.getLocation() + delta);
+7

Edit:

, . get/set . , , .

:

, , .

:

public class Foo
{
    public int bar;
}

"bar", :

public class Foo
{
    private int bar;

    public void setBar(final int val)
    {
        if(val <= 0)
        {
            throw new IllegalArgumentException("val must be > 0, was: " + val);
        }

        bar = val;
    }

    public int getBar()
    {
        return (bar);
    }
}

set/get . , .

- /get geterated / ( ).

+6

:

  • cleaned/terser;
  • () ().
+3

Java .

(#) .. /comprehend.

, .

, , , , :)

+2

, . , , , getter/setter. , , , . # 3.0 , - , / - :

public string Prop { get; set; }

, , , .

public string Prop { get; private set; }

getter/setter, , .

+1

- , . , , , , .

- , . Java . , , . , hasSomething isSomething getSomething.

, , .

, get set .

+1

- 2 " ", , ( ) ( ), , , .

, , ,

int x = foo.y;

int x = foo.y();

, "" "".

+1

/ . , , , , .

0

.

, , .

, - . - , .

0

- . , .

0

, (.. , ). GUI- (JGoodies, JSR295), , , .

, , , , X A Y B '. : A.x ↔ B.y

, Java. "x" "y" . ( ). , A. "x" ↔ B. "y"

, .

, . , 3 , - . :

public void setFoo(Foo foo){
  Foo old = getFoo();
  this.foo = foo;
  changeSupport.firePropertyChange("foo", old, foo);
}

, , .

, . (, , , , PropertyChangeSupport 3 , ). , ( , Property) .

- -, (- registerFormProperties (myObject.firstname, myObject.lastname, someOtherObject.amount), - . , , , ( , ).

, , , - - , .

0

Source: https://habr.com/ru/post/1704097/


All Articles