Event-Condition-Action: How to Write Clearer Code (Rough Draft)
ROUGH DRAFT (work in progress)
Hello fellow programmers. This is my first tutorial so if I have any mistakes or things are unclear, feel free to leave a comment and I'll make sure to improve this post wherever possible.
Event-Condition-Action: What is that?
The simplest definition I have come up with is the flow of instructions to a program. When communicating to your program (writing code) you are actually giving instructions to the programs. In reality, its no different than giving instructions to another human.
I believe I have broken down the best way to give instructions to both humans and programs.
Events
When giving instructions, we tend to use the word when. I.e:
*When (the dog gets hungry)
*When (the page is loaded)
*When (a button is clicked)
You always start off listening to when something happens. When coding functionality, there is most likely always a when. (At least I've traced any starting point of programming logic to always have one)
Action
Before I get to Condition, Action is a next step. I like to use the word it should to declare the action.
*It should (eat)
*It should (open a popup)
*It should (add a class to this element)
You will always have an action. There is no point in listening to an event if you aren't going to do something when you've heard it. Sometimes this can be multiple it should's. I.e. When the horse runs, it should put front left hoove up, right hoove up, back hoof up, etc. (Don't know if that's how horses actually run though)
Condition
Conditions are optional, but are most likely in your application, especially if you're not using an OOP language. You can tell a condition by the if.
*If (it hasn't eaten)
*If (url is on homepage)
*If (device is mobile)
If statements control what action(s) you will perform. Though this part is optional, strangely enough its the most important part of your application. If you aren't clear of the exact condition that should be met (===true) then you're application might do something completely different than you had wanted.
Conclusion
These are the ideas I've come up with through writing unit testing in Javascript recently. It seems with this idea of Event-Condition-Action in mind, you can write cleaner code and separate logic into functions a bit better. My next tutorial will be how to apply this in Behavior Driven Development, hopefully it'll make more since when I show sample code.
Thanks for reading. If you have any questions feel free to ask below.
Quick Theories
*If you're using an OOP language with function overloading, you can omit writing Conditions