Solved

method argument as final

Posted on 2016-08-14
1
113 Views
Last Modified: 2016-08-14
Hi,

When do we need to declare method argument as final say as below

void addPerson(final Employee theEmployee) {
......
.....

}

please advise
0
Comment
Question by:gudii9
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 27

Accepted Solution

by:
dpearson earned 500 total points
ID: 41755845
>> When do we need to declare method argument as final say as below

You almost never have to declare arguments as final, but some people consider it good practice and it may be adopted as a coding standard by some companies.

The reason to do this is that "final" makes sure the parameter cannot be modified within the method, which keeps the logic simpler.

void addPerson(final Employee theEmployee) {
    ... stuff before
    process(theEmployee) ; // guaranteed that this is the employee that was passed in
}

Open in new window


Without final the value could change:
void addPerson(Employee theEmployee) {
    ... stuff before
    process(theEmployee) ; // maybe modified along the way
}

Open in new window


E.g. Here's how not making it final allows parameter to be changed:
void addPerson(Employee theEmployee) {
    ... stuff before
    theEmployee = anotherEmployee; 
    ... more stuff
    process(theEmployee) ; // may not be what was intended
}

Open in new window


So it's probably a good idea to usually add "final" to parameters to methods by default.
So why don't people do this more often?  Because it's extra typing.

Doug
0

Featured Post

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Java Eclipse Loop 3 29
Octopus Deploy: need a Time Event that fires every midnight 2 29
Tomcat 9 + java 8 error while trying to deploy a war file 2 700
Java array 21 80
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question