I'm going to use Nim in new project for the Server of Web Applications. I read
tutorials, but one thing is not clear to me - how should I decide when to use
object and when to use ref?
In Servers like Ruby on Rails or Java - the refs are used everywhere except of
the basic types like Integers etc. I wonder should I just always use refs in
Nim too?
In Java - I never had to think about it or choose between ref or object and I
try to figure out some simple rule that I could use in Nim - like just use refs
everywhere, or maybe not use it at all.
A word about performance - I'm not trying to achieve top performance. I would
prefer to have simplicity and average performance instead of more complicated
code and high performance.
If we consider a common web application - a blog. The kind of work that needs
to be done will be 1) define some objects 2) manipulate with sequences of that
objects 3) render it, the pseudocode:
import sequtils, sugar
type
Post = object
title: string
text: string
author: string
let db = @[
Post(title: "post 1", text: "text 1", author: "alex"),
Post(title: "post 2", text: "text 2", author: "jim"),
]
# Doing some manipulations, lots of iterations with
# sequences like filtering, mapping etc.
let posts = db.filter(post => post.author == "alex")
# Rendering
echo posts.map(post => post.title)
Run
In this example I defined Post as object, without ref.
And it seems like that would be wrong, right? Because those objects (like post)
will be copied a lot in operations with sequences. So it seems like it would be
better to use ref object in such cases?