Refactor encoder and decoder to reduce duplication