# Sharing code between two classes

I'm writing two simple custom classes, one based on article and another based on book. They share some common code, such as font, margins, numering.

I'd like to reuse the lines of code that are common instead of copy-pasting them between the two files.

How can I share code between those two classes?

Alan has shown the two ways of sharing code at run time, however the other way is to share code development, but extract separate copies of the code to be loaded into the document at run time.

That is used for the two classes that you mention: article and book are almost identical in all respects except for some different defaults for \flushbottom, \twoside etc and some extra control over front and back matter in book.

These two files are extracted from the same documented source classes.dtx by the docstrip system that is part of the base LaTeX distribution. So the bulk of the code for article and book (and report) is only written once, but extracted separately into the three classes.

So you could write a single documented source of your classes and just mark specific lines with docstrip guards such as

%<*classa>
stuff here for classa.sty
%</classa>


where you want to specify different versions in each class.

• a similar system is used for the ams document classes, amsart and amsbook (as well as some other packages). the "common" documented source file is amsclass.dtx and is on ctan and in tex live, and, like drivers.dtx, could be used as a model. – barbara beeton Jun 4 '16 at 1:11
• That's perfect, thank you! A little trip down to docstrip land gave me the needed scaffolding to generate the files. – Robert Munteanu Jun 6 '16 at 21:25

There are basically two ways to do this.

You can put all the code into a single .tex file and then inside each class you would use:

\input{common_code}


This is the simplest method, and if the code is only usable within the custom classes, then is probably the most straightforward approach.

Alternatively, you could package the shared code as a package, and then use:

\RequirePackage{common_code}


This method might be preferable if the shared code is usable with document classes other than your custom class (and if such a use might be envisioned.)