FyredUp Posted June 18, 2020 Posted June 18, 2020 I've seen in multiple places instances of code that appears to perform identically given the objects are accessed differently. Off the top of my head there are: inventory and getInventory(), npcs and getNpcs(), objects and getObjects(). I'm just curious what the functional difference is between these two cases of accessing something? What should I prioritize using and why?
Nyb Posted June 18, 2020 Posted June 18, 2020 Inventory is the class, getInventory() returns you an instance of Inventory. https://osbot.org/api/org/osbot/rs07/script/MethodProvider.html#getInventory--
Chris Posted June 18, 2020 Posted June 18, 2020 (edited) Always use getters getBank() getInventory() getClient() etc Edited June 18, 2020 by Chris
FyredUp Posted June 19, 2020 Author Posted June 19, 2020 After looking into it a bit, given the scripts know all the information about the player, I don't see any reason why getX() is any better than X. In the MethodProvider class, the variables are public and the getters simply return those variables. I would understand using a getting if the class did not extend MethodProvider, but the scripts do extend it. I would argue the *only* reason to use getters is in case X is no longer in the same space, but I don't see that changing.
Nbacon Posted June 19, 2020 Posted June 19, 2020 There are more resons. If you work in the industry you find out people are id10ts and you should write code that holds peoples hands. Getter and setter play an important role by giving people access to data in a class. All java best Practices say to keep data private and to make getters and setters when Appropriate. When you make it so people can do what ever they want with data it could break your Internal code. You could do npcs=null and that would break thing Internally.
BravoTaco Posted June 19, 2020 Posted June 19, 2020 Always use getters when its available. Getters and Setters can be doing alot more under the hood than just returning a variable or just setting it to a different value. Take a look at this thread. In it, the settings variable was not returning the correct value of the run energy, but when he switched it to use the getter it worked.
zephruz Posted June 23, 2020 Posted June 23, 2020 The getter methods return values contained within a private static field in the MethodProvider class. Due to it being a static field it belongs to the class, rather than an instance of the class. If you were to call .inventory on an instance of a MethodProvider, you would not get the properties from the static field within the MethodProvider class as you would with the getter.