Refactoring for encode method.