DEV Community

loading...

Discussion on: Do you have a process for naming things?

Collapse
mortoray profile image
edA‑qa mort‑ora‑y

I've never understood why constants should be uppercase? I see no valuable semantic difference between these two forms of code:

  • create_deck( num_cards )
  • create_deck( NUM_CARDS )

The second form adds a visual clutter which provides no useful information to the reader.

Collapse
gypsydave5 profile image
David Wickes

I'd agree - but I think the convention is so widespread that I'd be surprised if it wasn't followed. Principal of least astonishment and all that.

Thread Thread
mortoray profile image
edA‑qa mort‑ora‑y

I've seen normal casing on constants used on many projects.

It's something that nobody would notice about, nor complain about. Nobody would miss the uppercase constants.

Thread Thread
gypsydave5 profile image
David Wickes

OK, you've convinced me! I'm removing it now as it's really not that important.

Collapse
zanehannanau profile image
ZaneHannanAU

Top-level constants (in a library or call function) would be uppercase as they are there to ensure capacity of use for the space they live in, and that . For instance, your create_deck( num_cards ) one would be better as a variable or simply a literal numeric value such as 52, 54, 128 or so on. Or it would be function called as a higher order function, eg

create_deck(Options { type: Cards::Playing, with_jokers: false, })

A better example would be

#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum ErrorCode {
  Other = 0,
  ServerDown = 1,
  BadRequest = 2,
  NotFound = 3,
  Gone = 4,
  EnhanceYourCalm = 5,
  DDoS = 6,

}

const ENUM_NAMES_ERROR_CODE: [&'static str; 7] = [
    "Other",
    "ServerDown",
    "BadRequest",
    "NotFound",
    "Gone",
    "EnhanceYourCalm",
    "DDoS"
];

pub fn enum_name_error_code(e: ErrorCode) -> &'static str {
  let index: usize = e as usize;
  ENUM_NAMES_ERROR_CODE[index]
}

where it's a constant; but it really is only used for one task and could be replaced with a match statement. This just avoids allocations in inlined code.