This is going to be a quick post and applies to a lot of different languages, but it's something we've been doing in our Rails projects a decent amount.
If you're ever working on a larger codebase and you decide you want to add a parameter to a method, but are afraid to do so because it might break code elsewhere, consider simply adding a default value.
Take the following setup for example
class MyModel < ApplicationRecord def my_method(user_id) user = User.find user_id user end end
Now, let's say you want to modify this method so you can add another parameter. Here's a safe way you can do it:
class MyModel < ApplicationRecord def my_method(user_id, new_parameter=nil) user = User.find user_id if new_parameter do something end user end end
Now that new parameter's default value could have been anything, but the key here:
- Have a default value so that any code calling this method with the original parameters will still work
- When the new parameter is not passed in, have the method behave the exact same way it did before
With these two principles you'll be able to extend your code without breaking any existing code.