Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

When writing some functions, I found a const keyword in parameters like this:

void MyClass::myFunction(const MyObject& obj,const string& s1,const string& s2,const string& s3){
}

often causes splitting a line into 2 lines in IDE or vim, so I want to remove all const keywords in parameters:

void MyClass::myFunction(MyObject& obj,string& s1,string& s2,string& s3){
} 

is that a valid reason to not using const? Is it maintainable to keep the parameter objects unchanged manually?

share|improve this question
46  
"Hey, I want to functionally change my program" to make it more readable is a bad bad reason. – Pieter B 17 hours ago
13  
The program is not becoming any more readable anyhow - Once you see something being handed over as const you have a strong hint that you don't need to bother how it might be changed in the function. – tofro 17 hours ago
17  
A better way to improve readability is to reduce the number of arguments. – 5gon12eder 15 hours ago
1  
a related similar issue: putting all the stuff that's in front of the method name onto the previous line. I have seen this being used in C++, too. – null 11 hours ago
1  
Readability is a reason to use string instead of const string, but using string & instead of const string & changes the semantics - it doesn't just affect readability. (I suspect it prevents you from passing a temporary string as an argument) – immibis 4 hours ago

Readability is a valid reason to learn to use whitespace:

void MyClass::myFunction(
        const MyObject& obj,
        const string& s1,
        const string& s2,
        const string& s3
) {
    return;
}

Located over there the parameters won't get confused with the body of the function. By locating them on a different line you won't have to reposition them when you change the name of myFunction to something more descriptive. Not changing the parameters position when they haven't changed is something source control diff tools will appreciate.

const means something. Don't throw it out just because you're out of space and ideas. Readability is king but breaking things in it's name is just giving up.

share|improve this answer
4  
"you won't have to reposition them when you change the name of myFunction" -- although in this case it looks as if they have been positioned to approximately line up with the opening (, and if that's the case then you might have to reposition them if the length of the class+function name changes by more than about 4 characters. So if you want not to have to do that, add a fixed number of levels of indentation, not a number that depends on the length of the function name. I would recommend 1 level, this answer uses 6, but any fixed number achieves the stated goal :-) – Steve Jessop 15 hours ago
    
@SteveJessop A good point. Consider using what c2 calls form 6 – CandiedOrange 12 hours ago
    
You can go further and introduce some tabs or other suitable whitespace to make the parameter names line up horizontally. – null 11 hours ago
5  
@CandiedOrange I'm surprised you didn't use "form 6" in this answer ... it's clearly less ugly! – svidgen 11 hours ago
5  
Form 6 for the win. One tabspace for one level of indentation. Simple and effective. Problem solved :) – Lightness Races in Orbit 10 hours ago

Actually, the readability issue definitely goes the other direction. First, you can trivially solve your run-on line by the use of whitespace. But removing const doesn't just make the line shorter, it completely changes the meaning of the program.

Herb Sutter refers to the const in reference to const as the most important const because a reference to const can bind to a temporary and extend its lifetime. An lvalue reference to non-const cannot, you need a separate variable.

void foo_const(std::string const& );
void foo_nc(std::string& );

std::string some_getter();

foo_const(some_getter());      // OK
foo_const("Hello there"); // OK

foo_nc(some_getter()); // error
foo_nc("Nope");   // error

std::string x = some_getter(); // have to do this
foo_nc(x);                     // ok
std::string msg = "Really??";  // and this
foo_nc(msg);                   // ok

What this means for usability is that you'll have to introduce all these temporary variables just to be able to call your function. That's not great for readability, since these variables are meaningless and exist only because your signature is wrong.

share|improve this answer

Simple answer is "no".

The long answer is that the const keyword is part of the contract the function offers; it tells you that the argument will not be modified. The moment you remove the const that guarantee goes out of the window. Remember that you can't reasonably maintain the constness (or any other property) of something using documentation, conventions, or guidelines - if the constness is not enforced by the compiler, someone will think that they can make their work easier if they fiddle with the parameter "just a little bit". Consider:

// parameter "foo" is not modified
void fna(Foo& foo);

void fnb(const Foo& foo);

Apart from the fact that the latter version is more concise, it also provides stronger contract, and lets the compiler help you maintain your intentions. The former does nothing to prevent the fna(Foo&) function from modifying the parameter you pass to it.

As in @CandiedOrange answer, you can use whitespace to lay out the code and enhance readability.

share|improve this answer

Removing the const keyword removes readability because const communicates information to the reader and the compiler.
Reducing the horizontal length of code is good (nobody likes scrolling sideways) but there's more to const than text. You could rewrite it:

typedef string str;
typedef MyObject MObj;
void MyClass::myFunction(const MObj& o,const str& s1,const str& s2,const str& s3)

Which doesn't change the contract but fulfils the need to reduce line length. Truly I would consider the above snippet to be less readable and would opt for using more whitespace as already mentioned in CandiedOrange's answer.

const is a functionality of the code itself. You wouldn't make the function a non-member to remove the MyClass:: section of the declaration, so don't remove the const

share|improve this answer
    
I agree that the snippet you provide is less readable. It forces a reader to go find out what MObj and str are, and certainly raises eyebrows. It's especially weird for types whose names you already have control over: E.g. Why didn't you just name MyObject as MObj to begin with? – Jason C 5 hours ago

As long as possible it is better to keep const visible. It improves code maintenance a lot (no guesswork to see if this method changes my arguments).

If I see lot of arguments in a method, it forces me to consider creation of project based jaron (Matrix, Employee, Rectangle, Account) that would be much shorter, easier to understand (eliminates long list of arguments to methods).

share|improve this answer
    
Agreed. I was hesitant to point it out. Thus, "extreme case". – blackpen 5 hours ago
    
@cmaster That said, sometimes in certain contexts, with certain programmers, it could stay readable. For example, in the very specific case of a program waist-deep in Windows API calls, with a reader who is used to that environment, stuff like e.g. typedef Point * LPPOINT and typedef const Point * LPCPOINT, while super obnoxious, still carries an implicit meaning, because it's consistent with immediate expectations in context. But never in the general case; it's just a weird exception I can think of. – Jason C 4 hours ago
1  
Yes, when I saw the question, "const unsigned long long int" came to my mind, but, it is not a good candidate to derive benefit from being either "const" or "reference". The typedef solves the general problem of shortening names; but it doesn't feel like good design to hide the very purpose of language constructs (like "const") behind it. – blackpen 4 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.