Python Methods: Returning data vs Storing data in attributes

73 views Asked by At

This might be a general programming question rather than Python specific, but, what is the best practice when it comes validation classes?

My first approach is having the method return a dictionary:

class Validator():
    def scene(self):
        # Do validations here
        return {'result': True, 'data' my_data, 'external_references': my_references}
    def character(self):
        # Do validations here
        return {'result': True, 'data' my_data, 'external_references': my_references}
# Usage
v = Validator()
scene_results = v.scene()
character_results = v.character()
if scene_results['result']:
    print "Scene Validation Succesful!"
    print "Data:", scene_results['data'], ", Files:", scene_results['external_references']
if character_results['result']:
    print "Character Validation Succesful!"
    print "Data:", character_results['data'], ", Files:", character_results['external_references']

My second approach is to populate the class attributes instead:

class Validator():
    def __init__(self):
        self.scene_result = None
        self.scene_data = None
        self.scene_external_references = None
        self.character_result = None
        self.character_data = None
        self.character_external_references = None
    def scene(self):
        ## Do validations here
        self.scene_result = True
        self.scene_data = my_data
        self.scene_external_references = my_references
        # Won't return the values
    def character(self):
        # Do validations here
        self.scene_result = True
        self.scene_data = my_data
        self.scene_external_references = my_references
        # Won't return the values
# Usage
v = Validator()
v.scene()
v.character()
if v.scene_result:
    print "Scene Validation Succesful!"
    print "Data:", v.scene_data, ", Files:", v.scene_external_references
if v.character_result:
    print "Character Validation Succesful!"
    print "Data:", v.character_data, ", Files:", v.character_external_references

Or should I use both approaches to get the best of both worlds?

Both of the examples work fine, however I want to know if this is the conventional way a validation class should work. Sorry if the answer is too obvious but I am learning here. Thanks in advance.

1

There are 1 answers

0
Orcist On

Well, if there are larger chunks of data to return and reuse, then i recommend the second approach since in that case you merely reference the data somewhere stored, whilst in the first case you also have to copy the returned value into a new variable, which could, for larger values, slow down the program. The second approach also provides encasement which is always good for security and also readabilty, so my recommendation sounds:

use classes where possible.

I also recommend writing separate test methods for the "validations" you talk about, for the same reasons as the previous.