Best practice for managing magic strings in Django JsonResponse keys/values
I have a Django view that returns JSON responses:
def post(self, request, post_id):
post = get_object_or_404(Post, pk=post_id)
if post.is_pub_date_future():
return JsonResponse({
'result': 'failure', # magic string
'message': 'No posts available to dislike' # magic string
}, status=404)
post.dislikes = F("dislikes") + 1
post.save()
return JsonResponse({
'result': 'success', # magic string
'dislikes': post.dislikes, # magic string
})
The problem: I have to memorize all these string keys ('result', 'message', 'dislikes') and values ('success', 'failure'). If I change them in the view, I also have to update them in my tests and templates.
I'm considering creating a constants.py file like this
class ResultConstants:
ERROR = "error"
SUCCESS = "success"
FAILURE = "failure"
class EntityConstants:
DISLIKE = "dislike"
LIKE = "like"
But I'm not sure if this is the best approach
So what is the best practice for managing these magic strings in JSON responses?
And how exactly this problem is called?
It's a good idea to isolate magic words. In addition to your approach, I do something else, in different languages and technologies. 1. I use naming conventions for files and classes, such as DefinitionSet. 2. In certain situations I auto-generate strings out of identifies. For example, in JavaScript, I auto-generate them from property names. Some may say, this is the same. No! In particular, it is not the same for Intellisense and code analyzers. Intellisense suggests property names, but not string values.
Obviously, it helps to avoid random mistakes. One can easily misspell a string, and nothing will detect it. If one misspells an identifier or a property name, the modern IDE will show the problem immediately.
One less than obvious benefit of this isolation is this: I classify all the files into having the definitions of magic constants and the other files. I can do the global text search and confirm that the other files have no quotation marks at all, this is pure code.
and how do the frontend and backend coordinate names? As I understand it, they use the same constant source? Some kind of XML or JSON.