Hot answers tagged

180

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 ...


152

There isn't always a perfect solution, but you have many alternatives to choose from: Use named arguments, if available in your language. This works very well and has no particular drawbacks. In some languages, any argument can be passed as a named argument, e.g. updateRow(item, externalCall: true) (C#) or update_row(item, external_call=True) (Python). ...


85

Anything in your source code, including const declared global constants, might be subject to change with a new release of your software. The keywords const (or final in Java) are there to signal to the compiler that this variable will not change while this instance of the program is running. Nothing more. If you want to send messages to the next maintainer, ...


80

When reviewing code, I apply the following rules: Always use const for function parameters passed by reference where the function does not modify (or free) the data pointed to. int find(const int *data, size_t size, int value); Always use const for constants that might otherwise be defined using a #define or an enum. The compiler can locate the data in ...


51

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 ...


39

The correct solution is to do what you suggest, but package it into a mini-facade: void updateRowExternally() { bool externalCall = true; UpdateRow(item, externalCall); } Readability trumps micro-optimization. You can afford the extra function call, certainly better than you can afford the developer effort of having to look up the semantics of the ...


29

Possible reasons are caching, naming or forcing type Caching (not applicable) You want to avoid the cost of creating an object during the act of comparison. In Java an example would be BigDecimal zero = new BigDecimal ("0.0"); this involves a fairly heavy creation process and is better served using the provided static method: BigDecimal zero = ...


25

Say I have a function like UpdateRow(var item, bool externalCall); Why do you have a function like this? Under what circumstances would you call it with the externalCall argument set to different values? If one is from, say, an external, client application and the other is within the same program (i.e. different code modules), then I'd argue that you ...


21

Speaking for Java where the keyword "final" represents "const", consider: final Person someone = new Person(); This means someone can NEVER refer to another Person object. But, you can still change details of the person being referred. E.g. someone.setMonthlySalary(10000); But, if someone was an "Immutable" object, one of the following would be true: (a) ...


21

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, ...


17

While I agree it's ideal to use a language feature to enforce both readability and value-safety, you can also opt for a practical approach: call-time comments. Like: UpdateRow(item, true /* row is an external call */); or: UpdateRow(item, true); // true means call is external or (rightly, as suggested by Frax): UpdateRow(item, /* externalCall */true);


16

I’ll speak to C++, where this difference is most relevant. As you correctly note, immutable means that an object cannot change at all after its creation. This creation can of course occur at runtime, i.e., a const object is not necessarily a compile-time constant. In C++, an object is immutable if (1) and either (2) or (3) are met: It has no members ...


14

Yes. It helps the reader to understand your intent. Clearly foo is given an initial value and never changed thereafter. It helps the compiler to optimise your code, for both speed and space. The compiler can perform certain optimisations such as hoisting values out of loops if there is a promise that the value cannot change. This is particularly the case ...


14

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& ...


13

We need to distinguish two aspects of constants: names for a values known at development time, which we introduce for better maintainability, and values that are available to the compiler. And then there's a related third kind: variables whose value does not change, i.e. names for a value. The difference between an these immutable variables and a constant ...


12

Note sure if this qualifies for you, but in functional languages like Standard ML everything is immutable by default. Mutation is supported through a generic reference type. So an int variable is immutable, and a ref int variable is a mutable container for ints. Basically, variables are real variables in the mathematical sense (an unknown but fixed value) ...


11

Generally in any programming language its recommended to use const or the equivalent modifier since It can clarify to the caller that what they passed in is not going to change Potential speed improvements since the compiler knows for certain it can omit certain things that are only relevant if the parameter can change Protection from yourself accidentally ...


11

First, is my understanding of these two concepts correct? Yes but your second question shows that you don't understand these differences. Second, if there is a difference, why are they almost exclusively used interchangeably? const in C++ is only used for access level (it means "read-only"), not for immutability. It imply that the access itself is ...


11

You can 'name' your bools. Below is an example for an OO language (where it can be expressed in the class providing UpdateRow()), however the concept itself can be applied in any language: class Table { public: static const bool WithExternalCall = true; static const bool WithoutExternalCall = false; and in the call site: UpdateRow(item, Table::...


10

Immutable objects are those that does not change state after creating it. For example; string prefix = "Pre"; string postfix = "Post"; string myComplexStr = prefix + postfix; In this example myComplexStr object is immutable but not constant because it's value is calculated. And it is immutable because it is a string and has a static length property and ...


10

Another option I haven’t read here yet is: Use a modern IDE. For example IntelliJ IDEA prints the variable name of the variables in the method you’re calling if you’re passing a literal such as true or null or username + “@company.com. This is done in a small font so it doesn’t take up too much space on your screen and looks very different from actual code. ...


9

As covered doing this as a performance thing is not sensible. However doing it for code readability is very sensible. In a non trivial bit of code I would use constants to add syntactic meaning to the variable. Fear the magic string. class GreetingPrinter { private const string Greeting = "Hello"; internal void CallMe() { ...


8

The main problem is programmers tend not to use it enough, so when they hit a place where it's required, or a maintainer later wants to fix the const-correctness, there is a huge ripple effect. You can still write perfectly good immutable code without const, your compiler just won't enforce it, and will have a more difficult time optimizing for it. Some ...


8

When implementing const and non-const member functions that only differ by whether the returned ptr/reference is const, the best DRY strategy is to: if writing an accessor, consider whether you really need the accessor at all, see cmaster's answer and http://c2.com/cgi/wiki?AccessorsAreEvil just duplicate the code if it is trivial (e.g. just returning a ...


8

Variables are not called variables because their values may be changed, but because their value isn't known in advance – when writing the code, they are placeholders for values that will be determined later. In contrast, the value of a constant is known when the program is written. Giving that known value a name is a matter of convenience and ...


7

I see the drawbacks as: "const poisoning" is a problem when one declaration of const can force a previous or following declaration to use const, and that can cause its previous of following declarations to use const, etc. And if the const poisoning flows into a class in a library that you don't have control over, then you can get stuck in a bad place. it's ...


7

Some good answers here already, but I think there is something more to say about your "mental model" of the object, since you wrote I think of this method like a generator that just creates a series of values on subsequent calls, rather than a method which modifies the object. But since previousParam is a member of your object, the method actually does ...


7

Case2 is better because the string has no more than the scope it needs and I don't have to chase variables to read your code. Simple. Performance doesn't matter here.


Only top voted, non community-wiki answers of a minimum length are eligible