Hot answers tagged

133

I’m still really new to learning to program. Just learning the syntax for a few programming languages at the moment. And that is actually the problem here - you approach this way too much from a syntactical point of view. What you need to learn first is solving problems with programs. When the problems get larger, the programs will get larger and require ...


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 ...


34

Getters and setters allow the programmer to change the implementation of a class later on more easily. If the class is used elsewhere, and if there are no getters and setters, then the programmer has to change every other class which uses it. With getters and setters, the using classes can remain unchanged. Imagine you have a class called BankAccount with a ...


33

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 {...


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"&...


23

Getters and setters make accessing fields into their own methods. When you're in Java you have to do this up front or when you decide to do it later you change the interface. In C# they have lovely properties so your clients won't care when you decide to make your public fields private. These let you detect when something is accessing your fields. Public ...


22

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 ...


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 ...


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!"); ...


15

I am one of the software engineers who advocates suspicion for getters and setters, but only because of how they are used today. The reason I object is mainly that application programmers have developed the bad habit of generating getters and setters for every field without considering whether or not each getter or setter is necessary. Furthermore, as 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 ...


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 ...


9

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 order 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 ...


8

When you're learning a new language and you're not sure about programming style, it might be good idea to take a look at the core libraries of the language. They might not always be a perfect model, but they're most likely way better than most of the code you'll see elsewhere. Adopting a similar programming style will be beneficial. Your code will be easy to ...


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

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 ...


5

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 ...


5

property with a { get .... ; } and a backing field a property with a { get .. ; private set .. ; } Note that your bullet points aren't quite correct. If you're using an auto property (i.e. not having an explicitly defined backing field), then the second bullet point's getter and setter should not have a body. Once you explicitly define the body of the ...


5

The main difference between using setters/getters/direct access and properly encapsulated objects, is a design question not a syntactical one. The former ones are basically a holdover from our procedural past, that we can't seem to shake. It is much easier to imagine a set of instructions on some data that the CPU has to execute. This thinking results in ...


4

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.


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

You cannot do exactly what you want - see the other answers, but there are a couple of things you could do. You could have a package private interface that exposes the setters, and a public interface that exposes the getters. You mention that you want to use the setters in multiple packages in your own code. Why is this? This is a code smell for me - if ...


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