How to programmatically get the NID of the current node I've pored over this old thread on drupal.org and it just kind of makes my head spin around. Pulling down the path and trying to parse out the NID from within it? There has to be a better way. 

And solutions like 

global $node;
$nid = $node-&gt;nid;


don't work in my custom module (though I'm told they work in templates?). No error or anything, it just instantiates $node with a NULL value. 

It feels like there must be something really obvious that I'm missing. 

So, how do you get the NID of the current node without a template, while following best practices and building a reasonably robust module?
Assuming your code is running for a node page, the methods I see used most often in core/contrib modules are either using menu_get_object() or arg():

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node-&gt;nid;
}


or

if (arg(0) == 'node' &amp;&amp; is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}


I personally prefer the first method (even though assignment in condition isn't considered a good idea by some people), but both are perfectly valid.