Private versus public methods

Now, coming back to the types of methods provided by classes, the send_sms method is a public method. This means that anyone working on our class can communicate with this method. This may not seem like a big deal if you are working on an application that no one else is working on. However, if you build an API or code library, it's vital that your public methods represent elements of functionality that you actually want other developers to use.

Public methods should rarely, if ever, be altered. This is because other developers may be relying on your public methods to be consistent, and a change to a public method may break components of their programs. Imagine if you developed the Google Maps API and you built a public method called get_coordinates, but out of the blue, you altered the method and reversed the order of the coordinates. All of the applications relying on your method will have their maps literally reversed. Obviously, this will upset developers.

So, if you can't change public methods, how can you work on a production application? That's where private methods come in. Private methods should never be called by outside services and should only be available within the class that's using them. This means that you can alter the behavior of your private methods (assuming that these changes don't have a domino effect and alter the public methods that they may be called from).

What exactly is a private method? A private method is a method that is only accessed by the class that it is contained in.

Ruby is so flexible that it allows private methods to be called; however, it is considered a bad programming practice. If a private method really needs to be called by an outside service, either it should be a public method or there is a design problem with the application that's forcing this behavior.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.157.6