Theme or Plugin: Where should I write my code?

How Sharma just mentioned, both approaches are working well, but depending on the site type and scope and also it depends on the feature that needs to be implemented in your WordPress.

If in the future you will change the theme of your WordPress site and you just implemented a feature in your current theme, it will be lost.

How the sketch below shows, I suggest to add your design in theme or child theme (recommended) and all functionalities in a plugin

enter image description here

I always add shortcodes, widgets, custom post types and metaboxes in plugin because the theme will not be same forever but this way the functionalities from the plugin will be kept.

Hope this answer your question;