Back to Browse

Code refactoring - 1 week, 1000 lines of code and no new features #raspberrypi #python

393 views
Jul 14, 2025
6:08

This video explains about code refactoring that I've been doing on my Raspberry Pi model railway application. The project is to create a graphical application for controlling a model railway using CBUS. More details at https://www.penguintutor.com/projects/pyvlcb As I'd been developing the code I was already aware that the amount of code in the MainWindow class was growing, and that it was becoming tightly coupled with several other classes. I'd put this off in favour of adding new features, but decided it reached a point where I needed to take a step back and refactor the code. This involved a significant refactoring and redesign of many of the classes. The following video explains that it's taken a week and involved changing over 1000 lines, to provide an improved structure. The main thing I achieved was to remove the mainwindow for needing to be passed to many of the features, this is to move it more towards the Model-View-Controller design pattern (MVC). I don't think I've quite reached he full sepearation that the MVC pattern provides, but it's certainly a lot less coupled than it as previously. I've also moved the Device class to a DeviceModel based around the Domain Model design pattern. This is based around a singleton class which is shared with other classes removing the need to call this through the MainWindow. Thirdly I've moved the communication between the various components to an Event Bus pattern. This fits in well with CBUS which uses a hardware event bus using a producer consumer model. Events from both the CBUS API and the GUI are published to the Event Bus, from where the various components (including API and GUI) listen for the events. This makes it easier for creating different events and passing them to the relevant consumers, but will also be important when I look at adding model railway automation as the project progresses. The code may not be completely decoupled and still has a few things that could be improved but is certainly in a much better state than it was before. This has been a worthwhile excercise and will hopefully result in better progress and cleaner code in future.

Download

1 formats

Video Formats

360pmp46.5 MB

Right-click 'Download' and select 'Save Link As' if the file opens in a new tab.

Code refactoring - 1 week, 1000 lines of code and no new features #raspberrypi #python | NatokHD