Skip to main content
Reading Time: 2 minutes

Single-File Chatbot to OOP

“When you find you have to add a feature to a program, and the program’s code is not structured in a convenient way to add the feature, first refactor the program to make it easy to add the feature, then add the feature.” ― Martin Fowler, Refactoring: Improving the Design of Existing Code

Yes, it’s time for another Refactoring Challenge! This time, I used a colleague’s chatbot but removed any sign of OOP. Now everything is in one single entry file. The challenge is to restructure the code in such a way, that you can extend the chatbot with new commands, services, or configurations. Ideally, each new extension should be possible by modifying 0 to a maximum of 1 file of code that already existed. And on top of all this: the code should be testable and tested!

Intentionally, there is no framework installed. The intention is to make you think about frameworks’ magic again. How would you deal with Dependency Injection? Config files? How to configure PHPUnit properly? And how does autoloading with composer work when you have to take care of it yourself?

Challenge in summary

Restructure the code, so that…

  • it is testable
  • it is extendable
  • it is configurable
  • changes and additions cause nearly no adjustment of your existing code

Tasks

  • Refactor existing code
  • Write tests
  • Make the configuration dynamic
  • Add new commands of your choosing
  • Add new services of your choosing
  • Fork the repository and publish your own solution

Rules

  • Don’t use a framework
  • You are allowed to use 3rd party libraries if necessary

Think of it as a survival challenge

“You’re stranded on a lonely island. Would you survive?”

– “Oh sure, I just put my house down there, connect to the electricity system, build a water connection, pish pash posh done!”

“But could you even light a fire without any of your support tools and frameworks?”

Again, it’s on you to choose the difficulty! If you’re a beginner, it might be hard enough to make it work with Symfony or Laravel. If you’re a little more experienced, you could lose the big framework but might want to use dependency injection or config processing. If you want to become the Bear Grills of programming, you might take on the challenge and implement it all by yourself.

Your choice!

Now let’s grab a coffee and enjoy the refactoring challenge! Good luck everyone ☕

https://github.com/moritzwachter/refactoring-challenge-2

Moritz Wachter

Author Moritz Wachter

More posts by Moritz Wachter