Consider your code snippet as a single paragraph: paragraphs in Writer are the basic units of significance. Every paragraph has a semantic value. The common examples are headings (at various levels) and main discourse. You communicate this value to Writer by applying a paragraph style to your paragraphs, e.g. Heading n for headings and Body Text for main discourse.
Regarding your code snippets, type them as you would in your code editor but separate lines with Shift+Enter instead of simple Enter (except at end) to make the snippet a single paragraph. It may also help do disengage some AutoCorrect options as suggested by @Zizi64.
If you paste from a source file, you’ll have to change the paragraph breaks into line breaks Shift+Enter.
Either apply built-in Preformatted Text style or your own style. I have created for this purpose a custom Code Sample using a monospace font, left indent to make the snippet stand out of main discourse and coloured background (I could not mimic old computer stationery because there is no way to have line-alternated background colour). This style also has an augmented space above and below so that the extent of the snippet is clearly visible.
Since there is nothing else than the code in the snippet, you can copy it and paste it in a source file without artefacts. The line breaks end up the same as paragraph breaks in plain text file (source file).
Here is an example:
and my Code Sample definition: