The grammar structure ことだ is used to give advice or recommendations, meaning "should do" or "ought to." It is used to state general principles, life advice, or what one ought to do in a given situation. It carries a somewhat authoritative or matter-of-fact tone, as if stating a truth or a rule of thumb, and is used by someone in a position of authority or experience (e.g., a teacher, parent, or doctor).
Use the plain non-past form of the verb + ことだ to recommend doing something.
Use the plain negative form (~ない) + ことだ to recommend not doing something.
While 〜~ほうがいい gives situational, personal advice (often directed at a specific person in a specific moment), ことだ tends to express broader, more general advice – like a life principle or universal recommendation. Because of this, ことだ can sound somewhat preachy or lecture-like if used carelessly, so it is most natural when the speaker has relevant authority or experience.