Reputation: 113
being quite new to Rust and programming in general I have a basic question that is probably easily answered. Let's say I have a rectangle object, which has a width and a height, like so:
struct Rectangle1 {
width: u32,
height: u32,
}
I can create such an object with a new method:
fn new(width: u32, height: u32) -> Self {
Rectangle1 {
width,
height,
}
}
Now, let's say I want to use that object later and need its area, what is better practice? Have the area a field or a method?
So either I just implement this:
fn area(&self) -> u32 {
self.width * self.height
}
Or, since area is inherent to that object, I give the object an "area" field:
struct Rectangle2 {
width: u32,
height: u32,
area: u32,
}
And implement the new method like this instead:
fn new(width: u32, height: u32) -> Self {
Rectangle2 {
width,
height,
area: width * height,
}
}
Now somewhere else in the code, when the area is needed:
let rect1 = Rectangle1::new(30, 50);
let rect2 = Rectangle2::new(30, 50);
println!(
"The area of the rectangle 1 is {} square pixels.",
rect1.area()
);
println!(
"The area of the rectangle 2 is {} square pixels.",
rect2.area
);
In this simple example I can't see when one would be better than the other. What should be preferred anyway? Is there one way that is less common because of something I am not aware of?
Upvotes: 3
Views: 677
Reputation: 22402
This starts to become opinionated very fast. Generally speaking your answer will be driven by use-cases.
On modern systems, experience says that it's better to keep dependent params as functions and only optimize the caching of results as a special case.
Length and height remain constant over life of the Rectangle; pre-calculating may be useful. (Consider having to do it for 10^6 rectangles e.g.)
Your height and length get modified ... then do you precalculate? Do you cache the result?
You are constantly updating the third param based on the user updating any of the other two :-)
@prog-fh made a comment about accessing memory is expensive. I would say that you have to consider that both ways. Fetching two values into the CPU and calculating it can be potentially more expensive than accessing exactly one pre-calculated value.
so IMHO, and in line with what every one says,
It depends :-)
Upvotes: 1