There are several tasks that are similar, but not identical.
Create a Sub
or a Function
that does the task. Use parameters to pass in the things that are different between the tasks.
Use this pattern when you have tasks that are similar, but not identical. Like:
- Draw houses that are the same, except for their location and color.
- Show Web pages that are the same, except for title and main content.
- Printing invitations to a wedding. They're the same (date, time, location, bride's name…), except for the name of the guest.
It's best to write code once. Easier to write, easier to debug, easier to change. Programmers call it the DRY (don't repeat yourself) principle.
What to do when tasks are almost the same, but not identical? Write a Sub
or a Function
that does the things that are the same. Pass in as parameters the things that are different.
Here's the house example:
Instead of having five separate pieces of code, write the code once, wrap it in a Sub
, and pass it top
, left
, and color
.
Some examples.
Houses
drawHouse top:= 34, left:=45, color:=vbGreen
drawHouse top:= 49, left:=56, color:=vbBlue
...
Sub drawHouse(top as Integer, left as Integer, color as Integer)
'Every house is the same, except for their location and color
...
End Sub
Web pages
showPage title:="Welcome", content:="Welcome! This is the most fun site ever!"
showPage title:="Exercises", content:="Here are the exercises: " & exerciseList
...
Sub showPage(title as String, content as String)
'Every page has the same header, footer, sidebars, font, colors... Only title and content is different.
...
End Sub
Wedding invitations
printInvitation guest:="Wilma and Fred Flintstone"
printInvitation guest:="Betty and Barney Rubble"
...
Sub printInvitation(guest as String)
'Each one has the same date, time, location... Only the guest name is different.
...
End Sub