How to put code into another macro to avoid duplication?

The following code has two branches: If true-branch, argument #2 is put into \colorbox by which is typeset; If false-branch, argument #2 is typeset directly.

#2 has to appear in both branches. In the first part of my example(\cmda), the code of #2 is simple(just itself). But if the code of #2 is large and complex, it will be boring to duplicate the part of #2 code.

Then I tried with the second part of my example(\cmdb) by bgroup and egroup, but failed.

So, how to "cap" a part of code with another macro, as I tried in \cmdb?

EXAMPLE:

\documentclass{article}
\usepackage{geometry,xparse,xcolor}
\geometry{showframe}

\begin{document}
%%%%% \cmda %%%%%
\NewDocumentCommand\cmda{sm}{%
\IfBooleanTF{#1}
{\colorbox{green}{#2}}
{#2}
}

Test: \par
\cmda*{with back-ground color.} \cmda{no back-ground color.}
%%%%%%%%%%%%%%%%%%

%%%%% \cmdb %%%%%
\NewDocumentCommand\cmdb{sm}{%
\IfBooleanT{#1}
{\colorbox{green}\bgroup}
#2
\IfBooleanT{#1}{\egroup}
}

Test: \par
\cmdb*{with back-ground color.} \cmdb{no back-ground color.}
%%%%%%%%%%%%%%%%%
\end{document}


\colorbox wraps things into something like an \fbox whose frame-lines have a thickness of 0pt and wherein the background of things is colored.

Seems with star you wish this box with background-coloring while without star you don't wish any wrapping into a box at all.

This way measurements of things differ depending on whether coloring the background is desired or not.

You can use the kernel-macro \@firstofone.

If you don't want to wrap things between \makeatletter..\makeatother you can do \csname @firstofone\endcsname.

In expl3-syntax \@firstofone is \use:n.

\documentclass{article}
\usepackage{geometry,xparse,xcolor}
\geometry{showframe}

%%%%% \cmda %%%%%
\NewDocumentCommand\cmda{sm}{%
\IfBooleanTF{#1}%
{\colorbox{green}}%
{\csname @firstofone\endcsname}%
{#2}%
}

\begin{document}
Test: \par
\cmda*{with back-ground color.} \cmda{no back-ground color.}
\end{document}


If you wish the same measurements both for the colored and the uncolored boxes, s.th. like this might do the trick:

\documentclass{article}
\usepackage{geometry,xparse,xcolor}
\geometry{showframe}

%%%%% \cmda %%%%%

\newcommand\framelessfbox[1]{{\fboxrule=0pt \fbox{#1}}}%
\NewDocumentCommand\cmda{sm}{%
\IfBooleanTF{#1}%
{\colorbox{green}}%
{\framelessfbox}%
{#2}%
}

\begin{document}
Test: \par
\fbox{\cmda*{with or without back-ground color.}} \fbox{\cmda{with or without back-ground color.}}

\fbox{\cmda{with or without back-ground color.}} \fbox{\cmda*{with or without back-ground color.}}
\end{document}