refactor addInvariant()
Merge pull request #4131 from WalterBright/addinvariant

[Refactor]: merge copy-pasta code into addInvariant()