Idea: Properties

Here are a few motivations:

  • Properties are more concise and easier to read than method calls. Consider these examples:

    foo.set_bar(bar); // vs
    foo.bar = bar;
    

    With the equals sign, the intent is immediately clear.

    foo.set_bar(foo.bar() * 2); // vs
    foo.bar *= 2;
    

    This is much shorter and easier to understand.

  • Properties are used for state, whereas methods are used for behavior. Without properties, it's not always clear which is which. If you have a method bar(), how do you know if it does an expensive computation, or just returns a field?

    You can of course start getters with get_, but that's more verbose. Also, a method starting with get_ may not be a getter, but will execute a GET HTTP request. True story.

  • Following good practices, getters and setters

    • should be cheap
    • should not produce an error
    • should return the same result over multiple invocations

    As long as you use properties only for state, not behavior, it's easy to follow these rules.

One important concern is that properties hide where computations are happening. However, IDEs like IntelliJ disambiguate properties from fields by using different syntax highlighting colors. This would also be possible in IntelliJ-Rust/RLS/rust-analyzer.

The purpose of properties is to expose state with a nice API, so it usually doesn't matter what the property does under the hood.

I found properties in Kotlin very useful. Kotlin even goes one step further and automatically converts getters and setters from Java APIs into properties. For example, this Java code: editText.setHint("...") is written like this in Kotlin: editText.hint = "..."

I think the same applies to properties. Properties can log a message when they are modified, or calculate a value lazily (e.g. the circumference of a circle from its radius, or a person's full name from their first and last name). Doing something more sophisticated is discouraged.

1 Like