First off make sure your ky-040 comes with built in resistors, Don't add extra ones or add capacitors like other people have told you if using the below KY-040 (if it does not come with built in resistors, you can modify my code to support it, take a look at the readme on the github page checkout the link to BoolRules original, he works with ones that dont have resistors you can copy and paste some stuff over, for now i left this basic to work with the ones below so nothing needs doing you just hook the example up)
KY-040 im using: KY-040 Rotary Decoder Encoder Module For AVR PIC Sale - Banggood UK
Hopefully this helps others i spent many hours looking for a solution to how to properly read these bouncy sensors and it turns out there was a state version of reading them which almost noone mentions anywhere, so enjoy a finally good version of Rotary Encoder Library for accuracy