# Is it alright to use \newcommand inside of the body of a document?

This document compiles fine.

\documentclass{article}
\begin{document}

\newcommand{\foo}{bar}
\foo

\end{document}

But like, this feels wrong or immoral or something. Is there any specific reason this is a bad practice to define \newcommand macros inside the body of a document?

• I do it if I want to define some ad hoc shorthand inside an environment (equations are often candidates for it), so it's forgotten at the end of the environment. Commands for general use should be in the preamble, so you can find them easily. May 24 '20 at 15:36
• no it's fine, and sometimes necessary to come after definitions that occur \AtBeginDocument or at least this is an easy way to address such issues. But if it is a command with scope for the whole document that could be defined in the preamble it is more natural to do it there. May 24 '20 at 16:11
• If you do not need the definition in the body of the document, or in a particular environment, it is as bad practice as far as the definitions code everywhere the text obfuscate the contents. It also forces you to remember in which part of the text you can use the macro or not (in practice = more errors by undefined control sequences). And it is also harder to reuse a set of custom macros from one document into another. But if your tolerance to edit text+code soups is high, no problem!
– Fran
May 24 '20 at 17:03