Search Results

Search found 356 results on 15 pages for 'getters'.

Page 1/15 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • When are Getters and Setters Justified

    - by Winston Ewert
    Getters and setters are often criticized as being not proper OO. On the other hand most OO code I've seen has extensive getters and setters. When are getters and setters justified? Do you try to avoid using them? Are they overused in general? If your favorite language has properties (mine does) then such things are also considered getters and setters for this question. They are same thing from an OO methodology perspective. They just have nicer syntax. Sources for Getter/Setter Criticism (some taken from comments to give them better visibility): http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html http://typicalprogrammer.com/?p=23 http://c2.com/cgi/wiki?AccessorsAreEvil http://www.darronschall.com/weblog/2005/03/no-brain-getter-and-setters.cfm http://www.adam-bien.com/roller/abien/entry/encapsulation_violation_with_getters_and To state the criticism simply: Getters and Setters allow you to manipulate the internal state of objects from outside of the object. This violates encapsulation. Only the object itself should care about its internal state. And an example Procedural version of code. struct Fridge { int cheese; } void go_shopping(Fridge fridge) { fridge.cheese += 5; } Mutator version of code: class Fridge { int cheese; void set_cheese(int _cheese) { cheese = _cheese; } int get_cheese() { return cheese; } } void go_shopping(Fridge fridge) { fridge.set_cheese(fridge.get_cheese() + 5); } The getters and setters made the code much more complicated without affording proper encapsulation. Because the internal state is accessible to other objects we don't gain a whole lot by adding these getters and setters. The question has been previously discussed on Stack Overflow: http://stackoverflow.com/questions/565095/java-are-getters-and-setters-evil http://stackoverflow.com/questions/996179

    Read the article

  • Data classes: getters and setters or different method design

    - by Frog
    I've been trying to design an interface for a data class I'm writing. This class stores styles for characters, for example whether the character is bold, italic or underlined. But also the font-size and the font-family. So it has different types of member variables. The easiest way to implement this would be to add getters and setters for every member variable, but this just feels wrong to me. It feels way more logical (and more OOP) to call style.format(BOLD, true) instead of style.setBold(true). So to use logical methods insteads of getters/setters. But I am facing two problems while implementing these methods: I would need a big switch statement with all member variables, since you can't access a variable by the contents of a string in C++. Moreover, you can't overload by return type, which means you can't write one getter like style.getFormatting(BOLD) (I know there are some tricks to do this, but these don't allow for parameters, which I would obviously need). However, if I would implement getters and setters, there are also issues. I would have to duplicate quite some code because styles can also have a parent styles, which means the getters have to look not only at the member variables of this style, but also at the variables of the parent styles. Because I wasn't able to figure out how to do this, I decided to ask a question a couple of weeks ago. See Object Oriented Programming: getters/setters or logical names. But in that question I didn't stress it would be just a data object and that I'm not making a text rendering engine, which was the reason one of the people that answered suggested I ask another question while making that clear (because his solution, the decorator pattern, isn't suitable for my problem). So please note that I'm not creating my own text rendering engine, I just use these classes to store data. Because I still haven't been able to find a solution to this problem I'd like to ask this question again: how would you design a styles class like this? And why would you do that? Thanks on forehand!

    Read the article

  • Naming conventions for complex getters in Java

    - by Simon
    Hi there! I was reading this C# article about the usage of properties and methods. It points out why and when to use properties or methods. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects I was asking myself how you could express this difference in Java, where you only use getters for the retrieval of data. What is your opinion?

    Read the article

  • TDD, DDD and the No-getters principle

    - by Justin
    Hi all, After several years of following the bad practice handed down from 'architects' at my place of work and thinking that there must be a better way, I've recently been reading up around TDD and DDD and I think the principles and practices would be a great fit for the complexity of the software we write. However, many of the TDD samples I have seen call a method on the domain object and then test properties of the object to ensure the behaviour executed correctly. On the other hand, several respected people in the industry (Greg Young most noticeably so) advocate the "no-getters" principle on our domain objects. My question therefore is: How does one test the functionality of a domain object if it is forbidden to retrieve its state? I believe I am missing something fundamental so please feel free to call me an idiot and enlighten me - any guidance would be greatly appreciated.

    Read the article

  • [PHP] Difference between normal and magic setters and getters

    - by Saif Bechan
    I am using a magic getter/setter class for my session variables, but I don't see any difference between normal setters and getters. The code: class session { public function __set($name, $value) { $_SESSION[$name] = $value; } public function __unset($name) { unset($_SESSION[$name]); } public function __get($name) { if(isset($_SESSION[$name])) { return $_SESSION[$name]; } } } Now the first thing I noticed is that I have to call $session->_unset('var_name') to remove the variable, nothing 'magical' about that. Secondly when I try to use $session->some_var this does not work. I can only get the session variable using $_SESSION['some_var']. I have looked at the PHP manual but the functions look the same as mine. Am I doing something wrong, or is there not really anything magic about these functions.

    Read the article

  • Difference between normal and magic setters and getters

    - by Saif Bechan
    I am using a magic getter/setter class for my session variables, but I don't see any difference between normal setters and getters. The code: class session { public function __set($name, $value) { $_SESSION[$name] = $value; } public function __unset($name) { unset($_SESSION[$name]); } public function __get($name) { if(isset($_SESSION[$name])) { return $_SESSION[$name]; } } } Now the first thing I noticed is that I have to call $session->_unset('var_name') to remove the variable, nothing 'magical' about that. Secondly when I try to use $session->some_var this does not work. I can only get the session variable using $_SESSION['some_var']. I have looked at the PHP manual but the functions look the same as mine. Am I doing something wrong, or is there not really anything magic about these functions.

    Read the article

  • What Getters and Setters should and shouldn't do.

    - by cyclotis04
    I've run into a lot of differing opinions on Getters and Setters lately, so I figured I should make it into it's own question. A previous question of mine received an immediate comment (later deleted) that stated setters shouldn't have any side effects, and a SetProperty method would be a better choice. Indeed, this seems to be Microsoft's opinion as well. However, their properties often raise events, such as Resized when a form's Width or Height property is set. OwenP also states "you shouldn't let a property throw exceptions, properties shouldn't have side effects, order shouldn't matter, and properties should return relatively quickly." Yet Michael Stum states that exceptions should be thrown while validating data within a setter. If your setter doesn't throw an exception, how could you effectively validate data, as so many of the answers to this question suggest? What about when you need to raise an event, like nearly all of Microsoft's Control's do? Aren't you then at the mercy of whomever subscribed to your event? If their handler performs a massive amount of information, or throws an error itself, what happens to your setter? Finally, what about lazy loading within the getter? This too could violate the previous guidelines. What is acceptable to place in a getter or setter, and what should be kept in only accessor methods?

    Read the article

  • Java design: too many getters

    - by dege
    After writing a few lesser programs when learning Java the way I've designed the programs is with Model-View-Control. With using MVC I have a plethora of getter methods in the model for the view to use. It feels that while I gain on using MVC, for every new value added I have to add two new methods in the model which quickly get all cluttered with getter & setters. So I was thinking, maybe I should use the notifyObserver method that takes an argument. But wouldn't feel very smart to send every value by itself either so I figured, maybe if I send a kind of container with all the values, preferably only those that actually changed. What this would accomplish would be that instead of having a whole lot of getter methods I could just have one method in the model which put all relevant values in the container. Then in the view I would have a method called from the update which extracted the values from the container and assigning them to the correct fields. I have two questions concerning this. First: is this actually a viable way to do this. Would you recommend me doing something along these lines? Secondly: if I do use this plan and I don't want to keep sending fields that didn't actually change. How would I handle that without having to have if statements to check if the value is not null for every single value?

    Read the article

  • Java Interface Usage Guidelines -- Are getters and setters in an interface bad?

    - by user68759
    What do people think of the best guidelines to use in an interface? What should and shouldn't go into an interface? I've heard people say that, as a general rule, an interface must only define behavior and not state. Does this mean that an interface shouldn't contain getters and setters? My opinion: Maybe not so for setters, but sometimes I think that getters are valid to be placed in an interface. This is merely to enforce the implementation classes to implement those getters and so to indicate that the clients are able to call those getters to check on something, for example.

    Read the article

  • What should be allowed inside getters and setters?

    - by Botond Balázs
    I got into an interesting internet argument about getter and setter methods and encapsulation. Someone said that all they should do is an assignment (setters) or a variable access (getters) to keep them "pure" and ensure encapsulation. Am I right that this would completely defeat the purpose of having getters and setters in the first place and validation and other logic (without strange side-effects of course) should be allowed? When should validation happen? When setting the value, inside the setter (to protect the object from ever entering an invalid state - my opinion) Before setting the value, outside the setter Inside the object, before each time the value is used Is a setter allowed to change the value (maybe convert a valid value to some canonical internal representation)?

    Read the article

  • Create automatically only getters in Eclipse

    - by lerad
    In Eclipse is it possible to create automatically Getters and Setters for a field. But I have a lot of private fields for which only getters should exist. Is somewhere in Eclipse a "create Getters" Function which does not create setters too? Well, it is not so much work to write getters, but doing it automatically would be nice :) Thank you, lerad

    Read the article

  • Implicit vs explicit getters/setters in AS3, which to use and why?

    - by James
    Since the advent of AS3 I have been working like this: private var loggy:String; public function getLoggy ():String { return loggy; } public function setLoggy ( loggy:String ):void { // checking to make sure loggy's new value is kosher etc... this.loggy = loggy; } and have avoided working like this: private var _loggy:String; public function get loggy ():String { return loggy; } public function set loggy ( loggy:String ):void { // checking to make sure loggy's new value is kosher etc... this.loggy = loggy; } I have avoided using AS3's implicit getters/setters partly so that I can just start typing "get.." and content assist will give me a list of all my getters, and likewise for my setters. I also dislike underscores in my code which turned me off the implicit route. Another reason is that I prefer the feel of this: whateverObject.setLoggy( "loggy's awesome new value!" ); to this: whateverObject.loggy = "loggy's awesome new value!"; I feel that the former better reflects what is actually happening in the code. I am calling functions, not setting values directly. After installing Flash Builder and the great new plugin SourceMate ( which helps to get some of the useful features that FDT is famous into FB ) I realized that when I use SourceMate's "generate getters and setters" feature it automatically sets my code up using the implicit route: private var _loggy:String; public function get loggy ():String { return loggy; } public function set loggy ( loggy:String ):void { // do whatever is needed to check to make sure loggy is an acceptable value this.loggy = loggy; } I figure that these SourceMate people must know what they are doing or they wouldn't be writing workflow enhancement plugins for coding in AS3, so now I am questioning my ways. So my question to you is: Can anyone give me a good reason why I should give up my explicit g/s ways, start using the implicit technique, and embrace those stinky little _underscores for my private vars? Or back me up in my reasons for doing things the way that I do?

    Read the article

  • The use of getters and setters for different programming languages [closed]

    - by leonhart88
    So I know there are a lot of questions on getters and setters in general, but I couldn't find something exactly like my question. I was wondering if people change the use of get/set depending on different languages. I started learning with C++ and was taught to use getters and setters. This is what I understand: In C++ (and Java?), a variable can either be public or private, but we cannot have a mix. For example, I can't have a read-only variable that can still be changed inside the class. It's either all public (can read and change it), or all private (can't read and can only change inside the class). Because of this (and possibly other reasons), we use getters and setters. In MATLAB, I can control the "setaccess" and "getaccess" properties of variables, so that I can make things read-only (can directly access the property, but can't overwrite it). In this case, I don't feel like I need a getter because I can just do class.property. Also, in Python it is considered "Pythonic" to not use getters/setters and to only put things into properties if needed. I don't really understand why its OK to have all public variables in Python, because that's opposite of what I learned when I started with C++. I'm just curious what other people's thoughts are on this. Would you use getters and setters for all languages? Would you only use it for C++/Java and do direct access in MATLAB and Python (which is what I am currently doing)? Is the second option considered bad? For my purposes, I am only referring to simple getters and setters (just return/set the value and do not do anything else). Thanks!

    Read the article

  • Are trivial protected getters blatant overkill?

    - by Panzercrisis
    Something I really have not thought about before (AS3 syntax): private var m_obj:Object; protected function get obj():Object { return m_obj; } private var m_str:String; protected function get str():String { return m_str; } At least subclasses won't be able to set m_obj or m_str (though they could still modify m_obj). Is this just blatant overkill? I am not talking about doing this as opposed to making them public. I am talking about doing this instead of just making the variables themselves protected. Like this: protected var m_obj:Object; //more accessible than a private variable with a protected getter protected var m_str:String; //more accessible than a private variable with a protected getter

    Read the article

  • Enforcing a coding template in the getters of a class in java

    - by Yoav Schwartz
    Hello, I want to make sure all getters of the classes in a certain package follow a given template. For example, all getters must be of the form: XXX getYYY(){ classLock.lock(); return YYY; finally{ classLock.unlock(); } } Basically, I want that my project will not compile/run unless all getters are of that form. What is the best way to do that? I would prefer a solution that can be used as an Eclipse plugin. Thanks, Yoav

    Read the article

  • Getters and Setters are bad OO design?

    - by Dan
    Getters and Setters are bad Briefly reading over the above article I find that getters and setters are bad OO design and should be avoided as they go against Encapsulation and Data Hiding. As this is the case how can it be avoided when creating objects and how can one model objects to take this into account. In cases where a getter or setter is required what other alternatives can be used? Thanks.

    Read the article

  • Correct OOP design without getters?

    - by kane77
    I recently read that getters/setters are evil and I have to say it makes sense, yet when I started learning OOP one of the first things I learned was "Encapsulate your fields" so I learned to create class give it some fields, create getters, setters for them and create constructor where I initialize these fields. And every time some other class needs to manipulate this object (or for instance display it) I pass it the object and it manipulate it using getters/setters. I can see problems with this approach. But how to do it right? For instance displaying/rendering object that is "data" class - let's say Person, that has name and date of birth. Should the class have method for displaying the object where some Renderer would be passed as an argument? Wouldn't that violate principle that class should have only one purpose (in this case store state) so it should not care about presentation of this object. Can you suggest some good resources where best practices in OOP design are presented? I'm planning to start a project in my spare time and I want it to be my learning project in correct OOP design..

    Read the article

  • Why are getters prefixed with the word "get"?

    - by Joey
    Generally speaking, creating a fluid API is something that makes all programmers happy; Both for the creators who write the interface, and the consumers who program against it. Looking beyond conventions, why is it that we prefix all our getters with the word "get". Omitting it usually results in a more fluid, easy to read set of instructions, which ultimately leads to happiness (however small or passive). Consider this very simple example. (pseudo code) Conventional: person = new Person("Joey") person.getName().toLower().print() Alternative: person = new Person("Joey") person.name().toLower().print() Of course this only applies to languages where getters/setters are the norm, but is not directed at any specific language. Were these conventions developed around technical limitations (disambiguation), or simply through the pursuit of a more explicit, intentional feeling type of interface, or perhaps this is just a case of trickle a down norm. What are your thoughts? And how would simple changes to these conventions impact your happiness / daily attitudes towards your craft (however minimal). Thanks.

    Read the article

  • Getters and Setters: Code smell, Necessary Evil, or Can't Live Without Them [closed]

    - by Avery Payne
    Possible Duplicate: Allen Holub wrote “You should never use get/set functions”, is he correct? Is there a good, no, a very good reason, to go through all the trouble of using getters and setters for object-oriented languages? What's wrong with just using a direct reference to a property or method? Is there some kind of "semantical coverup" that people don't want to talk about in polite company? Was I just too tired and fell asleep when someone walked out and said "Thou Shalt Write Copious Amounts of Code to Obtain Getters and Setters"? Follow-up after a year: It seems to be a common occurrence with Java, less so with Python. I'm beginning to wonder if this is more of a cultural phenomena (related to the limitations of the language) rather than "sage advice". The -1 question score is complete for-the-lulz as far as I am concerned. It's interesting that there are specific questions that are downvoted, not because they are "bad questions", but rather, because they hit someone's raw nerve.

    Read the article

  • "Default approach" when creating a class from scratch: getters for everything, or limited access?

    - by Prog
    Until recently I always had getters (and sometimes setters but not always) for all the fields in my class. It was my 'default': very automatic and I never doubted it. However recently some discussions on this site made me realize maybe it's not the best approach. When you create a class, you often don't know exactly how it's going to be used in the future by other classes. So in that sense, it's good to have getters and setter for all of the fields in the class. So other classes could use it in the future any way they want. Allowing this flexibility doesn't require you to over engineer anything, only to provide getters. However some would say it's better to limit the access to a class, and only allow access to certain fields, while other fields stay completely private. What is your 'default' approach when building a class from scratch? Do you make getters for all the fields? Or do you always choose selectively which fields to expose through a getter and which to keep completely private?

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >