Inyeol wrote:
For example: I'm writing simple class:

    class Numbers:
        def __init__(self, numbers):
            self._numbers = numbers
        def get_all(self):
            for number in self._numbers:
                yield number

If I want to add another method for yielding even numbers only, I may
use:

        def get_even(self):
            for numbers in self._numbers:
                if numbers % 2 == 0:
                    yield number

or, I can use public method 'get_all' instead of using private
attribute '_numbers', like:

        def get_even(self):
            for numbers in self.get_all():
                if numbers % 2 == 0:
                    yield number

Which coding style do you prefer? I'm more toward public API way,
since it requires less code change if I refactor private data
structure later.
Plz give pros and cons of these.
- Unless you already know that you'll need to refactor the structure later, there's no need to anticipate => unnecessary optimization

- Using public API deos not necessarily make refactoring easier.
Let me explain, public APIs are meant to be called by external objects. These APIs may need to do some things that internal computing doesn't. For instance, let's say you add a logging statement in the get_all() method. Every call triggers a log entry. Does the get_even method want to log this call ? Maybe not. In that particular case, using the internal strucutre is preferable.

- If you agree to the statement that readability > edition, then you should care more about writing clean and concise code, than refactorable ( :D ) code. Using self._numbers raises less questions to the reader. Though I admit that question raised by get_all are answered in 5 seconds (the question being 'If he used an method instead of _numbers, this method must do something special')

- In fine, it doesn't really matter in the example you gave above.

JM



--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to