oop - Is public variable all that bad? -


i've read lot of articles "public vs getter/setter", still wonder if there part public variable.

or question is:

if you're going make new awesome programming languange, still going support public variable , why??

a public variable means have global accessible/changeable variable within scope of object. there use case this?

take example: have class databasequeryhandler has variable databaseaccessor. under circumstances want variable be:

  1. publicly accessible (i.e. gettable)
  2. publicly settable

option #1 can think of few - may want last insert id after insert operation, may want check errors last query generated, commit or rollback transactions, etc., , might make more logical sense have these methods written in class databaseaccessor databasequeryhandler.

option #2 less desirable, if doing oop , abiding solid principles, in particular regards isp , dip principles. in case, when want set variable databaseaccessor in databasequeryhandler? on construction only, , never @ time after that. want type-hinted @ interface level well, can code interfaces. also, why need arbitrary object able alter database accessor? happens if foo changes variable databasequeryhandler->databaseaccessor null , bar tries call databasequeryhandler->databaseaccessor->begintransaction()?

i'm giving 1 example here, , no means bullet proof. program in php (dodges hurled rotten fruit) , take oop , solid given looseness of language. i'm sure there arguments on both sides of fence, if you're considering using public class variable, instead consider needs access it, , how variable used. in cases functionality can exposed via public methods without allowing unexpected alteration of variable type.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -