Why Shouldn't i put every function Public?
I don't know if i understood well, but as i kwon a private function can be called just from the class where it is, And a public function can be called from anywhere. Now: Why shouldn't i put everything on public? What should i put on private? I mean, if i put something on private or on public, what does change?
Sorry for really bad english, hope in an answer!
Answer by Dave-Carlile · Sep 21, 2015 at 08:53 PM
Private methods and fields are intended for things that are used internally by a class. The only things that should be public are things that need to be visible outside of the class in order for that class to be useful.
For example, I have Class A that creates a texture for me by doing some complex operations. Nobody outside of the class cares about those operations or the fact that an array and some other fields are used to cache things to make them more efficient. In fact, if that cache was public, Class B could change the cache and break Class A because it could ruin the assumptions that Class A makes about the validity of the cache. So that cache is safely hidden inside Class A where only Class A can change it.
In other words, access modifiers (that's what public, private, internal, etc. are called) are there to allow you to properly organize your code to help prevent bugs. As a rule, if something doesn't need to be public, don't make it public.
If you're just learning to write code I wouldn't worry about it too much. Learn the basics first and worry about "proper" object oriented programming when you start writing a lot more code.
Ok, thanks, i think i'v understood :). For now, if i don't nedd to do something complex, i'll put my functions as private, and if i have any dubt i'll post it here :). Thanks for the answer!
Your answer
Follow this Question
Related Questions
Google play services? 0 Answers
need script for launching missile 0 Answers
Acceleration issue 0 Answers
Unity Scripting Learn 1 Answer