In this paper we propose a unified theory describing the rules governing the formation of various oxide and metal nanostructures via electrochemical anodization. Nanoporous metal oxides of various morphologies have been of keen interest owing to their potential for various functional applications in chemical and biomedical sensing, chemical and photocatalysis, energy conversion in batteries and supercapacitors. This unified theory, based on thermodynamic and electrochemical principles, explains that the formation of porous or compact metal oxide and porous metal structures is dictated by the reaction free energy balance between the electrochemical anodic formation of the metal oxide and the chemical dissolution of the metal oxide in the electrolyte. Based on this theory, a range of key experimental observations reported in the literature are explained, including (1) the selection of the formation of compact oxide, porous oxide or porous metal during anodization, (2) voltage dependence of thickness of compact oxides, and (3) in situ pore perforation by step-wise reduction of anodization voltage.