First, the codes you posted are not equivalent: in the first case, the pointer str
may be reallocated at will, but the contents of the pointed string no (more details in that question in the SOEN). in the second, the reference str
cannot be modified, but the content of the object in principle could be - if String
was no longer immutable (I am thinking of Java, but if you were referring to another language please specify).
This example in ideone shows this clearly:
char *process_string(const char *str) {
str = outra_string; // Pode mudar o ponteiro à vontade
//str[0] = '1'; // Não pode mexer no conteúdo
return str;
}
char *process_string_2(char * const str) {
//str = outra_string; // Não pode mudar o ponteiro
str[0] = '2'; // Pode mexer no conteúdo à vontade
return str;
}
Why is this not common in other languages? Unfortunately I can’t say... It would be extremely useful for a compiler to guarantee the contract that "this method has no side effects [in this parameter at least]" but I have no idea of the difficulty of implementing (in particular in object-oriented languages, which do not support pointer arithmetic and make extensive use of references).
And speaking of references, the main reason you don’t see many parameters final
is that it is common for references to objects to be passed by value. That is, the object is not copied, but the reference to it is. So, what’s wrong with the function of reassigning its own parameters? Only she really sees them... And for that very reason it’s hard to see a C function with meters just like the process_string_2
of the above example.
The only case I know that a parameter final
may be necessary when it is used in a closure and language does not support "spaghetti pile":
public void prepararBotao(final String mensagem) {
final JTextField caixaTexto = this.caixaTexto;
botao.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
caixaTexto.setText(mensagem); // Só pode usar "mensagem" aqui porque é final
}
});
}
(I don’t know the exact reason why this is needed in Java - other languages allow closures to access non-terminal attributes smoothly)
In fact, final in Java parameters is generally a good practice to avoid improper reuse of parameters as variables. Almost nobody uses it because most of the "javeiros" do not study beyond the basic and the rest have laziness.
– utluiz
That’s interesting. Could you tell me where I can get these good practices?
– Sid