- Phoenix Web Development
- Brandon Richey
- 249字
- 2021-08-27 18:28:22
Your objects have no power here
Another thing that might be a little more difficult to contend with, especially if you're coming from a language where object-oriented programming is treated as a first-class citizen, is that objects are not a thing you can use in Elixir to organize your code or group data and functionality together. Again, let's use JavaScript as an example, as follows:
var greeting = "Hello There"
greeting.toUpperCase() # Convert a string to upper case by calling a function on the "greeting" string object
# End result: "HELLO THERE"
Here, you'll instead want to get used to the concept of using modules and functions to accomplish the same things. You can think of modules as a collection of related functions that operate on particular sets or types of data, or are otherwise grouped together by some sort of common element. So, the preceding block of code would instead be written as the following in Elixir:
greeting = "Hello There"
String.upcase(greeting) # Results in the same "HELLO THERE" message as the Javascript example
This is going to be a very common pattern that you should familiarize yourself, as you will frequently see function called as [Module Name].[Function Name]([Arguments]). Try to shy away from calling functions on objects and data and instead get used to calling functions with the module name.