Is it worth making get and set methods in OOP?

前端 未结 4 666
执念已碎
执念已碎 2020-12-14 10:37

I have seen some some projects in which classes are having get and set methods to manipulate insert data. Let me have an example here :

    class Student ext         


        
4条回答
  •  猫巷女王i
    2020-12-14 11:19

    An example as to why to sometimes use getters and setters: I have code that sets a value in 200 different files:

    $cat->name = 'Fery'          // in file one
    $favoriteCat->name = 'Tery'  // in another file
    $fatCat->name = 'jery'             // in another file
    // 200 more calls in alot of places
    

    Imagine the customer suddenly has a new requirement: "all cat names must be prepended by 'Sweet'

    Now we must find all declarations of cats and replace their assignments:

    $cat->name = 'Sweet '.'Fery'
    // times 200   
    

    On the other hand, If we used a setter method all we need to do is add the code to add 'Sweet ' in one place:

    public function setCatname($catname)
    {
      $this->catName = 'Sweet ' . $catname;
    }
    

提交回复
热议问题