Let $ G $ be a generator matrix of a linear code $ \mathcal C $ and $ [G: I_k] $ be a generator matrix of its extendable linear code $ \mathcal {C}' $, we call $ \mathcal C $ is optimally (almost optimally) extendable if $ d(\mathcal C^\perp) = d({\mathcal C'}^\perp) $($ d(\mathcal C^\perp) $ is very close to $ d({\mathcal C'}^\perp) $, respectively), where $ d(\mathcal C^\perp) $ is the minimal distance of the dual code of $ \mathcal C $. In order to safeguard the susceptible information lay in registers oppose SCA and FIA, it is useful to construct an optimally extendable linear code $ \mathcal C $. In this paper, we construct three classes of (almost) optimally extendable linear codes: (1) irreducible cyclic codes; (2) maximum-distance-separable (MDS) codes and near maximum-distance-separable (NMDS) codes.