简体   繁体   中英

Are Magic Numbers Okay In This Instance?

In this question regarding magic numbers in arrays, paxdiablo says that any number other than -1, 0 and 1 are magic numbers. I know that this is only a guideline but I was wondering if when specifying dimensions of a multi dimensional array if I needed to define constants for which dimension was x, y and z. For example, is this okay:

typedef boost::multi_array<TileID, 3> TileArray3D;

TileArray3D::size_type GoRPG::MapData::GetWidth() {
    return mData.shape()[0]; 
}

or is this preferred:

TileArray3D::size_type GoRPG::MapData::GetWidth() {
    return mData.shape()[x_dimension]; 
}

Thanks in advance, ell.

Edit: The reason the lengths are stored in an array is because I am using Boost::multi_array and that is how they are stored. Apologies for the broken code! I can fix that later - at the moment I just would like to know about the magic numbers, although it is still useful, thank you!

No, magic numbers are non-obvious ones. -1 , 0 , and 1 are generally obvious, but not always.

In your case, neither of your snippets is obvious to me. Why is the width of your map data stored in an array?

Without seeing more code, I would prefer this:

auto GoRPG::MapData::GetWidth() {
    return mData.shape()[width_index]; 
}

I think you should have a constant defined for this case and not use a number. 0 is not always "magic", in instances where accessing the first element is the intuitive thing to do. Example: checking the first byte of a string, there's no reason to define a c_first_byte constant.)

But in your code, it would be even better to add a method to shape or mData named x() that returns the value that you want. There's no need to expose the internal representation of mData or shape to its users.

The code does not compile though. Since, you haven't used decltype to deduce the return type. Do all the shapes have the same width ?

If yes, then should be OK. If not, then better approach could be to provide a default argument.

  auto MapData::GetWidth(const size_t index = 0) -> decltype( mData.shape()[0]) { 
    return mData.shape()[index];  
  } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM