When to use a class instead of a dict
<p>User data, as follows:</p>

<pre><code>user = {"id": 1, "firstName": "Bar", "surname": "Foosson", "age": 20}
</code></pre>

<p>is sent to an application via json. </p>

<p>In many places in the code the following it done:</p>

<pre><code>user["firstName"] + " " + user["surname"]
</code></pre>

<p>which leads me to believe a function should be used:</p>

<pre><code>def name(user):
    return user["firstName"] + " " + user["surname"]
</code></pre>

<p>which in turn leads me to believe that the code should be refactored with the use of a <code>User</code> class instead, with a <code>name</code> method. Do you agree and is there any argument for not refactoring the code to use a class instead?</p>

<p>Dictionaries are great for storage and retrieval, but if you need more functionality on top of that, a class is usually the way to go. That way you can also assure certain attributes are set, etc.</p>

<p>For your situation, if a user's attributes are read-only, my approach would actually be using <a href="https://docs.python.org/3/library/collections.html#collections.namedtuple" rel="nofollow"><code>namedtuple</code></a>. You get immutability of attributes, memory efficiency, and you can still set <code>name</code> to a pre-defined method to be used just like you'd use <code>property</code> on a class:</p>

<pre><code>from collections import namedtuple

@property
def name(self):
    return '{} {}'.format(self.firstName, self.surname)

User = namedtuple('User', 'id firstName surname age')
User.name = name

user = User(1, 'Bar', 'Foosson', 20)
print(user.name)  # Bar Foosson

user = User(2, 'Another', 'Name', 1)
print(user.name)  # Another Name
</code></pre>

python