There's a reason many Medieval castles are still standing today, aside from the fact that most were built out of stone- they were constructed by builders who knew their stuff.
These builders didn't waste time with a bunch of decorative elements or other unnecessary additions, so pretty much every detail we see in a castle was put there on purpose.
The moat made it hard for an army on foot or horseback to run up to the castle walls during a siege, but more importantly moats prevented invading armies from tunneling beneath the castle- because their tunnels would flood.
The main gate was also meant to serve as a death trap, as it opened up into a small secured courtyard where the invading army would be trapped and quickly cut down from above by archers.
But to me the most interesting fact shared by Will Kalif of All Things Medieval has to do with the very logical reason why castle stairwells are so narrow and turn clockwise versus counter-clockwise:
...any attackers coming up the stairs had their sword hands (right hand) against the interior curve of the wall and this made it very difficult for them to swing their swords.
Defenders had their sword hands on the outside wall, which meant they had more room to swing. Another ingenious design of stairs was that they were designed with very uneven steps. Some steps were tall and other steps were short.
The inhabitants, being familiar with the uneven pattern of the stair heights could move quickly up and down the stairs but attackers, in a dimly lit stairwell, would easily fall and get bogged down in the stairwells.
This made them vulnerable to attacks and slowed their attacks down significantly.