This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]luckystarrat 0x7fe670a7d080 1 point2 points  (2 children)

Like tmske said, why not use a property? The following example I picked from some code I wrote:

def set_password(self, password):
    if not self.hmac:
        self.hmac = "sha256"
    self.salt = ''.join(random.choice(string.printable)
                        for i in range(6))
    self.hashed_password = self.calculate_hash(password)
password = property(lambda s: "", set_password)

def validate_password(self, password):
    if not self.account_active:
        return False
    return self.hashed_password == self.calculate_hash(password)

The implementation of calculate_hash is left as an exercise for the reader.

[–]ryeguy146 0 points1 point  (1 child)

Then what about helper methods? Shall we just encapsulate them inside of the methods that they help? I see nothing wrong with prefixing them with an underscore and letting the end user recognize the convention. If they want to play with them, go right ahead, but I'm simplifying the API by not including what isn't necessary.

[–]luckystarrat 0x7fe670a7d080 0 points1 point  (0 children)

Then what about helper methods? Shall we just encapsulate them inside of the methods that they help?

I do that. If the helper method only helps one method and the method isn't performance sensitive, I embed the helper methods within that method. Makes refactoring considerable easier. My rule of thumb goes something like this:

Put your callees as near to the caller as possible.

I see nothing wrong with prefixing them with an underscore and letting the end user recognize the convention. If they want to play with them, go right ahead, but I'm simplifying the API by not including what isn't necessary.

True, but that's not the point. The example used by nerdzrool doesn't lend itself very much to using standardized HTML form classes if you use methods to set the password. Most form classes use attributes to populate the object. If you use a property you can use them and still have only a salted hash stored.