PyCon UK 2019

Philosophy of Refactoring
2019-09-13, 16:30–17:00, Ferrier Hall

Many of us can recite the advantages of well factored code, yet in practice it
is easy to let standards slide. This talk explores the mindset one should
adopt to have a well factored codebase, complete with examples of how this
looks in practice.

At Deloitte we frequently switch between clients, which means we must be
prepared to work with a new tech stack at short notice. When learning a new
technology it may be natural to try and gain a knowledge of its syntax,
standard library and idioms. Yet an overarching
understanding of how to factor problems into well-conceived
functional units is even more important.

This talk will explain how to tame a difficult problem by adopting a rigorous
philosophy towards separation of concerns, a topic that is relevant to any
language but particularly important in the Python community, which places great
emphasis on beauty and readability.

Examples of how factoring can be
improved will be provided with the
code posted on GitHub, but the take home message is around
the mindset required to write well factored code,
not the tooling. Take a simple example of swapping two
variables, a and b. We could do
temp = a a = b b = temp
but the more Pythonic way is
a, b = b, a
For sure this is a neat trick, but that's not the point: the temp
variable exists at a different logical level of abstraction to a and b,
so having it exist in the same context increases the reader's cognitive load
by forcing them to consider both core business logic
and the mechanics of how to swap two variables at the same time.

Further examples will include: * Using urllib.parse and pathlib instead of manipulating strings; * Preferring the use of iterators and else: instead of control variables
in loops; * Error handling and setup/teardown using context managers; * Handling formatting logic using __format__; * Using sqlalchemy's tooling to construct SQL queries.

Let human beings, with their limitless creativity but poor
short term memory
, operate on a single level of abstraction. Let machines,
with their capacity to handle data
but lack of original thought, do the legwork of building a coherent

Is your proposal suitable for beginners? – True