Tag Info

New answers tagged

3

Yes. eg: Public class MyRepository { public MyObject GetObject(string id) { //get data from the DB and build an object } } or Public class MyService { public MyObject3 ProcessData(MyObject1 obj1, MyObject2 obj2) { //perform a process which is not a sole responsiblity of obj1 or obj2 } } However, in general the ...


2

Can classes represent entity-less objects? Can? Yes. Should? Probably not - or at least, not how you're phrasing things. Objects actually are best when not representing a physical object directly since reality so infrequently maps nicely to code. But they do need to represent a cohesive concept or code-object. They need to represent a single cohesive ...


3

Can classes represent entity-less objects? If not, why they are bad/incomplete/non-OOP-centric? Are there ways they need to be changed/improved? In short, you can do anything, but this specific scenario would be against OOP principals :) What you are describing is sometimes called a "Utils" class - usually a sing of code smell. You want to avoid ...


0

If a property is dependent only on the User, then it belongs on User; if it depends only on a Role, it belongs on Role. Clearly, if it depends on both User and Role, it belongs on a class that models the intersection of User and Role, i.e. something like Profile. A user can have many profiles; many profiles can refer to the same role, so it's just a normal ...


4

Your question seems to stem from the wrong assumption that every List is also a subclass of AbstractList. While AbstractList offers versatile base implementations for a lot of methods, there might be reasons not to use this option. It’s hard to find an example when looking to the public API only, but there is one: CopyOnWriteArrayList. You will find much ...


0

My humble opinion is that this kind of bold statements can be wrong, boldly. Will not be possible to use a static class. And won't allow some ways of creating a singleton for instance. Sometimes it is useful and helps the algorithm. But read this post it will help you make up your own decision. ...


3

What you gain by following his recommendations is the ability to accept any object regardless of implementation as long as it implements an interface correctly. There's nothing special about this and it's a commonly-used technique. As the paper points out, what you lose is: The ability to restrict variables to a specific class, which matters when ...


-1

Data-Oriented Entity Component Systems can coexist with Object-Oriented Paradigms - firstly, Systems themselves tend to be object-based: we're likely to create custom systems based on existing built-in ones, and there is VERY likely to be a base System class, or interface, depending on your preference. And secondly, Components can be both POD (plain old ...


1

The answer depends on the responsibilities of your wrapping class. If all it does is encapsulate your connection settings for convenience, then simply letting PDOException pass through is preferable. If your wrapper has more responsibilities such as encapsulating certain queries or connection pooling, you may want to develop an exception or two for this ...


3

I would like to understand the clear reason, Why additionally interface List is introduced? In Java, types form a directed acyclic graph, but classes form a tree. As such, types are strictly more flexible than classes. When designing APIs, you should prefer uses non-class types as much as possible for your parameters and your return types. And pretty ...


6

In both of your code snippets, the use of AbstractList is discouraged.1 The correct usage is to put the new instance of list in a List variable. The abstract classes AbstractList and AbstractSequentialList are provided for the convenience of implementers (i.e. library writers) of list-like containers, by providing default implementations(*) for some of the ...


1

Serialization is a two part problem: Knowledge about how to instantiate a class aka structure. Knowledge about how to persist/transfer the information that is needed to instantiate a class aka mechanics. As far as possible, structure should be kept separate from the mechanics. This increases the modularity of your system. If you bury the information on ...


7

I generally avoid having the class know how to serialize itself, for a couple of reasons. First, if you want to (de)serialize to/from a different format, you now need to pollute the model with that extra logic. If the model is accessed via an interface, then you also pollute the contract. public class Image { public void toJPG(String filePath) { ... } ...


0

Only because you want to do things OO does not mean that you must create the graph made out of nodes and vertices. It is absolutely fine to capture the full graph in a single object, and to create a nice, well contracted OO interface on top of it. A classic idea that I have used is the concept of a cursor that works on top of a graph. That cursor knows ...


0

I'm my opinion, you should change your code so that it is Simple, Consistent and Readable. I wrote some blog posts on this topic, and trust me they are simple to understand: What is good code Simple: Just like a circuit board contains different pieces, each one with a responsibility. Code should be divided into smaller, simpler parts. Consistent: Use ...


2

You shouldn't catch the PDOException at all. Now, you should have some sort of last resort exception handler that catches all exceptions and logs them. PDOExceptions should be caught there. But you shouldn't catch them anywhere else. In my understanding, PDOException indicates either that something has gone very wrong with the connection to the database, ...


1

I would argue its impossible to handle all exceptions the same way. I think you should let it propagate back to the calling code as it ultimately knows how it should handle the exceptional situation. Just to think of a (maybe weird) example. Imagine you have an blog. An each hour you query the database for new articles. But luck isn't with you and your ...


0

timesSignerIsRequired is not global state, it's a field on your object. It's okay for the methods of an object to access the fields (including private fields) of that same object.


0

What are those role-dependent attributes? That's strange for users to have different sets of attributes, since they can change roles in a blink. What will you do with the attributes from role A when user no longer has the role? Delete them? What if tomorrow that user will change his role back to A? So, one approach is to maintain a single overly-bloated ...


2

Your confusion around tissue = new Tissue(); tissue1 = tissue.load_tissue(2); // tissue1 = 3; tissue2 = tissue.load_tissue(3); // tissue2 = 6 BUT tissue1 = 6 as well. derives from confusion value and object-oriented semantics in your tissue abstraction. This is called 'aliasing'. To find out which one you should use, ask the following question "If two ...


1

In CQRS, queries are not allowed to have any side effects, and thus they cannot change any data. Commands on the other hand must not return any data, but change the state of the application. With these definitions and your problem domain the question becomes this: What does the search functionality do? If it's purely for finding an order, then it is not ...


4

You are over-using SRP. Let's take a look at mappingConcern's creation-and-initialization version: public function mappingConcern($data) { $parameters = $data; $product = new Product($parameters); return $product; } $parameters is the same as $data, and $product is returned immediately, so it can be translated to: public function ...


3

Why create a whole other classes to handle those responsibilities? Because when you're doing Object Oriented Programming, your focus should be on the objects. They are your unit of work for making the design and providing abstraction. And most importantly, they are your unit of reuse. By letting them change for different reasons, you're forcing people ...


0

As an example, if you have a class with instances representing a user interface element, and that class has a "draw" method, then the "draw" method specification will not say exactly what will be drawn. It will instead say "the user interface element will be drawn appropriately to inform the user about all the state of the user interface element that is ...


4

Summary: The design without the abstract class will be only be acceptable if it is carefully documented to distinguish its abstract and concrete behaviours. The Liskov Substitution Principle is generally regarded as a "good thing". By the LSP, I mean that if type S is a subtype of type T, then objects of type S should behave as objects of type T are ...


1

Congratulations, you just have discovered how the violation of Liskov Substitution Principle looks like, as the very first commenter politely pointed you at. To answer exactly to your question: according to the aforementioned principle, you don't design a subclass whose method contradicts its superclass. Reasons for this are explained in the literature ...


0

The Liskov Substitution Principle only says that subclasses should not violate provable properties of the supertype. The provable properties are basically the type signatures of members. So if a method on a superclass is declared to return an integer, then it shouldn't be overwritten in subclass to return a string. Type systems in modern statically-typed ...


2

This bothers me because it looks like a logical contradiction: All scissors are right-handed. Incorrect at this point. You've defined scissors as all having handedness, and that this defaults to right-handed if not overridden. You have not said that all scissors are right-handed, that would require overriding being prohibited (as can be done in ...


34

There is nothing wrong with the design shown in the question. While one could also introduce abstract Scissor with two concrete subclasses, and maybe more overall clarity, it's also common to do it like shown (especially when the hierarchy is a result of years of incremental development, with Scissor being around for much longer than the concept of ...


9

Another option is to introduce the handed-ness as a dependency with a default value of right-handed. In pseudocode here as I am not familiar with Ruby: class Scissors { Scissors(isRightHanded = true) { _isRightHanded = isRightHanded } IsRightHanded() { return _isRightHanded } } class LeftHandedScissors : Scissors { ...


23

You are thinking too logically! There is no logical contradiction because class definitions are not logical propositions. Having the Scissor base class return true does not correspond to saying that all scissors are right-handed. It just means that a scissor instance is right-handed unless the method is overridden in a subclass.


15

You don't. It's like saying that all animals are dogs, and then asking how to make cats meow instead of bark. If you were naming your classes properly, your Scissor class would rather be named RightHandedScissor; now does it make sense to inherit LeftHandedScissor from RightHandedScissor? One possible approach is to make Scissor class abstract, and ...


3

"All scissors are right-handed"? Where do you get that idea from? Your code only expresses "scissors are right-handed by default". It's a default value, not a design decision. If there were no way of having a different value, what's the point in programming a boolean accessor function?


1

Well I think people are missing the point that you're delegating the behavior that was once in the Driver class into the Car class, so it's not really Extract Method because otherwise it would be in the same class. This is either simple composition (not a DP) but if you want to be kind, it might be an implementation of Strategy, which some people do consider ...


5

To be clear, none of "refactoring", "abstraction" or "encapsulation" are design patterns. Neither is what you posted. As you say, it is a refactoring. Specifically, it is the one that Martin Fowler named Extract Method. The definition is "Turn the fragment into a method whose name explains the purpose of the method.", which is precisely what you are doing. ...


1

Arguably it is simply the application of structured programming which was named long before design patterns were born. As a refactoring, you can call what you have done 'Extract method'


0

Your teacher's definition completely misses the most important point of object-oriented programming, the one thing that makes it useful and unique. "Message passing" is a bunch of nonsense dreamed up by the Smalltalk folks, and it's been a failure everywhere it's been tried. The true power of OOP is something known as Liskov substitution, and while the ...


7

This seems like one of those common "favor composition over inheritance" scenarios. A RestController serves as an endpoint for REST calls. Not something to govern Authorization. Not something to control the HttpCache. It's a violation of the Single Responsibility Principle. Instead, you should have classes (strategies if you'd prefer) to govern these two ...


5

As Harrison Paine and Brandin suggest, I would re-use the same object and factorize the initialization of the properties in a Reset method: public class MyClass { public MyClass() { this.Reset() } public void Reset() { this.Prop1 = whatever this.Prop2 = you name it this.Prop3 = oh yeah } public object Prop1 { get; ...


2

If the intended usage pattern for a class is that a single owner will keep a reference to each instance, no other code will keep copies of the references, and it will be very common for owners to have loops which need to, many times, "fill in" a blank instance, use it temporarily, and never need it again (a common class meeting such a criterion would be ...


8

Given the very generic example, it's hard to tell. If "resetting the properties" makes semantic sense in the case of the domain, it will make more sense to the consumer of your class to call MyObject.Reset(); // Sets all necessary properties to null Than MyObject = new MyClass(); I would NEVER require making the consumer of your class call ...


2

Apple's sample code is just that, sample code. No guarantee that it works, that it is bug free, that it is the best way to achieve something. Use it to study some area that you don't know much about, until you are knowledgable in that area by yourself. And then throw the sample code away. Which is what you should do with any code that you find on the ...


12

You should definitely prefer creating a new object in the vast majority of cases. Problems with reassigning all properties: Requires public setters on all properties, which drastically limits the level of encapsulation you can provide Knowing whether you have any additional use for the old instance means you need to know everywhere that the old instance is ...


42

Instantiating a new object is always better, then you have 1 place to initialise the properties (the constructor) and can easily update it. Imagine you add a new property to the class, you would rather update the constructor than add a new method that also re-initialises all properties. Now, there are cases where you might want to re-use an object, one ...


1

You're trying to program a transaction that involves two accounts. This means that the code should live outside the BankAccount class. If the subtraction and addition happened in a method in the BankAccount class, you would always have to find all existing BankAccount objects and send the transaction details to each of them. This is a huge waste of effort, ...


5

The way you're showing it now ("I instantiate the BallEntity this way"), it is being done by the implementation (code) that calls the constructor to create BallEntity. To be clear, the point is that the way you're showing it, everywhere that you create a BallEntity (whether in separate classes or multiple places within the same class), you're re-specifying ...


3

Naming things should always be done in the context of their scope, and as a rule of thumb compare it to how you would refer to these things in natural language. When you want to talk about the person who owns the car, you refer to them as "the car's owner", not a "the car's person" - so that's how you should name the field - owner(actually - it's better to ...


7

Either you are building domain models, or you are building relational database schemas. If you are building relational database schemas, use ids. If you are building domain models, do not use ids, always use references to objects. This should answer the entirety of your question. Now, if you were building a relational database schema, and if you wanted ...


1

It's certainly do-able, but it's not small. An incomplete minimal example looks something like: template <typename BaseIterator, typename FieldType, FieldType SensorReading::*FieldPtr> class FilteredIterator { BaseIterator base_; typedef FilteredIterator<BaseIterator, FieldType, FieldPtr> self_type; public: // iterator type traits ...


5

All three are wrong, because you are storing connection strings in source code. Source code is not the right place for configuration, because you are not expected to have to change your code (and so, do all the regression testing) every time your database moves or every time you move from development database to staging and to production database. Instead: ...



Top 50 recent answers are included