logoalt Hacker News

incrediblers • today at 8:33 PM • 5 replies • view on HN

Getters and setters is the one I'm most at disagreement with.

   // Mine
   let label = Label.text("Hello Wold");
   let label_text = label.get_text();

   // Theirs
   let label = Label.set_text("Hello Wold");
   let label_text = label.text();
A method is a way to accomplish a specific task. Emphasis on specific not generic. The getter task is to always return. The setter task is specific. So the method should be the setter - `text`, `color`, `fill`. In Rust the getter can't have same name, so prefix it. Not the other way around.

Replies

i2talics • today at 8:43 PM

Their style is pervasive in Rust, such as in the standard library, so I would personally apply a when-in-rome philosophy. FWIW something like `.text("hello")` I would expect to see in a builder-pattern but not in a setter for an object that's already built.

That being said I don't particularly understand your conception of a method. They are both methods. The getter ought to have a shorter name since it is probably called more frequently and because it inherently has less of an impact -- this goes along with the principle that names that demand attention should be larger and easier to notice.

➕ show 1 reply
epage • today at 9:17 PM

I think which to use in general Rust code depends on the purpose of your type.

A builder type like `Command` will have unqualified setters and `get_` qualified getters.

For record-like-structs, I think unqualified getters becomes preferred and `set_` qualified setters.

trimbo • today at 8:55 PM

This style is aligned with protocol buffers, which is aligned with the style of protos in C++.

https://protobuf.dev/reference/rust/rust-generated/