squid3ox
squid3ox

Reputation: 19

Why creating a method better than declaring variable as a field?

int timeDuration = duration * MONTHS_IN_A_YEAR;

My online instructor said I should declare a method of name getTimeDuration() rather than creating a field of the same name. My question is a why creating a method is more preferable. Thanks.

Upvotes: 0

Views: 89

Answers (3)

Majid Roustaei
Majid Roustaei

Reputation: 1764

Some code snippets are called "best practice"s, these are told by experienced people and accepted by developers and programmers because of the reasons like:

  • more readable code
  • easy to change for future extending or debugging
  • better performance
  • help developers to do better configurations
  • ...

the matter we are talking about (using setter and getter for accessing or modifying fields), has one or some of matters that I have mentioned so it is better for developers to use it.

to talk more specific, by setting a field in a method (which that method is called setter) you can check the user input, put some rules for your code and many more features that some frameworks will give to you as a developer.

accessing the value of a field by a method (which is called getter), might add some abilities in some cases, imagine a situation that you want the user to read the field but not be able to change it. this could be done easily this way.

Upvotes: 0

Thomas Bitonti
Thomas Bitonti

Reputation: 1234

This could fall into a style war. Folks from some camps will always use getters, while others rarely do so. You will find no single 100% agreed upon answer.

Practically, there will be little difference between a using a getter on a private final variable vs direct access. Good runtime environments will inline getters, making for only a slight additional overhead.

There are several reasons to prefer using a getter: If the value which is being retrieved is to be considered a part of an API; if the value obtained by the getter will be different in subclasses; if you want to place a break point or log or otherwise track calls to access the value; if you want a place to attach documentation of the value obtained by the getter, which would be the getter name and explicit documentation.

On the other hand, adding getters does add (a little) code bloat.

Upvotes: 1

maazakn
maazakn

Reputation: 404

One reason, in future if you set variable as private or it will become private data, you are not allowed to access this variable outside the class boundary. So, the value of value of variable fetch by such getters and in object oriented getters are used for this purpose and came into action. Here getters is method like getTimeDuration().

Upvotes: 0

Related Questions