Mitzvah habah ba’aveirah is bad, because the ends don’t justify the means (mitzvah isn’t enough to justify the aveirah that brings it about). However, you ARE allowed to break shabbos, shomer negiah and other mitzvos to do pikuach nefesh, because the ends (pikuach nefesh) justify the means (breaking shabbos). What’s going on here?
Also, I think there is a midrash about Amram and Yocheved talking about whether its worth it to have a child when he could get killed- I forget the details though.
For those who care, the two deios I quoted form a classic secular philosophical debate between Deontologists and Utilitarians. It’s cool that halacha picks sides as well.