Should I use getters and setters in constructors?










3















When initialising a class, is it good practice to use the getter and setter functions in the constructors?



Or is it good practice to set the variables directly, since the constructor could be considered a kind of mutator?










share|improve this question



















  • 3





    if you have some customization code in your setter, then use it, otherwise leave it simple as this.x = x;

    – Kartik
    Nov 13 '18 at 23:11






  • 4





    Why would you use getters in the constructor? That seems dangerous (what is there to get, the instance is still being constructed). Using a setter seems justifiable.

    – Elliott Frisch
    Nov 13 '18 at 23:11












  • @Kartik, except you setter could have been overridden and your customization code won't get run.

    – rghome
    Nov 14 '18 at 0:00











  • @rghome good point, but (I might be wrong) if you are overriding the setter, it will almost always mean that you are overriding the field. And in that case, the parent class constructor will be of no use.

    – Kartik
    Nov 14 '18 at 0:04











  • I think the answer to that is "not necessarily".

    – rghome
    Nov 14 '18 at 0:11















3















When initialising a class, is it good practice to use the getter and setter functions in the constructors?



Or is it good practice to set the variables directly, since the constructor could be considered a kind of mutator?










share|improve this question



















  • 3





    if you have some customization code in your setter, then use it, otherwise leave it simple as this.x = x;

    – Kartik
    Nov 13 '18 at 23:11






  • 4





    Why would you use getters in the constructor? That seems dangerous (what is there to get, the instance is still being constructed). Using a setter seems justifiable.

    – Elliott Frisch
    Nov 13 '18 at 23:11












  • @Kartik, except you setter could have been overridden and your customization code won't get run.

    – rghome
    Nov 14 '18 at 0:00











  • @rghome good point, but (I might be wrong) if you are overriding the setter, it will almost always mean that you are overriding the field. And in that case, the parent class constructor will be of no use.

    – Kartik
    Nov 14 '18 at 0:04











  • I think the answer to that is "not necessarily".

    – rghome
    Nov 14 '18 at 0:11













3












3








3








When initialising a class, is it good practice to use the getter and setter functions in the constructors?



Or is it good practice to set the variables directly, since the constructor could be considered a kind of mutator?










share|improve this question
















When initialising a class, is it good practice to use the getter and setter functions in the constructors?



Or is it good practice to set the variables directly, since the constructor could be considered a kind of mutator?







java






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 0:17









rghome

4,80462641




4,80462641










asked Nov 13 '18 at 23:09









JarrydJarryd

316211




316211







  • 3





    if you have some customization code in your setter, then use it, otherwise leave it simple as this.x = x;

    – Kartik
    Nov 13 '18 at 23:11






  • 4





    Why would you use getters in the constructor? That seems dangerous (what is there to get, the instance is still being constructed). Using a setter seems justifiable.

    – Elliott Frisch
    Nov 13 '18 at 23:11












  • @Kartik, except you setter could have been overridden and your customization code won't get run.

    – rghome
    Nov 14 '18 at 0:00











  • @rghome good point, but (I might be wrong) if you are overriding the setter, it will almost always mean that you are overriding the field. And in that case, the parent class constructor will be of no use.

    – Kartik
    Nov 14 '18 at 0:04











  • I think the answer to that is "not necessarily".

    – rghome
    Nov 14 '18 at 0:11












  • 3





    if you have some customization code in your setter, then use it, otherwise leave it simple as this.x = x;

    – Kartik
    Nov 13 '18 at 23:11






  • 4





    Why would you use getters in the constructor? That seems dangerous (what is there to get, the instance is still being constructed). Using a setter seems justifiable.

    – Elliott Frisch
    Nov 13 '18 at 23:11












  • @Kartik, except you setter could have been overridden and your customization code won't get run.

    – rghome
    Nov 14 '18 at 0:00











  • @rghome good point, but (I might be wrong) if you are overriding the setter, it will almost always mean that you are overriding the field. And in that case, the parent class constructor will be of no use.

    – Kartik
    Nov 14 '18 at 0:04











  • I think the answer to that is "not necessarily".

    – rghome
    Nov 14 '18 at 0:11







3




3





if you have some customization code in your setter, then use it, otherwise leave it simple as this.x = x;

– Kartik
Nov 13 '18 at 23:11





if you have some customization code in your setter, then use it, otherwise leave it simple as this.x = x;

– Kartik
Nov 13 '18 at 23:11




4




4





Why would you use getters in the constructor? That seems dangerous (what is there to get, the instance is still being constructed). Using a setter seems justifiable.

– Elliott Frisch
Nov 13 '18 at 23:11






Why would you use getters in the constructor? That seems dangerous (what is there to get, the instance is still being constructed). Using a setter seems justifiable.

– Elliott Frisch
Nov 13 '18 at 23:11














@Kartik, except you setter could have been overridden and your customization code won't get run.

– rghome
Nov 14 '18 at 0:00





@Kartik, except you setter could have been overridden and your customization code won't get run.

– rghome
Nov 14 '18 at 0:00













@rghome good point, but (I might be wrong) if you are overriding the setter, it will almost always mean that you are overriding the field. And in that case, the parent class constructor will be of no use.

– Kartik
Nov 14 '18 at 0:04





@rghome good point, but (I might be wrong) if you are overriding the setter, it will almost always mean that you are overriding the field. And in that case, the parent class constructor will be of no use.

– Kartik
Nov 14 '18 at 0:04













I think the answer to that is "not necessarily".

– rghome
Nov 14 '18 at 0:11





I think the answer to that is "not necessarily".

– rghome
Nov 14 '18 at 0:11












3 Answers
3






active

oldest

votes


















5














You should not call getters and setters from the constructor.



A constructor constructs the specific class in which it is defined. It is its job to initialise the fields because - well - nothing else will.



The only way to guarantee initialising the fields is to assign them. If you call a setter there is a chance it could be overridden and it might do something else. It might call a method in sub-class which is not initialised yet.



Calling a getter is also a bad idea if you are just getting a field from the same class. If it has been declared in the super-class you might justify it; if you need to get data from the super-class in the sub-class, you will have to call the getter (unless it is protected). If you need to communicate data from a sub-class to the super-class during construction you should pass it as a parameter. But this is a different use-case to what you are describing and the sub-class would probably not have your own field corresponding to the getter anyway.



If you have any "special" initialisation code, put that in a separate private method and call it from both the constructor and the setter separately.






share|improve this answer
































    2














    It depends, do you plan on ever subclassing this class, should someone else be able to subclass your class?



    • If the answer is no then, you could use it, but I would say it's
      generally bad practice to do so for several reason, if you don't explicitly forbid inheritance then the class can be subclassed and the methods overridden see quote below. In general it's good practice to aim for as much immutability as you can and using getters/setters keeps you from doing that. I would also argue that Constructors should only have parameters that are necessary to initialize a class to a valid state. If they can be also passed in using setters then they might not be necessary for a valid state to be achieved.

    • If you want to design your class with inheritance in mind then the answer is no and if you use init method it can't use getters/setters either, or any method that can be overriden.
      Direct quote from Effective Java 2nd Edition:


    There are a few more restrictions that a class must obey to allow
    inheritance. Constructors must not invoke overridable methods,
    directly or indirectly
    . If you violate this rule, program failure will
    result. The superclass constructor runs before the subclass
    constructor, so the overriding method in the subclass will get invoked
    before the subclass constructor has run. If the overriding method
    depends on any initialization performed by the subclass constructor,
    the method will not behave as expected.







    share|improve this answer
































      0














      No, the point of having accessors and mutators is to be able to access private fields from another class in the same package.



      You technically could, but mutating variables from the constructor defeats the purpose of initializing. Accessing variables would simply be adding an extra step to getting its contents.



      So yes, you should just reassign the values you want to your variables directly.






      share|improve this answer






















        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53290861%2fshould-i-use-getters-and-setters-in-constructors%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        5














        You should not call getters and setters from the constructor.



        A constructor constructs the specific class in which it is defined. It is its job to initialise the fields because - well - nothing else will.



        The only way to guarantee initialising the fields is to assign them. If you call a setter there is a chance it could be overridden and it might do something else. It might call a method in sub-class which is not initialised yet.



        Calling a getter is also a bad idea if you are just getting a field from the same class. If it has been declared in the super-class you might justify it; if you need to get data from the super-class in the sub-class, you will have to call the getter (unless it is protected). If you need to communicate data from a sub-class to the super-class during construction you should pass it as a parameter. But this is a different use-case to what you are describing and the sub-class would probably not have your own field corresponding to the getter anyway.



        If you have any "special" initialisation code, put that in a separate private method and call it from both the constructor and the setter separately.






        share|improve this answer





























          5














          You should not call getters and setters from the constructor.



          A constructor constructs the specific class in which it is defined. It is its job to initialise the fields because - well - nothing else will.



          The only way to guarantee initialising the fields is to assign them. If you call a setter there is a chance it could be overridden and it might do something else. It might call a method in sub-class which is not initialised yet.



          Calling a getter is also a bad idea if you are just getting a field from the same class. If it has been declared in the super-class you might justify it; if you need to get data from the super-class in the sub-class, you will have to call the getter (unless it is protected). If you need to communicate data from a sub-class to the super-class during construction you should pass it as a parameter. But this is a different use-case to what you are describing and the sub-class would probably not have your own field corresponding to the getter anyway.



          If you have any "special" initialisation code, put that in a separate private method and call it from both the constructor and the setter separately.






          share|improve this answer



























            5












            5








            5







            You should not call getters and setters from the constructor.



            A constructor constructs the specific class in which it is defined. It is its job to initialise the fields because - well - nothing else will.



            The only way to guarantee initialising the fields is to assign them. If you call a setter there is a chance it could be overridden and it might do something else. It might call a method in sub-class which is not initialised yet.



            Calling a getter is also a bad idea if you are just getting a field from the same class. If it has been declared in the super-class you might justify it; if you need to get data from the super-class in the sub-class, you will have to call the getter (unless it is protected). If you need to communicate data from a sub-class to the super-class during construction you should pass it as a parameter. But this is a different use-case to what you are describing and the sub-class would probably not have your own field corresponding to the getter anyway.



            If you have any "special" initialisation code, put that in a separate private method and call it from both the constructor and the setter separately.






            share|improve this answer















            You should not call getters and setters from the constructor.



            A constructor constructs the specific class in which it is defined. It is its job to initialise the fields because - well - nothing else will.



            The only way to guarantee initialising the fields is to assign them. If you call a setter there is a chance it could be overridden and it might do something else. It might call a method in sub-class which is not initialised yet.



            Calling a getter is also a bad idea if you are just getting a field from the same class. If it has been declared in the super-class you might justify it; if you need to get data from the super-class in the sub-class, you will have to call the getter (unless it is protected). If you need to communicate data from a sub-class to the super-class during construction you should pass it as a parameter. But this is a different use-case to what you are describing and the sub-class would probably not have your own field corresponding to the getter anyway.



            If you have any "special" initialisation code, put that in a separate private method and call it from both the constructor and the setter separately.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 17 '18 at 15:31

























            answered Nov 14 '18 at 0:10









            rghomerghome

            4,80462641




            4,80462641























                2














                It depends, do you plan on ever subclassing this class, should someone else be able to subclass your class?



                • If the answer is no then, you could use it, but I would say it's
                  generally bad practice to do so for several reason, if you don't explicitly forbid inheritance then the class can be subclassed and the methods overridden see quote below. In general it's good practice to aim for as much immutability as you can and using getters/setters keeps you from doing that. I would also argue that Constructors should only have parameters that are necessary to initialize a class to a valid state. If they can be also passed in using setters then they might not be necessary for a valid state to be achieved.

                • If you want to design your class with inheritance in mind then the answer is no and if you use init method it can't use getters/setters either, or any method that can be overriden.
                  Direct quote from Effective Java 2nd Edition:


                There are a few more restrictions that a class must obey to allow
                inheritance. Constructors must not invoke overridable methods,
                directly or indirectly
                . If you violate this rule, program failure will
                result. The superclass constructor runs before the subclass
                constructor, so the overriding method in the subclass will get invoked
                before the subclass constructor has run. If the overriding method
                depends on any initialization performed by the subclass constructor,
                the method will not behave as expected.







                share|improve this answer





























                  2














                  It depends, do you plan on ever subclassing this class, should someone else be able to subclass your class?



                  • If the answer is no then, you could use it, but I would say it's
                    generally bad practice to do so for several reason, if you don't explicitly forbid inheritance then the class can be subclassed and the methods overridden see quote below. In general it's good practice to aim for as much immutability as you can and using getters/setters keeps you from doing that. I would also argue that Constructors should only have parameters that are necessary to initialize a class to a valid state. If they can be also passed in using setters then they might not be necessary for a valid state to be achieved.

                  • If you want to design your class with inheritance in mind then the answer is no and if you use init method it can't use getters/setters either, or any method that can be overriden.
                    Direct quote from Effective Java 2nd Edition:


                  There are a few more restrictions that a class must obey to allow
                  inheritance. Constructors must not invoke overridable methods,
                  directly or indirectly
                  . If you violate this rule, program failure will
                  result. The superclass constructor runs before the subclass
                  constructor, so the overriding method in the subclass will get invoked
                  before the subclass constructor has run. If the overriding method
                  depends on any initialization performed by the subclass constructor,
                  the method will not behave as expected.







                  share|improve this answer



























                    2












                    2








                    2







                    It depends, do you plan on ever subclassing this class, should someone else be able to subclass your class?



                    • If the answer is no then, you could use it, but I would say it's
                      generally bad practice to do so for several reason, if you don't explicitly forbid inheritance then the class can be subclassed and the methods overridden see quote below. In general it's good practice to aim for as much immutability as you can and using getters/setters keeps you from doing that. I would also argue that Constructors should only have parameters that are necessary to initialize a class to a valid state. If they can be also passed in using setters then they might not be necessary for a valid state to be achieved.

                    • If you want to design your class with inheritance in mind then the answer is no and if you use init method it can't use getters/setters either, or any method that can be overriden.
                      Direct quote from Effective Java 2nd Edition:


                    There are a few more restrictions that a class must obey to allow
                    inheritance. Constructors must not invoke overridable methods,
                    directly or indirectly
                    . If you violate this rule, program failure will
                    result. The superclass constructor runs before the subclass
                    constructor, so the overriding method in the subclass will get invoked
                    before the subclass constructor has run. If the overriding method
                    depends on any initialization performed by the subclass constructor,
                    the method will not behave as expected.







                    share|improve this answer















                    It depends, do you plan on ever subclassing this class, should someone else be able to subclass your class?



                    • If the answer is no then, you could use it, but I would say it's
                      generally bad practice to do so for several reason, if you don't explicitly forbid inheritance then the class can be subclassed and the methods overridden see quote below. In general it's good practice to aim for as much immutability as you can and using getters/setters keeps you from doing that. I would also argue that Constructors should only have parameters that are necessary to initialize a class to a valid state. If they can be also passed in using setters then they might not be necessary for a valid state to be achieved.

                    • If you want to design your class with inheritance in mind then the answer is no and if you use init method it can't use getters/setters either, or any method that can be overriden.
                      Direct quote from Effective Java 2nd Edition:


                    There are a few more restrictions that a class must obey to allow
                    inheritance. Constructors must not invoke overridable methods,
                    directly or indirectly
                    . If you violate this rule, program failure will
                    result. The superclass constructor runs before the subclass
                    constructor, so the overriding method in the subclass will get invoked
                    before the subclass constructor has run. If the overriding method
                    depends on any initialization performed by the subclass constructor,
                    the method will not behave as expected.








                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 19 '18 at 11:14

























                    answered Nov 14 '18 at 0:39









                    KameeCodingKameeCoding

                    348520




                    348520





















                        0














                        No, the point of having accessors and mutators is to be able to access private fields from another class in the same package.



                        You technically could, but mutating variables from the constructor defeats the purpose of initializing. Accessing variables would simply be adding an extra step to getting its contents.



                        So yes, you should just reassign the values you want to your variables directly.






                        share|improve this answer



























                          0














                          No, the point of having accessors and mutators is to be able to access private fields from another class in the same package.



                          You technically could, but mutating variables from the constructor defeats the purpose of initializing. Accessing variables would simply be adding an extra step to getting its contents.



                          So yes, you should just reassign the values you want to your variables directly.






                          share|improve this answer

























                            0












                            0








                            0







                            No, the point of having accessors and mutators is to be able to access private fields from another class in the same package.



                            You technically could, but mutating variables from the constructor defeats the purpose of initializing. Accessing variables would simply be adding an extra step to getting its contents.



                            So yes, you should just reassign the values you want to your variables directly.






                            share|improve this answer













                            No, the point of having accessors and mutators is to be able to access private fields from another class in the same package.



                            You technically could, but mutating variables from the constructor defeats the purpose of initializing. Accessing variables would simply be adding an extra step to getting its contents.



                            So yes, you should just reassign the values you want to your variables directly.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 14 '18 at 2:59









                            Shawn GeShawn Ge

                            1




                            1



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53290861%2fshould-i-use-getters-and-setters-in-constructors%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                What does pagestruct do in Eviews?

                                Dutch intervention in Lombok and Karangasem

                                Channel Islands