Constants

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

Constants

Postby Joeldi » Wed Apr 18, 2012 11:26 pm UTC

So while I was looking at some code at work, I came across some method level constants. I thought "Isn't that a bit pointless? If you don't declare constants at the top of the file what's the point." Stack overflow, and I assume the majority of you guys couldn't disagree more http://stackoverflow.com/questions/244191/what-are-your-thoughts-on-method-scoped-constants

The consensus there is "declare constants as close to where you need them as possible." But quite often, constants that only need method scope are only there to avoid a single-use magic number. In these cases, 'as close as possible' would BE a magic number.

In these cases, what are the significant advantages of having the constant at all, beyond "oh no magic numbers, you can't ever use them!!! My teacher told me NO!"

As for me, I think I'll keep them at the class level unless you guys are really convincing otherwise..
I already have a hate thread. Necromancy > redundancy here, so post there.

roc314 wrote:America is a police state that communicates in txt speak...

"i hav teh dissentors brb""¡This cheese is burning me! u pwnd them bff""thx ur cool 2"
Joeldi
 
Posts: 999
Joined: Sat Feb 17, 2007 1:49 am UTC
Location: Central Queensland, Australia

Re: Constants

Postby Sagekilla » Thu Apr 19, 2012 12:10 am UTC

I agree with the sentiment that you should keep constants as local as possible. If you're using constants
as some part of implementation detail, there's no reason why a client of that code should know about
those constants. It should be possible to change the implementation without changing the outward
functionality. If you make your constants at the class level so that basically everyone knows what you're
using, it becomes much harder to be able to change implementation details because a client may have
used your specific implementation details in their usage.

It's the same reason why we have various access modifiers. It's no different from saying "Hey I'm just going
to go and make all my methods public so it's easier to work with this class." In both cases, you're blatantly
violating encapsulation and you're exposing way too much of yourself.

Think to yourself: Do you use different access levels for fields and functions? Do you use different scopes
and access levels for your variables you use? Constants are no different and should be treated the same.*
Unless you have a good reason to expose a constant, it should be hidden away in whatever function or
scope it's required in.

In these cases, 'as close as possible' would BE a magic number.

What if you use it in multiple places? Or if you need to change it at some later point? Imagine you used magic
constants in just two places in your code. Then you change it and forgot to change the other. Now the program
could crash, or even worse, run and spit out the wrong results.

Don't forget that by using a constant, you can make your code document itself without requiring an explicit comment
in the middle of the code. Placing that constant at the method level is in no way similar to using magic constants, at all.

Edit: Just thought of something else. When I say client in the above post, I'm talking about ANYONE who calls your code.
That could be you within your own application, or someone else reusing your code for something.
http://en.wikipedia.org/wiki/DSV_Alvin#Sinking wrote:Researchers found a cheese sandwich which exhibited no visible signs of decomposition, and was in fact eaten.
Sagekilla
 
Posts: 385
Joined: Fri Aug 21, 2009 1:02 am UTC
Location: Long Island, NY

Re: Constants

Postby Joeldi » Thu Apr 19, 2012 12:19 am UTC

To clarify, I'm not suggesting I publically expose constants I don't need to. They're still private.
Last edited by Joeldi on Thu Apr 19, 2012 12:28 am UTC, edited 1 time in total.
I already have a hate thread. Necromancy > redundancy here, so post there.

roc314 wrote:America is a police state that communicates in txt speak...

"i hav teh dissentors brb""¡This cheese is burning me! u pwnd them bff""thx ur cool 2"
Joeldi
 
Posts: 999
Joined: Sat Feb 17, 2007 1:49 am UTC
Location: Central Queensland, Australia

Re: Constants

Postby Xanthir » Thu Apr 19, 2012 12:20 am UTC

The advantage of a constant is the same as the advantage of a variable - it names the value, which makes it easier to understand for others reading it.

Making it const rather than a normal variable just makes it clearer that, well, it's a constant that you're naming, and you won't be doing anything tricky with it.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))
User avatar
Xanthir
My HERO!!!
 
Posts: 4002
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex

Re: Constants

Postby Joeldi » Thu Apr 19, 2012 12:27 am UTC

Xanthir wrote:The advantage of a constant is the same as the advantage of a variable - it names the value, which makes it easier to understand for others reading it.
Making it const rather than a normal variable just makes it clearer that, well, it's a constant that you're naming, and you won't be doing anything tricky with it.

Okay, that makes a lot of sense to me.

Sagekilla wrote:What if you use it in multiple places? Or if you need to change it at some later point?

That's kind of where I'm coming from by making it class level. Methods are often broken up into helpers, and the more atomic a method, the less likely you are to use a constant more than once within that method. but what if later you need the same value in another method. Now you should have made it class level.
I already have a hate thread. Necromancy > redundancy here, so post there.

roc314 wrote:America is a police state that communicates in txt speak...

"i hav teh dissentors brb""¡This cheese is burning me! u pwnd them bff""thx ur cool 2"
Joeldi
 
Posts: 999
Joined: Sat Feb 17, 2007 1:49 am UTC
Location: Central Queensland, Australia

Re: Constants

Postby Divinas » Thu Apr 19, 2012 9:52 am UTC

A very simple code example, to show you why it's better to have a constant:
Code: Select all
InteractionDistance GetInteractionDistance(Target* t)
{
   float distance = DistanceToTarget(self, t);
   if (distance < 5.f)
      return Close;
   else if (distance < 12.f)
      return Medium;
   else
      return FarAway;
}


Why the hell 5? Why 12? Would be a lot clearer if instead of that, you had 5 as a const float PushRange = 5.f and 12 as const float ShootingRange = 12.f; Now you know: If he's in push range, he's considered close. If he's in shooting range, he's considered in medium distance, otherwise he's too far away to care. Now you know what those numbers express, and someone going through the code can immediately know why you put those numbers - even if they're used nowehere else and you always use the InteractionDistance enum.
Divinas
 
Posts: 55
Joined: Wed Aug 26, 2009 7:04 am UTC

Re: Constants

Postby darkone238 » Thu Apr 19, 2012 4:51 pm UTC

Divinas wrote:A very simple code example, to show you why it's better to have a constant:
Code: Select all
InteractionDistance GetInteractionDistance(Target* t)
{
   float distance = DistanceToTarget(self, t);
   if (distance < 5.f)
      return Close;
   else if (distance < 12.f)
      return Medium;
   else
      return FarAway;
}


Why the hell 5? Why 12? Would be a lot clearer if instead of that, you had 5 as a const float PushRange = 5.f and 12 as const float ShootingRange = 12.f; Now you know: If he's in push range, he's considered close. If he's in shooting range, he's considered in medium distance, otherwise he's too far away to care. Now you know what those numbers express, and someone going through the code can immediately know why you put those numbers - even if they're used nowehere else and you always use the InteractionDistance enum.


This wasn't really the point though. The question wasn't why have constants, it was why have constants at the method level rather than the class level? I don't think there's much debate over the value of naming a magic number.
User avatar
darkone238
 
Posts: 68
Joined: Thu Feb 09, 2012 6:37 am UTC

Re: Constants

Postby Sagekilla » Sat Apr 21, 2012 3:56 am UTC

Joeldi wrote:
Xanthir wrote:The advantage of a constant is the same as the advantage of a variable - it names the value, which makes it easier to understand for others reading it.
Making it const rather than a normal variable just makes it clearer that, well, it's a constant that you're naming, and you won't be doing anything tricky with it.

Okay, that makes a lot of sense to me.

Sagekilla wrote:What if you use it in multiple places? Or if you need to change it at some later point?

That's kind of where I'm coming from by making it class level. Methods are often broken up into helpers, and the more atomic a method, the less likely you are to use a constant more than once within that method. but what if later you need the same value in another method. Now you should have made it class level.


If you need to use a constant in more than one place, it makes sense to put it at a scope where it's visible for where it's needed.
I already said this in my previous post. Use the tightest possible scope for a given constant that satisfies the needs of all who use
it. Sometimes (but not always), the fact that the constant is used in so many places may mean it's a bad design. If you need that
constant in multiple methods, it may mean those methods are not doing enough work. Or that your abstraction of functionality
into functions is not the "best" one possible.

It really depends though . Sometimes you need the constant at the class level because it's used everywhere internally to a class.
Other times it's only used in once place and that's the only location you need it. There is no "one size fits all". Rather, keep your
constant as local as possible.


Again, it basically boils down to: What parts of my code need to see this constant? If I only need it in one method, it doesn't make
sense to make it visible to the whole class.
http://en.wikipedia.org/wiki/DSV_Alvin#Sinking wrote:Researchers found a cheese sandwich which exhibited no visible signs of decomposition, and was in fact eaten.
Sagekilla
 
Posts: 385
Joined: Fri Aug 21, 2009 1:02 am UTC
Location: Long Island, NY

Re: Constants

Postby sebwiers » Tue Apr 24, 2012 1:31 am UTC

Constants can also be a good defense against code creep. Suppose you have the following function (I'm a php worker, so its gonna be psuedo-php):
Code: Select all
function dispaly_complex_data($data_input, $user_preferences){
   ... 200+ lines of stuff ...
   work_on($data_input);
   ...tweak($user_prefereces);
   ...200+ lines of stuff ...
   use($data_input);
  examine($user_preferences);
}


Yeah, OK, you shouldn't have a 400+ line function. But you probably will, or will inherit one. And chances are you are gonna want to use those arguments. Now, down at the bottom, how do you know (without looking at the 400+ lines above) if or where changes to the parameter inputs were made? You don't. But if you define them as constants (as below), then you can just get the original value by looking at the constant. And mre important, anybody who has to modify the function KNOWS they can do that, without reading all the other cruft.
Code: Select all
function dispaly_complex_data($data_input, $user_preferences){
   define('INPUT', $data_input);
   define('PREFERENCES',$user_preferences);
   ... 200+ lines of stuff ...
   work_on($data_input);
   ...tweak($user_prefereces);
   ...200+ lines of stuff ...
   use(INPUT);
  examine(PREFERENCES);
}
sebwiers
 
Posts: 18
Joined: Sat Apr 21, 2012 3:12 pm UTC

Re: Constants

Postby sourmìlk » Tue Apr 24, 2012 1:49 am UTC

That doesn't really say much about necessary scope. Also, in real languages (or at least C++) you can define the parameter as constant in the function definition.
Terry Pratchett wrote:The trouble with having an open mind, of course, is that people will insist on coming along and trying to put things in it.
User avatar
sourmìlk
If I can't complain, can I at least express my fear?
 
Posts: 6405
Joined: Mon Dec 22, 2008 10:53 pm UTC
Location: permanently in the wrong


Return to Coding

Who is online

Users browsing this forum: No registered users and 11 guests