Hot answers tagged

50

So is there a reason why isn't this a OOP convention? My best guess: because it violates CQS You've got a command (changing the state of the object) and a query (returning a copy of state -- in this case, the object itself) mixed into the same method. That's not necessarily a problem, but it does violate some of the basic guidelines. For instance, in C++...


35

Show the UI with index 1, use index 0 in code. That said, I worked with audio devices like this and used index 1 for the channels and designed the code never to use "Index" or indexers to help avoid frustration. Some programmers still complained, so we changed it. Then other programmers complained. Just pick one and stick with it. There are bigger problems ...


32

Saving a few keystrokes isn't compelling. It might be nice, but OOP conventions care more about concepts and structures, not keystrokes. The return value is meaningless. Even more than being meaningless, the return value is misleading, since users may expect the return value to have meaning. They may expect that it is an "immutable setter" public FooHolder {...


25

This is not the most popular opinion but I don't see much of a difference. Setters and getters are a fairly bad idea. I've thought about it and honestly I can't come up with a difference between a setter/getter a property and a public variable in practice. In THEORY a setter and getter or property add a place to take some extra actions when a variable is ...


24

It feels like you're conflating the Identifier for the Channel with its position within a ChannelSet. The following is my visualisation of how your code/comments would look at the moment : public sealed class ChannelSet { private Channel[] channels; /// <summary>Retrieves the specified channel</summary> /// <param name="channelId"&...


21

Use both. Do not mix the UI with your core code. Internally (as a library) you should code "without knowing" how each element on the array will be called by the final user. Use the "natural" 0-indexed arrays and collections. The part of the program that joins the data with the UI, the view, should take care to correctly translate data between the User's ...


21

Simply exposing fields – whether as public fields, properties, or accessor methods – can be an indicator of insufficient object modelling. The result is that we ask an object for various data and make decisions on that data. So these decisions will be made outside of the object. If this happens repeatedly, maybe that decision should be the responsibility of ...


20

Have you ever heard about a property? A property is a field that has "built-in" accessors (getters and setters). Java, for instance, doesn't have properties, but it's recommended to write the getters and setters to a private field. C# has properties. So, why do we need getters and setters? Basically we need it to protect/shield the field. For instance, you'...


17

I think you are missing the point. Its not saying you should rename the setter and getter, but to have methods which add and remove items from the fridge. ie public class Fridge { private int numberOfCheeseSlices; public void AddCheeseSlices(int n) { if(n < 0) { throw new Exception("you cant add negative cheese!"); ...


12

I don't think this is an OOP convention, it's more related to the language design and its conventions. It seems you like to use Java. Java has a JavaBeans specification which specifies the return type of the setter to be void, i.e. it is in conflict with chaining of setters. This spec is widely accepted and implemented in a variety of tools. Of course you ...


12

You can see the collection from two different angles. (1) It is, in the first place, a regular sequential collection, like an array or a list. Index from 0 is obviously the right solution then, following the convention. You allocate enough entries and map channel number to indices, which is trivial (just subtract 1). (2) You collection is essentially a ...


8

That cannot be done. Your problems arise from violating ISP. That said, the only idea I can think of is to force client classes to register with your classes in orden to be able to call their methods or they get a NotRegisteredException. Once they register you can check their type and rise a YouAreNotAllowedToCallThisMethodException if the registered class ...


8

You have a number of options. Go ahead and use custom constructors, virtual properties, or an object builder. The rationale behind this is that an object should stand on its own, and not depend on some magic like the automapper. A class which is completely useless unless there is some magic going on is not a very well thought of class. "Business value" is ...


7

As other people have said, this is often called a fluent interface. Normally setters are call passing in variables in response to the logic code in an application; your DTO class is a example of this. Conventional code when setters don’t return anything is normal best for this. Other answers have explained way. However there are a few cases where ...


7

When testing a repository the essential thing to test is whether you can get out what you put in. so... (excuse pseudo code) $data = ..//whatever addProduct(array $data) $actual = getProduct(id) Assert $actual == $data This will obviously fail if the setters don't work. But doesn't explicitly test every setter


7

Firstly, you have to consider why we encapsulate state. This stock answer is fairly typical: Encapsulation makes it possible to separate an objects implementation from its behavior to restrict access to its internal data. This restriction allows certain details of an object's behavior to be hidden. It allows us to create a “black box” and protects an ...


5

Using getters and setters also enables you to control what content gets stored in a particular variable. If the content needs to be of a certain type or value, part of your setter code can be to ensure that the new value meets these requirements. If the variable is public you can't ensure these requirements are met. This approach also makes your code more ...


5

Hiding inherited methods is a terrible idea and almost guaranteed to cause you grief. I would say that this is what Interfaces are for; a "disclosure agreement" between two or more classes that accurately describes what each is allowed to know about the other[s]. Of course, this will get just a mite fiddly if its mixed with inheritance as you describe - ...


5

Instead of keeping 3 member fields and synchronizing them, you only need to store one actual value in memory - the radius is a good choice in this example - and always use it: import cmath class Circle(object): def __init__(self, radius=0.0): self._radius = radius @property def radius(self): return self._radius @radius....


5

That technique is actually used in the Builder pattern. x = ObjectBuilder() .foo(5) .bar(6); However, in general it is avoided because it is ambiguous. It is not obvious whether the return value is the object (so you can call other setters), or if the return object is the value that was just assigned (also a common pattern). Accordingly, ...


5

I think much of the reason it's not a convention to chain one setter after another is because for those cases it's more typical to see an options object or parameters in a constructor. C# has an initializer syntax as well. Instead of: DTO dto = new DTO().setFoo("foo").setBar("bar"); One might write: (in JS) var dto = new DTO({foo: "foo", bar: "bar"}); (...


5

A class should encapsulate its state, which means abstracting over it. In the first example, your members might as well be public, since returning references lets the user do absolutely anything with them anyway. The second is harder to decide. The theoretical nature of your example means that I still don't like it; the names are meaningless, and I can't ...


4

Is your class a dumb bag of containers? Then give direct access to them! Is your class maintaining complex internal state in containers? Then you probably don't want to expose that internal state to damage from outside (especially if that vector and map are somehow in sync with each other). tl;dr it depends what you're trying to achieve. "Things in a class"...


4

Restricting write access to an internal variable but granting read access does not preserve encapsulation, as external code can then depend on the objects internal state just as much as any of its methods would. Having getters for all of a class's member variables should be a warning sign that something is wrong. Instead, you should have something like a ...


4

Getters and setters break encapsulation every single time, by definition. What might be argued is that sometimes we need to do that. With that out of the way, here are my answers: How is encapsulation preserved by renaming it from get/set to putCheese()/takeCheese() You're obviously getting/setting a value, so why not simply leave it as get/set? The ...


3

If your class is a data structure, then obviously it's fine to do so. Java Map has a put method, which stores a reference. If you modify that reference, you would expect to get the modified object back when calling Map.get(). If your class is a Car, and you are setting the Tires, then well, the problem is there: what happens if I set the Tire and then in ...


3

You are mixing up two concepts: indexing and identity. They are not the same thing and should not be confused. What is the purpose of indexing? Fast random access. If the performance isn't an issue, and given your description it isn't, then using a collection that has an index is unnecessary and probably accidental. If you (or your team) is being ...


3

Everybody and their dog uses zero based indexes. Using one-based indexes inside your application will cause you maintenance problems forever. Now what you display in a user interface, that is entirely up to you and your client. Just display i+1 as the channel number, together with channel #i, if that makes your client happy. If you expose a class, then ...


3

Because Microsoft decided to only support properties in Entity Framework. There are many reasons why properties are preferred over public fields, but I'll just mention the one that I think is most relevant here: changing from public fields to properties (if the need arises) is a binary breaking change.


Only top voted, non community-wiki answers of a minimum length are eligible