سد الذرائع or “Blocking the Means to Sin” is an established Islamic juristic principle. In life often one thing leads to another. An act of sin is not an isolated event but is preceded by chains of other events, which facilitate it. Therefore, Islam does not just forbid the final act, but also the preceding acts that can lead to it. There are hundreds of laws in Islamic jurisprudence that are based on this important principle. Consider alcohol. All its problems arise from its consumption. But Islam banned not just consumption of alcohol, but also making it, storing it, selling it, offering it, and even eating at a table where it is being served. This is blocking the means. One only needs to look at the spectacular success that Islam had in prohibiting alcohol and keeping the lands of Islam dry compared to the miserable failure of other societies in achieving that goal to appreciate the wisdom of the Islamic teachings.
Islam’s laws of hijab follow the same principle. Ultimately, it is the illicit extramarital relationships that are prohibited. But Islam does not limit itself to banning this final result. It also prohibits a number of other practices that could lead to this final sin. Therefore, looking, mixing, unnecessarily talking to, touching and fantasising about a non-mahram of the other gender have all been prohibited. Again, the result speaks for itself. For centuries, Islam has provided an atmosphere of chastity and decency in its societies that remains unmatched by any other society. And this has been accomplished through the same laws of hijab and segregation of sexes that are under attack today.
Source with few modifications.