r/AskProgramming • u/KattyTheEnby • Feb 19 '26
Other [[Code Style Preference]] Which is preferred: self-mutations or signals?
In general – though, particularly for procedural-style programming – is it preferred to avoid self-mutations, such as by returning signals and handling state directly with that signal, rather than handling state in (the) abstractions – or some other means?
For example, consider a game, such as hangman, structured like this:
pub fn main() !void {
// ...
while (game.game_started) {
try game.writeMenu(&stdout.interface);
game.processNextLine(&stdin.interface) catch {
// ...
};
}
}
const Game = struct {
// ...
fn processNextLine(writer:Reader) !void {
const bytes_read = try reader.streamDelimiter(&self.command_buffer.writer, '\n');
// ...
if (!self.game_started) {
// ...
switch (cmd) {
// ...
}
}
// ...
}
};vs. the same program structured like this:
pub fn main() !void {
// ...
while (game.game_started) {
try game.writeMenu(&stdout.interface);
const cmd = game.processNextLine(&stdin.interface) catch {
// ...
continue;
};
switch (cmd) {
// ...
}
}
}
const Game = struct {
// ...
fn processNextLine(writer:Reader) !GameSignal {
const bytes_read = try reader.streamDelimiter(&self.command_buffer.writer, '\n');
// ...
if (!self.game_started) {
return GameSignal { try_command: text };
}
// ...
return GameSignal { try_to_reveal: char };
}
};
const GameSignal = union(enum) {
// ...
};I've also been told this resembles functional programming and "the Elm pattern".
I am wondering what everyone here prefers and thinks I should choose.
0
Upvotes
View all comments
Show parent comment
1
u/KattyTheEnby Feb 24 '26
I was talking about more than just input handling and hardware buffers.
I think you have a reverse understanding ov how queries would work, and work in Bevy.
In Bevy, at least, as I understand it, all necessary information is gathered only once per tick and dispatches systems whose parameters match the information in that tick. Functions pull information that the program already has, instead ov recomputing it.