Access to field from a passed object

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

Below I have method MostPowerful which is located in class SportsCar.
As you can see the fomel parameter for method MostPowerful is carCompare of
class SportsCar.
Because this method MostPowerful is a member of class SportsCar
can I use the field directly for the passed SportsCar object in
this way "carCompare.horsepower".

Now to my question. I have two choices. I wonder which is best according to
OOP.
1. Use the field directly as I have done by using this statement
"carCompare.horsepower"
2 Or use a property to get the horsepower. Like carCompare.GetHorsepower or
somthing similar

Is the performance between using 1 or 2 about the same?


public SportsCar MostPowerful(SportsCar carCompare)
{
if (carCompare.horsepower > this.horsepower)
return carCompare;
else
return this;
}



//Tony
 
Because this method MostPowerful is a member of class SportsCar
can I use the field directly for the passed SportsCar object in
this way "carCompare.horsepower".
Yes.

Now to my question. I have two choices. I wonder which is best according
to OOP.
1. Use the field directly as I have done by using this statement
"carCompare.horsepower"
2 Or use a property to get the horsepower. Like carCompare.GetHorsepower
or somthing similar

Doesn't really matter. In this case it's perfectly fine to access the
private member directly. The main purpose of encapsulating your fields is
to protect them from being set to an invalid value by consumers of your
class. However, when the consumer happens to be another instance of the
same class it's presumed that the person who developed the class would take
the steps necessary to ensure they don't set a field to something invalid.

It can be advantagious to use accessor methods if the accessor method has
to do something special in addition to setting the value. However, in your
case it doesn't look necessary.
Is the performance between using 1 or 2 about the same?

From a purely theoretical standpoint, you'd think the direct access method
could give better results. However, I'd wager they'd be so close in speed
that you couldn't accurately measure it. You'd have windows processes
themselves mucking with the timing enough to make the results inconclusive.
The JIT compiler is pretty good at optimizing this kind of stuff.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top