attack or defense

Attack when you can, defend when you must.
Usually white attacks and black defends.
There are exceptions when black plays some sharp systems often sacrificing a pawn for an attack and then white has to defend.
Whoever has the long term advantage is better to defend.
Whoever has no long term advantage must attack.

You can only attack if you have some kind of an advantage. You must calculate that you do not lose material unless you can checkmate or win the material back.
#3
Example: black sacrifices a pawn to attack, white defends to win.
https://www.chessgames.com/perl/chessgame?gid=1095025
Example: from the pawn structure black attacks the white king and defends his queen's side, white defends his king and attacks black's queen's side pawns.
https://www.chessgames.com/perl/chessgame?gid=1044673
Example: white attacks the black king, black defends and attacks the white king.
https://www.chessgames.com/perl/chessgame?gid=1044020
Example: white attacks the black king, black defends and launches a counterattack
https://www.chessgames.com/perl/chessgame?gid=1042835

Opponents mainly attack your King with pawn storms. Keep it in mind, that pawn storms are dangerous and expose your King thoroughly. So, if you see a pawn storm coming, or your opponent building up a battery against your King, immediately take action against it. But if your attack has reached before your opponent's attack, then proceed with it. Your opponent would be forced to play according to your wish.
If your opponent's attack is going to reach first, then defend. Do not proceed with your attack as your position would crumble. There are situations where both players are threatening mate in 1 but because white gets to move first, he/she wins.
Hope this helped