Avatar billede fredand Forsker
14. juni 2009 - 16:29 Der er 2 kommentarer og
1 løsning

Local final variable or member?

Hello!

Hope to get some comment about this.

I use PMD to check my code as often as I can.

Consider this method:

    public boolean isDir() {
        File file = new File(filePath);
        return (file.isDirectory());
    }

PMD gives this comment:
Local variable 'file' could be declared final

If I do that like:

    public boolean isDir() {
        final File file = new File(filePath);
        return (file.isDirectory());
    }

Then I get this comment from PMD:
Avoid using final local variables, turn them into fields

Seems like there is a contradiction in PMD?
In this particularly case there is no use for making "file" into a field.
So is there any case when I should set local variables final?

What do you guys prefer?

Best regards
Fredrik
Avatar billede arne_v Ekspert
14. juni 2009 - 18:14 #1
Making file a field does not make sense at all in this case.

Whether to use final or not is debatable.

I an on the "no" side of the debate. My reason is that:
1) It is a rare source for errors
2) If you want a functional language then use a functional language instead of Java
Avatar billede fredand Forsker
14. juni 2009 - 21:11 #2
Hello Mate!

Thanks for your reply!

Correct me if I'm wrong when I say that Cobol and C is examples of functional languages?

Since my experience is very little in those languages, I just guess it might be common to use constant values in such methods/functions?
(I guess a function correlates in some way to a method?)

Btw please give a svar so I can reward you!

Best regards
Fredrik
Avatar billede arne_v Ekspert
15. juni 2009 - 08:30 #3
Cobol and C are procedural languages.

Java is an object oriented language.

Functional languages are ML and the like.

If you want a functional language for the JVM look at Scala and Clojure. But neither of them are pure functional.

For more about functional see:
  http://en.wikipedia.org/wiki/Functional_programming

Quote:

In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data.
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester