Should a class provide public mutators for all its private fields? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Should the methods of a class call its own getters and setters?What is the use of Association, Aggregation and Composition?“Default approach” when creating a class from scratch: getters for everything, or limited access?Public versus private inheritance when some of the parent's methods need to be exposed?Access fields of super class from derived classesMeaning of using getters and setters and Uses of parameterized Constructor.Encapsulation and Displaying InformationIs encapsulation still one of the elephants OOP stands on?Encapsulation and SRPAre groovy automatic getters and setter effectively any different to public variables?Should I use accessors or public static fields for global constants?

Declining "dulcis" in context

What are the out-of-universe reasons for the references to Toby Maguire-era Spider-Man in ITSV

Is there such thing as an Availability Group failover trigger?

How could we fake a moon landing now?

Why are both D and D# fitting into my E minor key?

Why aren't air breathing engines used as small first stages

Why do we bend a book to keep it straight?

What does the "x" in "x86" represent?

Around usage results

Fundamental Solution of the Pell Equation

What does "lightly crushed" mean for cardamon pods?

Do jazz musicians improvise on the parent scale in addition to the chord-scales?

Most bit efficient text communication method?

Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?

Amount of permutations on an NxNxN Rubik's Cube

What is the longest distance a player character can jump in one leap?

Is grep documentation wrong?

Generate an RGB colour grid

Wu formula for manifolds with boundary

How do I stop a creek from eroding my steep embankment?

2001: A Space Odyssey's use of the song "Daisy Bell" (Bicycle Built for Two); life imitates art or vice-versa?

Can a party unilaterally change candidates in preparation for a General election?

Has negative voting ever been officially implemented in elections, or seriously proposed, or even studied?

Where are Serre’s lectures at Collège de France to be found?



Should a class provide public mutators for all its private fields?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)Should the methods of a class call its own getters and setters?What is the use of Association, Aggregation and Composition?“Default approach” when creating a class from scratch: getters for everything, or limited access?Public versus private inheritance when some of the parent's methods need to be exposed?Access fields of super class from derived classesMeaning of using getters and setters and Uses of parameterized Constructor.Encapsulation and Displaying InformationIs encapsulation still one of the elephants OOP stands on?Encapsulation and SRPAre groovy automatic getters and setter effectively any different to public variables?Should I use accessors or public static fields for global constants?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I work on refactoring an Java application based on a CAST audit. One of the criterion says that




To respect OO encapsulation concepts, private fields should always be
accessed through accessors




So far, so good. However, the audit highlights all private fields in the class that have no mutators, regardless how they are being used.



In my case, these fields are only accessed from inside the class.



I could provide private accessors for all of them, but for readability purposes, I do not think it is a good idea. Furthermore, I do not see how providing private getters for private attributes enhances OO encapsulation.



I could also provide public mutators for all fields. I have seen it done in many applications. Come to think of it, most IDEs provide a functionnality that automatically generates public mutators for all of the class attributes...



But I wonder, is it not against the very principle of encapsulation to provide public accessors for private attributes that are only meant to be used inside the class?



EDIT : my question is not about the use of accessors inside their own class. It is about the relevance of providing public accessors for all private fields in the class, regardless they are used outside the class or not.










share|improve this question









New contributor




Pikuni is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    Possible duplicate of Should the methods of a class call its own getters and setters?

    – gnat
    15 hours ago











  • Your suspicions are correct: it's actually an anti-pattern to provide public mutators for all fields (or even most fields). Unfortunately this practice was historically required by some frameworks/libs (e.g. some persistence frameworks), but it's a historical artifact that goes against OOP practices.

    – Andres F.
    7 hours ago

















2















I work on refactoring an Java application based on a CAST audit. One of the criterion says that




To respect OO encapsulation concepts, private fields should always be
accessed through accessors




So far, so good. However, the audit highlights all private fields in the class that have no mutators, regardless how they are being used.



In my case, these fields are only accessed from inside the class.



I could provide private accessors for all of them, but for readability purposes, I do not think it is a good idea. Furthermore, I do not see how providing private getters for private attributes enhances OO encapsulation.



I could also provide public mutators for all fields. I have seen it done in many applications. Come to think of it, most IDEs provide a functionnality that automatically generates public mutators for all of the class attributes...



But I wonder, is it not against the very principle of encapsulation to provide public accessors for private attributes that are only meant to be used inside the class?



EDIT : my question is not about the use of accessors inside their own class. It is about the relevance of providing public accessors for all private fields in the class, regardless they are used outside the class or not.










share|improve this question









New contributor




Pikuni is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 1





    Possible duplicate of Should the methods of a class call its own getters and setters?

    – gnat
    15 hours ago











  • Your suspicions are correct: it's actually an anti-pattern to provide public mutators for all fields (or even most fields). Unfortunately this practice was historically required by some frameworks/libs (e.g. some persistence frameworks), but it's a historical artifact that goes against OOP practices.

    – Andres F.
    7 hours ago













2












2








2


1






I work on refactoring an Java application based on a CAST audit. One of the criterion says that




To respect OO encapsulation concepts, private fields should always be
accessed through accessors




So far, so good. However, the audit highlights all private fields in the class that have no mutators, regardless how they are being used.



In my case, these fields are only accessed from inside the class.



I could provide private accessors for all of them, but for readability purposes, I do not think it is a good idea. Furthermore, I do not see how providing private getters for private attributes enhances OO encapsulation.



I could also provide public mutators for all fields. I have seen it done in many applications. Come to think of it, most IDEs provide a functionnality that automatically generates public mutators for all of the class attributes...



But I wonder, is it not against the very principle of encapsulation to provide public accessors for private attributes that are only meant to be used inside the class?



EDIT : my question is not about the use of accessors inside their own class. It is about the relevance of providing public accessors for all private fields in the class, regardless they are used outside the class or not.










share|improve this question









New contributor




Pikuni is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












I work on refactoring an Java application based on a CAST audit. One of the criterion says that




To respect OO encapsulation concepts, private fields should always be
accessed through accessors




So far, so good. However, the audit highlights all private fields in the class that have no mutators, regardless how they are being used.



In my case, these fields are only accessed from inside the class.



I could provide private accessors for all of them, but for readability purposes, I do not think it is a good idea. Furthermore, I do not see how providing private getters for private attributes enhances OO encapsulation.



I could also provide public mutators for all fields. I have seen it done in many applications. Come to think of it, most IDEs provide a functionnality that automatically generates public mutators for all of the class attributes...



But I wonder, is it not against the very principle of encapsulation to provide public accessors for private attributes that are only meant to be used inside the class?



EDIT : my question is not about the use of accessors inside their own class. It is about the relevance of providing public accessors for all private fields in the class, regardless they are used outside the class or not.







java encapsulation getters






share|improve this question









New contributor




Pikuni is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Pikuni is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 10 hours ago







Pikuni













New contributor




Pikuni is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 15 hours ago









PikuniPikuni

265




265




New contributor




Pikuni is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Pikuni is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Pikuni is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 1





    Possible duplicate of Should the methods of a class call its own getters and setters?

    – gnat
    15 hours ago











  • Your suspicions are correct: it's actually an anti-pattern to provide public mutators for all fields (or even most fields). Unfortunately this practice was historically required by some frameworks/libs (e.g. some persistence frameworks), but it's a historical artifact that goes against OOP practices.

    – Andres F.
    7 hours ago












  • 1





    Possible duplicate of Should the methods of a class call its own getters and setters?

    – gnat
    15 hours ago











  • Your suspicions are correct: it's actually an anti-pattern to provide public mutators for all fields (or even most fields). Unfortunately this practice was historically required by some frameworks/libs (e.g. some persistence frameworks), but it's a historical artifact that goes against OOP practices.

    – Andres F.
    7 hours ago







1




1





Possible duplicate of Should the methods of a class call its own getters and setters?

– gnat
15 hours ago





Possible duplicate of Should the methods of a class call its own getters and setters?

– gnat
15 hours ago













Your suspicions are correct: it's actually an anti-pattern to provide public mutators for all fields (or even most fields). Unfortunately this practice was historically required by some frameworks/libs (e.g. some persistence frameworks), but it's a historical artifact that goes against OOP practices.

– Andres F.
7 hours ago





Your suspicions are correct: it's actually an anti-pattern to provide public mutators for all fields (or even most fields). Unfortunately this practice was historically required by some frameworks/libs (e.g. some persistence frameworks), but it's a historical artifact that goes against OOP practices.

– Andres F.
7 hours ago










2 Answers
2






active

oldest

votes


















7














So I did some googling.



here is the rule you quote:




To respect OO encapsulation concepts, private fields should always be
accessed through accessors




https://www.appmarq.com/public/changeability,4576,Provide-accessors-to-Private-Fields



Its remediation:




Write a getter and setter to each private field




And a reference. Presumably for justification:




http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html
JavaBeans(TM) Specification 1.01 Final Release - paragraph 8.3 Design
Patterns for Properties p 55




However, if you check the reference it says nothing of the sort. It's all about how properties are implemented.



That coupled with the awful appmarq site which prevents text selection. Lead me to believe that the entire CAST audit is basically worthless.



The idea that every private field should be backing a property is ridiculous. Presumably what they mean is: "Use properties rather than public fields" or maybe "Beware of stateful objects!"






share|improve this answer























  • I had not checked the reference (shame on me), but you are right, the content of Section 8.3 is not really about the violated rule. This criterion is quite unclear, because the description of the violation says Accessors are identified using the following java bean naming conventions: "set" and "get" followed by the name of the field with the first char in uppercase (case sensitive). For Boolean fields, the getter can also be named "is" followed by the name of the field. I think in the end, it mixes proper naming and relevance of the use of public accessors, which are different issues.

    – Pikuni
    10 hours ago


















5














No, you don't seem to have missed anything. That audit sounds misguided, among other things it implies immutable objects, like String, are "against OO encapsulation concepts".






share|improve this answer























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "131"
    ;
    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: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    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
    );



    );






    Pikuni is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsoftwareengineering.stackexchange.com%2fquestions%2f390498%2fshould-a-class-provide-public-mutators-for-all-its-private-fields%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    7














    So I did some googling.



    here is the rule you quote:




    To respect OO encapsulation concepts, private fields should always be
    accessed through accessors




    https://www.appmarq.com/public/changeability,4576,Provide-accessors-to-Private-Fields



    Its remediation:




    Write a getter and setter to each private field




    And a reference. Presumably for justification:




    http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html
    JavaBeans(TM) Specification 1.01 Final Release - paragraph 8.3 Design
    Patterns for Properties p 55




    However, if you check the reference it says nothing of the sort. It's all about how properties are implemented.



    That coupled with the awful appmarq site which prevents text selection. Lead me to believe that the entire CAST audit is basically worthless.



    The idea that every private field should be backing a property is ridiculous. Presumably what they mean is: "Use properties rather than public fields" or maybe "Beware of stateful objects!"






    share|improve this answer























    • I had not checked the reference (shame on me), but you are right, the content of Section 8.3 is not really about the violated rule. This criterion is quite unclear, because the description of the violation says Accessors are identified using the following java bean naming conventions: "set" and "get" followed by the name of the field with the first char in uppercase (case sensitive). For Boolean fields, the getter can also be named "is" followed by the name of the field. I think in the end, it mixes proper naming and relevance of the use of public accessors, which are different issues.

      – Pikuni
      10 hours ago















    7














    So I did some googling.



    here is the rule you quote:




    To respect OO encapsulation concepts, private fields should always be
    accessed through accessors




    https://www.appmarq.com/public/changeability,4576,Provide-accessors-to-Private-Fields



    Its remediation:




    Write a getter and setter to each private field




    And a reference. Presumably for justification:




    http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html
    JavaBeans(TM) Specification 1.01 Final Release - paragraph 8.3 Design
    Patterns for Properties p 55




    However, if you check the reference it says nothing of the sort. It's all about how properties are implemented.



    That coupled with the awful appmarq site which prevents text selection. Lead me to believe that the entire CAST audit is basically worthless.



    The idea that every private field should be backing a property is ridiculous. Presumably what they mean is: "Use properties rather than public fields" or maybe "Beware of stateful objects!"






    share|improve this answer























    • I had not checked the reference (shame on me), but you are right, the content of Section 8.3 is not really about the violated rule. This criterion is quite unclear, because the description of the violation says Accessors are identified using the following java bean naming conventions: "set" and "get" followed by the name of the field with the first char in uppercase (case sensitive). For Boolean fields, the getter can also be named "is" followed by the name of the field. I think in the end, it mixes proper naming and relevance of the use of public accessors, which are different issues.

      – Pikuni
      10 hours ago













    7












    7








    7







    So I did some googling.



    here is the rule you quote:




    To respect OO encapsulation concepts, private fields should always be
    accessed through accessors




    https://www.appmarq.com/public/changeability,4576,Provide-accessors-to-Private-Fields



    Its remediation:




    Write a getter and setter to each private field




    And a reference. Presumably for justification:




    http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html
    JavaBeans(TM) Specification 1.01 Final Release - paragraph 8.3 Design
    Patterns for Properties p 55




    However, if you check the reference it says nothing of the sort. It's all about how properties are implemented.



    That coupled with the awful appmarq site which prevents text selection. Lead me to believe that the entire CAST audit is basically worthless.



    The idea that every private field should be backing a property is ridiculous. Presumably what they mean is: "Use properties rather than public fields" or maybe "Beware of stateful objects!"






    share|improve this answer













    So I did some googling.



    here is the rule you quote:




    To respect OO encapsulation concepts, private fields should always be
    accessed through accessors




    https://www.appmarq.com/public/changeability,4576,Provide-accessors-to-Private-Fields



    Its remediation:




    Write a getter and setter to each private field




    And a reference. Presumably for justification:




    http://www.oracle.com/technetwork/java/javase/documentation/spec-136004.html
    JavaBeans(TM) Specification 1.01 Final Release - paragraph 8.3 Design
    Patterns for Properties p 55




    However, if you check the reference it says nothing of the sort. It's all about how properties are implemented.



    That coupled with the awful appmarq site which prevents text selection. Lead me to believe that the entire CAST audit is basically worthless.



    The idea that every private field should be backing a property is ridiculous. Presumably what they mean is: "Use properties rather than public fields" or maybe "Beware of stateful objects!"







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 12 hours ago









    EwanEwan

    44.2k33799




    44.2k33799












    • I had not checked the reference (shame on me), but you are right, the content of Section 8.3 is not really about the violated rule. This criterion is quite unclear, because the description of the violation says Accessors are identified using the following java bean naming conventions: "set" and "get" followed by the name of the field with the first char in uppercase (case sensitive). For Boolean fields, the getter can also be named "is" followed by the name of the field. I think in the end, it mixes proper naming and relevance of the use of public accessors, which are different issues.

      – Pikuni
      10 hours ago

















    • I had not checked the reference (shame on me), but you are right, the content of Section 8.3 is not really about the violated rule. This criterion is quite unclear, because the description of the violation says Accessors are identified using the following java bean naming conventions: "set" and "get" followed by the name of the field with the first char in uppercase (case sensitive). For Boolean fields, the getter can also be named "is" followed by the name of the field. I think in the end, it mixes proper naming and relevance of the use of public accessors, which are different issues.

      – Pikuni
      10 hours ago
















    I had not checked the reference (shame on me), but you are right, the content of Section 8.3 is not really about the violated rule. This criterion is quite unclear, because the description of the violation says Accessors are identified using the following java bean naming conventions: "set" and "get" followed by the name of the field with the first char in uppercase (case sensitive). For Boolean fields, the getter can also be named "is" followed by the name of the field. I think in the end, it mixes proper naming and relevance of the use of public accessors, which are different issues.

    – Pikuni
    10 hours ago





    I had not checked the reference (shame on me), but you are right, the content of Section 8.3 is not really about the violated rule. This criterion is quite unclear, because the description of the violation says Accessors are identified using the following java bean naming conventions: "set" and "get" followed by the name of the field with the first char in uppercase (case sensitive). For Boolean fields, the getter can also be named "is" followed by the name of the field. I think in the end, it mixes proper naming and relevance of the use of public accessors, which are different issues.

    – Pikuni
    10 hours ago













    5














    No, you don't seem to have missed anything. That audit sounds misguided, among other things it implies immutable objects, like String, are "against OO encapsulation concepts".






    share|improve this answer



























      5














      No, you don't seem to have missed anything. That audit sounds misguided, among other things it implies immutable objects, like String, are "against OO encapsulation concepts".






      share|improve this answer

























        5












        5








        5







        No, you don't seem to have missed anything. That audit sounds misguided, among other things it implies immutable objects, like String, are "against OO encapsulation concepts".






        share|improve this answer













        No, you don't seem to have missed anything. That audit sounds misguided, among other things it implies immutable objects, like String, are "against OO encapsulation concepts".







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 15 hours ago









        CalethCaleth

        6,51221420




        6,51221420




















            Pikuni is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            Pikuni is a new contributor. Be nice, and check out our Code of Conduct.












            Pikuni is a new contributor. Be nice, and check out our Code of Conduct.











            Pikuni is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Software Engineering Stack Exchange!


            • 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%2fsoftwareengineering.stackexchange.com%2fquestions%2f390498%2fshould-a-class-provide-public-mutators-for-all-its-private-fields%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







            -encapsulation, getters, java

            Popular posts from this blog

            Creating 100m^2 grid automatically using QGIS?Creating grid constrained within polygon in QGIS?Createing polygon layer from point data using QGIS?Creating vector grid using QGIS?Creating grid polygons from coordinates using R or PythonCreating grid from spatio temporal point data?Creating fields in attributes table using other layers using QGISCreate .shp vector grid in QGISQGIS Creating 4km point grid within polygonsCreate a vector grid over a raster layerVector Grid Creates just one grid

            What is this called? Old film camera viewer?What makes a good film camera?What to do with an old film camera?What should one look for when buying a used film camera?What is the value and age of this pre-1967 Ricoh 35 mm camera?DSLR recommendation, question about old Canon 35mm film Camera & lensesCan anyone identify the silver rangefinder-style camera in this advertisement?What kind of a Polaroid 600-camera is this?Will an old film camera still work even when not used in a very long time?What is this camera / Can I develop the film?How to fit an action camera into antique (bellows) housing?What to check when buying used and old film bodies?

            Why is this plane circling around the Lucknow airport every day?Why do aircraft on Flight Radar 24 jump around randomly sometimes?What airport has this walkway over a taxiway?How does Chicago O'Hare's tower sequence aircraft at peak capacity?Which airport is featured in this Delta commercial?After a crash, for how long is the airport closed?Can a passenger plane stand still in the air, or hover at a fixed location above a ground?What are those trucks towing around, and why?What is this airport outside of Cairo, Egypt?Which US airport has the lowest circling MDH?What is this airport video?