New answers tagged

0

Yes, there is a better solution. The root of your problem appear to be that you try to handle the exception at the wrong place, where you don't have the required information any more to roll back some actions that were taken. If creating your Container object consists of multiple steps that can fail and that have externally visible or persistent effects ...


6

I'd prefer Option #4: Avoid relying on inheritance. Just make UrlBuilder an interface, and give people some way to inject their own implementation to the process, overriding the default you provided. interface UrlBuilder { public function url($config); } class DefaultUrlBuilder implements UrlBuilder{ public function url($config) { $config = ...


2

The convenience of inheritance in this example is reducing the amount of boilerplate code you have to write, but this falls under code reuse rather than behavioral reuse. By itself, that isn't an argument against using inheritance but rather that code reuse isn't a sufficient argument for inheritance. Inheritance has significance and consequences beyond ...


1

Your goal in both cases is the same: extending B's behviour. This could either be done if B uses A or if B inherits from A. Usage could be done in three ways: a) Aggregation b) Composition c) B makes temporary use of A for doing stuff (think of A as part of a message sent to B). Both of your implementations differ semantically. The second ...


6

If your composition situation is simple enough, you can use inheritance instead. Not recommended, because it would be confusing to others, and also will require refactoring as soon as the composition situation becomes less simple. Composition allows a number of things. Because the classes are separate, each can have their own inheritance hierarchy. So ...


0

Each item itself This all should work much alike event-driven system. Parent entity should give orders to its Items, and Items should check with their state to see if and how they can perform that action. Even if it is as simple as reading 1-2 public properties for the Parent, it is still better for encapsulation to not do so and let Items check their ...


1

As Robert Harvey commented, MVP (model-view-presenter) is the architectural pattern of choice for Winforms. MVP is really just a flavor of MVC though. Your form (view) should implement an interface defining the public API of the view. FooForm : IFooView, Form And it will expose some of its elements via properties, say maybe a textbox input. public ...


2

Whilst it's admirable to check your preconditions, I wonder: is your class usage such that you'll need to check all these ? e.g. I will check preconditions for a set of components that are exposed for more general usage, but for more limited usage in which I know how the component will be used, I won't perform so many checks. The counter argument to this ...


0

Visibility is often something you want to aggregate so you can tell a whole group of objects to hide or show themselves together. Even so it's still best let each object test and paint itself. I'm a big believer in tell don't ask. To me the object oriented world is divided into behavior objects that tell you nothing about their state, and data objects ...


1

At least in OO + event driven interfaces: GUI objects, including the window pane itself, have event listeners who are triggered with user actions. Those event listeners call a method which then send messages to other GUI elements (or to themselves). But... once a GUI element receives an message (like myButton.setVisible(false);) it renders itself ...


2

Use the factory-pattern. A factory is an object which creates objects. So when you have a weapon which shoot projectiles, pass a ProjectileFactory to it and leave the creation of the projectile to that class. You can then have different classes which extend ProjectileFactory, like BulletProjectileFactory, ExplosiveProjectileFactory, ...


1

Returning the Optional seems OK but if there is no value the logic should not proceed. Each guest has a real room assigned to it or it is not a guest. So once the receptionist decided to return an empty Optional, the order should be put back in the queue and nothing more. It is fine to first take the order from the queue, then perform the ...


1

I think you could model it in two ways: Option 1: Using an wrapper + enum for the receptionist response: enum ReceptionistDecision { BOOK_ROOM, NO_ROOM, RETURN_TO_QUEUE, } class ReceptionistResponse { ReceptionistDecision Decision; Optional<Room> Room; ReceptionistResponse(Room room) { ... } ...


5

There are couple of approaches one could apply to modelling this. First, we might have the passive receptionist. The passive receptionist decides what to do, but doesn't do anything. Instead, we have class something like public class ReceptionistResponse { public static ReceptionistResponse bookRoom(Room room); public static ReceptionistResponse ...


0

Unfortunately, it is difficult to model the relationships between numeric types using the typical feature set of an object oriented language. You can get close by modelling both real and complex as instances of an interface" number", but OO semantics will trip you up because in many cases functions of real values will want to return real and the same ...


1

To quote Eric Evans, "a model is neither right nor wrong, just more or less useful" An inheritance hierarchy could be useful if you really need to operate on many different types of numbers and be able to handle them in an abstract manner. In this case maybe you also need Fraction class, and maybe the abstract base class is neither Complex, nor double but a ...


0

Why not make real a special case of complex where imaginary just happens to be 0. This obeys the substitution principle which states that a subclass must always be able to stand in for the superclass. This means that real should inherit from complex (because a real number is a complex number). In any case I would not worry too much over it and just ensure ...


2

Graph(ical) issues aside, the inheritance case seems just wrong to me. A complex number consists of two data members, and I don't see any advantage in inheriting one and adding the other. Even worse, you may be able to do invalid calculations with a complex and a non-complex number (double or integer) when deriving from double, while I think these operations ...


2

The association marker isn't an arrow, it's a binary relation that is marked on one side (so you can distinguish dog-has-tail from tail-has-dog). And the inheritance arrow looks as if it is "moving" into one particular direction, but there is no particular reason why anything would notionally move from the superclass to the subclass, or from the subclass ot ...


0

Why you would even begin to implement this is beyond me. Qt has such a tools for such animations in place already for both its widgets and qml (qml side being slightly more convenient imo). If qt is not possible, there is probably numerous other libraries.


2

I'm not sure there is any one answer, but rather many (likely opinionated) answers. What you're talking about might generally fall under Software Development Process or Design Methodologies, such as Domain-driven_design. The space is pretty large, and, Wikipedia has a good (but more than likely incomplete) ontology around software development, and, you may ...


1

What you describe here is a Factory, which simply offloads the responsibility of object creation to another class. What factory to use is static: known at compile time, does not change. What you need is an Abstract Factory, where the factory is an interface and the implementation of the factory is unknown until run time. This allows third parties to ...


1

You have brought up questions about two SOLID principles. The first is about the Single Reponsibility Principle. And now I doubt if I should add a isAdjacentTo(Node) method to the GraphEdge class or I should create a GraphUtil class(*) and add static edgeIsAdjacentToNode(Edge,Node) method to it. The question that you should ask yourself about this is ...


1

TL;DR This phrase would help remind one not to apply SRP prematurely: A good separation of responsibilities is done only when the full picture of how the application should work is well understand. Source: http://www.oodesign.com/single-responsibility-principle.html API Requirements Phase These are given as examples. Cross out ones that are not ...


0

The Single Responsibility Principal states that a class should only have one reason to change. If your class has multiple reasons to change, then you can split it out into other classes and utilize composition to eliminate this problem. To answer your question, I have to ask you a question: Does your class have only one reason to change? If not, then don't ...


21

The single responsibility principle can be tricky to understand. What I've found useful is to think of it like how you write sentences. You don't try to cram a lot of ideas into a single sentence. Each sentence should state one idea clearly and defer the details. For example, if you wanted to define a car, you would say: A road vehicle, typically with ...


6

Update (recap) Since I've written a rather verbose answer, here's what it all boils down to: Namespaces are good, use them whenever it makes sense Using inGameIO and playerIO classes would likely constitute a breach of the SRP. It likely means you're coupling the way you handle IO with the application logic. Have a couple of generic IO classes, that are ...


1

You should follow the coding guidelines where you work or on the projects you work on. You will find that there are a lot of people who are totally for or totally against the use of this unless it is needed as in the example given in @KilianFoths answer. It does not have anything to do with public, protected or private.


3

No, you shouldn't use this redundantly. It adds unnecessary clutter and makes you look as if you're not sure what fields your class has. The only reason that many people do this is that they often see this introductory example: public Foo(Bar bar) { this.bar = bar; } and wrongly assume that you always have to use this, when in fact you only need it ...


2

I'd say that the best way to go is to keep them in separate classes. Small classes are not bad, in fact most of the time they're a good idea. Regarding your specific case I think that having the separated can help you change the logic of any of those specific handlers without affecting the others and, if necessary, it would be easier for you to add new ...


2

Brian Agnew's suggestion is very much applicable, but I'd like to point out something else: I get the feeling that maybe the actors (the plugged-in behavior you mentioend) on your model are carrying two very different responsibilities. Alternatively, you could design your framework to have a separate registration mechanism, exclusively for disposable ...


4

I don't think it's unreasonable for your abstract base class to provide an empty implementation of the IDisposable interface, and for subclasses to implement their own implementation as required. That seems to me a commonly used and understood pattern.


2

You are going down the wrong road by using a _reset() method for clearing the parser state. Rather you should ensure that the Parser object is is only used for parsing a single input once. You can do this either by providing the input string in the constructor or in a factory method, and perform the parsing immediately the same place. That way there is no ...


0

If you use frame numbers as reference, your animation may run faster or slower, depending how good the PC is. A better approach would be to have timed events, and to update your animation depending on these. By the way, in qt it is possible to do whatever you like. Animated widgets are easy to do. Handle a timer event, and do custom paining of the widget. ...


7

A basic problem I see with your approach, at least as you presented it here, is that it promotes mutability and side-effects. In fact, when trying to implement your suggestions closely, I couldn't even figure out how to create an immutable object at all! It looks like you promote constructing incomplete half-initialized objects and then initializing them in ...


0

Admittedly, the DDD book doesn't make it very clear, but when it says "stateless" it means "without persistent or long-lived state". So, service objects are allowed to keep state in their instance variables/fields, as long as it's not state that gets persisted or externalized in some way. The state the book cares about, when discussing statefullness, is the ...


1

What you're facing here is the tension between two issues: good encapsulation and the Single Responsibility Principle. If Party has to expose its inner state to everyone, it's poorly encapsulated with all the usual effects that has (in this case, that includes violating Tell, Don't Ask). But if it keeps its state encapsulated then only it has the access ...


0

a) Don't really understand why you're using $_SERVER variable... I'm always passing localhost (or whatever) from static config. b) Personally I'm using MySQLi, but my connection functions aren't that much different. Never heard about the need or way to make it more secure. It's already very secure as far as I'm aware. You can use SSL if you're connecting to ...


2

In JavaScript, functions are just objects. As such, there is no particular reason not to pass them around as parts of other objects. In fact, may JavaScript libraries do this, for instance, letting you pass in an object containing a success and an error callback. As a way of doing OOP in JavaScript, that's a perfectly reasonable way of doing things, and ...


1

Passing the reference Yes it would still work because you are only passing the reference and therefore it doesn't alter the referenced object (nor create a copy) Responsibility for opening/closing There are 3 possible cases: Only one command uses the serial port. The serial port is completely encapsulated in the command and is opened at the beginning of ...


2

To understand the difference, there's one more piece of the puzzle you need to understand: dynamic dispatch. Let's slightly modify your example by having both Asteroid and SpaceShip inherit from Sprite (as you might if this was a game), which has the same two methods, but is abstract. Now imagine some code like: Sprite ship = new SpaceShip(); Here we can ...


0

The documentation clearly states that interfaces which return null or throw an exception are behaving as expected. Therefore such interfaces don't break the LSP, since they behave as expected. If the documentation said "interfaces never return null" then an interface returning null would violate the LSP. Since the documentation says the exact opposite, ...


3

The issue with the second solution is that each of Asteroid and Spaceship need knowledge about each other now, creating a strong dependency. If additional classes are mixed in, each single class belonging to the group needs to be touched. Having a central, multi dispatch class means that only two files at most need to be modified in order to add a new class ...


0

It doesn't appear any different when you write it as in your simplified example, but in a real application, Asteroid and Spaceship are going to be in two completely separate files, with a bunch of other unrelated methods and data mixed in. Multiple dispatch allows you to easily group all your collision logic in one place, sharing common collision-related ...


0

I've used a different approach in the past. In my scenario I had a large number of methods that could generate warnings. I created a Context class, which contains various things, including a list of warnings. It also has a static method getCurrentContext(). So, any time I need to generate a warning, I can do: Context.getCurrentContext().addWarning("Email ...


2

"Should the Party class know how to send itself to the client, and repository?" It is hard to answer your question because you are writing your application in a procedural rather than object-oriented style, despite the object-oriented and domain-driven-design tags. In an object-oriented program your Party object would constrain the number of Pokemons ...


2

I'd really be more worried about the fact that you seem to feel the need to "mock" just about every type in your whole project. Test doubles are mostly useful for isolating your code from the external world (third-party libs, disk IO, network IO, etc.) or from really expensive computations. Being too liberal with your isolation framework (do you even REALLY ...


1

I think option 1 is best, but in my opinion there's a better way to do it than creating a custom Results class. Simply use a 2Tuple, as some others have mentioned, of the result and the list of warnings. public Tuple2<double[],String[]> performCalculation(double[] someInData){ ... } Here is an example of how to implement a tuple I believe ...


15

A fourth option, rather than passing in a String[] warnings (or more-flexibly a mutable List<String> warnings) as you suggest in #2, would be to pass in a callback listener or object that receives and displays the warnings. For fast calculations, this is very likely overkill, but may be a way to go if your calculation is long-running or otherwise needs ...


2

If the caller needs to be able to react to the warnings, the preferred way is your first proposal, that is return a custom type (as others have already pointed out). However, most of the times, the caller is not interested in warnings. For these cases, such warnings would usually be sent to a Logger (see for example slf4j). public double[] ...



Top 50 recent answers are included