[Tutor] How to separate UI code from program logic?
Mark Lawrence
breamoreboy at gmail.com
Sun May 6 18:35:51 EDT 2018
On 06/05/18 22:59, boB Stepp wrote:
> I was solving a programming problem in one of my books concerning the
> generation of a Collatz sequence
> (https://en.wikipedia.org/wiki/Collatz_conjecture), and started to
> wonder how I should separate my program's output from its logic. It
> seems like this should be obvious to me, but, unfortunately, it isn't.
> The core functions from my program are:
>
> #----------------------------------------------------------------------------
> def collatz(integer):
> """Returns the Collatz sequence number corresponding to integer. integer
> must be > 0, or the sequence will not converge to 1."""
>
> if integer % 2 == 0:
> return integer // 2
> else:
> return 3 * integer + 1
>
> def generate_collatz_sequence(seed):
> """Generates a Collatz sequence starting from seed.
> seed must be a positive integer, or the sequence will not
> coverge to 1."""
>
> counter = 0
> collatz_number = seed
> print("Collatz seed number: ", collatz_number)
> while True:
> counter += 1
> collatz_number = collatz(collatz_number)
> print("Collatz number", counter, ": ", collatz_number)
> if collatz_number == 1:
> print("The Collatz sequence has once again converged to 1!")
> break
> #----------------------------------------------------------------------------
>
> My understanding of best practice here is that I should not have any
> print() calls inside my generate_collatz_sequence() function. I
> _could_ store the generated sequence in a list and return it, but that
> does not seem like good use of RAM if some user-supplied seed value
> led to kazillions of Collatz sequence numbers being generated. As it
> stands there will be no theoretical RAM issues as the numbers are
> being generated and then outputted one at a time. OTOH, if I created
> some kind of display messages function, I don't see how I have gained
> anything as these calls to a display message function would just be
> taking the place of the print() calls. The end result would be the
> same -- display code interleaved with program logic code. What am I
> being dense about here?
>
You're not being dense, you're just trying to wrap your head around a
difficult concept. I suggest you read up on the model view controller
pattern. First hit on google
https://www.tomdalling.com/blog/software-design/model-view-controller-explained/
seems as good as any.
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list