php - Why cant i just use public property and not be looked down at -


i see (and write) lot of code this:

class myclass {     private $_myproperty;      public function setmypropert($myproperty)     {          $this->_myproperty = $myproperty;     }      public function getmyproperty()     {          return $this->_myproperty;     } } 

since taught class properties should private.

however, want in above scenario:

class myclass {     public $myproperty; } 

thats less code , easier read. other developers down on code , fail code reviews etc. if not, still never fear of else seeing , making judgement.

why though? ingrained in developers of oop code? or there reason i'm missing, perhaps related testing, future maintenance or other non obvious technical reason. talking in scenario getter/setter noting more get/set.

if doing nothing in getters , setters, yes, may make property public. setters typically used check value make sure it's valid:

public function setfoo($foo) {     if (!is_string($foo)) {         throw new invalidargumentexception('no foo-l!');     }     $this->foo = $foo; } 

it's idea ensure integrity of class, that's encapsulation for. , if you're not doing checking now, may adding in future after have fixed 3rd bug resulting setting invalid values. if start switching method calls instead of property assignment, you'll have hard time retrofitting code that's setting properties.

best start actual encapsulation possible.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -