Solved

method argument as final

Posted on 2016-08-14
1
118 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

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Regarding swagger API 1 63
$_GET call between URL 3 70
XSLT to pick out a particular element and then pick out all following siblings 4 20
Problem to macro 5 24
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.

752 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