New answers tagged

0

With function pointers, you can do: str.replace(&str, i, c); This is generally only useful if the implementation can change, in which case you should use a vtable so the overhead is only one pointer per struct: str.vtable->replace(&str, i, c);


0

Instead of making two base classes and multiple instances of each, make one notification class with a bool to indicate if the notification is blocking and any other information needed to communicate the notification to the user. This allows you to use one set of code for processing and presenting notifications and reduces the complexity of your code.


0

It depends. To elaborate, the parameters your method accepts should semantically match what you're trying to do. Consider an EmailInviter and these three possible implementations of an invite method: void invite(String emailAddressString) { invite(EmailAddress.parse(emailAddressString)); } void invite(EmailAddress emailAddress) { ... } void invite(User ...


2

Neither is generally better than the other. It's a judgment call you have to make on a case-by-case basis. But in practice, when you're in a position that you can actually make this decision, it's because you get to decide which layer in the overall program architecture should be breaking the object up into primitives, so you should be thinking about the ...


2

Pass around the object, not its constituent state. This supports the object-oriented principles of encapsulation and data hiding. Exposing an object's innards in various method interfaces where it is not necessary violates core OOP principles. What happens if you change the fields in Otherthing? Maybe you change a type, add a field, or remove a field. Now ...


0

Clean Code recommends having as few arguments as possible, which means Object would usually be the better approach and I think it makes some sense. because insertIntoDatabase(new Account(id) , new Otherthing(id, "Value")); is a more readable call than insertIntoDatabase(myAccount.getId(), myOtherthing.getId(), myOtherthing.getValue() );


1

So when you create a function, you're implicitly declaring some contract with code that is calling it. "This function takes this info, and turns it into this other thing (possibly with side effects)". So, should your contract logically be with the objects (however they're implemented), or with the fields that just so happen to be part of these other ...


0

Split these checks to where they belong. "Players" are a part of Matchup. As Matchup never wants null players, this check should be in the constructor of Matchup. public Matchup(Set<Player> players) { if (players == null || players.Contains(null)) throw new IllegalArgumentException("Player cannot be null"); this.players = players; } ...


4

From what I have always understood about the C# language, when an object is passed to a method, it is only a copy or instance that actually gets passed. That's where you are getting mixed up. All variables in C# are references to objects. The buffer object in your example lives on the heap, and both the consumer and producer have a reference to that ...


-1

Other than the fact that it allows multiple superclasses, Python's inheritance is not substantially different to Java's, i.e. members of a subclass are also members of each of their supertypes[1]. The fact that Python uses duck-typing makes no difference either: your subclass has all of the members of its superclasses, so is able to be used by any code that ...


4

As a converse to the existing answers, I would suggest that the boolean property is the best option if the mode that is to be used is required to be changed dynamically (e.g. via a configuration file that gives a list of which types are to be blocking and which aren't). That said, a better design even in this situation might be to use a Decorator object.


33

You want to avoid base classes knowing about derived classes. It introduces tight coupling and is a maintenance headache because you have to remember to add to the list every time you create a new derived class. It will also prevent you from being able to put the Notification class into a reusable package/assembly if you wanted to use this class in ...


14

and specify a list of subclasses that are blocking inside the Notification parent class. That looks very peculiar and is a particular code smell. I would provide subclasses if you have differences in behaviour between the classes, and you want to treat all of these notifications in the same fashion (i.e. using polymorphism).


3

This is an easy one. If the preconditions are associated with the matchup (i.e. they always hold), then they belong in the constructor. If the preconditions are associated with the event (i.e. the event decides whether they hold or not), then they belong with the event.


-1

I'll step your through how I think I see it: Let's say we have a base class A and subclass B. When B is instantiated an A object is also created and contained within the B object. When we try and assign the B object to an A- type pointer/reference/etc, we slice away the B part of the object, effectively only being left with the subObject (A). Therefore ...


0

How do I prove or disprove “god” objects are wrong? You Cannot. This kind of conjecture is not amenable to mathematical proof, and mathematical proof is the only kind of proof that is sound. Even if you try to replace the emotive word "wrong" with quantifiable measures of the effects of using god objects, you will find that: the available measures ...


0

Surely "b" now points to the correct object so that when we call b.doSomething, we know which method needs to be called. Surely not! The key problem is if b points to or references a base class but in actuality is a derived class, it is the doSomething method defined in that derived class that should be called, rather than the than doSomething method ...


6

Because virtual functions have a runtime performance cost, and part of the philosophy of C++ is "you don't pay for what you don't use". Specifically, virtual methods have to dereference a pointer to find out where the correct method is for the specific object they were called on. One pointer dereference per call may not sound like a lot, but this also ...


3

If you're talking about variables of user-defined polymorphic types, then in C++ you need to use a pointer or a reference in order to achieve runtime polymorphism. The exact syntax you're describing is probably legal in C++ (hard to say since you didn't give a complete example), but results in "object slicing" rather than polymorphism. The reason is that a ...


1

If you need to be able to assign a subclass instance to a variable in c++, and you need reassignment, then what you want is a pointer. private: State* current_state; If there's ownership involved, you should use a smart pointer like unique_ptr or shared_ptr. shared_ptr most closely matches the semantics of Java references, other than the fact that it ...


2

Within the superclass, State, I have declared several variables which need to be accessed and changed from the 3 subclasses. That's what the protected modifier is for; "# Me and my Subclasses ...". Is it possible to instantiate these 3 subclass objects from the same "superclass object" so that they can all access the variables ... That you get ...


0

Is it possible to instantiate these 3 subclass objects from the same "superclass object" so that they can all access the variables from the SAME object? No. But you can instantiate from a State that has its members defaulted to particular values, and consequently your subclasses will all have the same values. public class State { protected int ...


0

Short answer: From the perspective of OOP this should be an implementation detail. You can hide this implementation detail if you have an instance method that is used like local method variable. This way your three options are implementation details that can be easily changed any time with just a few lines of code: class MyService { protected ...


0

I would say keep it simple: Make 1 program that's the editor and another program where you play the game. This way you can make editobjects for your editor and playobjects for your game without needing to mix and match functionality that essentially does not belong together.


1

Here's an example of how you might approach this from a functional perspective, and how it helps avoid the potential pitfalls. I'm working in Haskell, which I'll assume you don't know, so I'll explain it in detail as I go along. data Application = Applied ApplicationDetails | InReview ApplicationDetails | Approved ...


1

You could use the «command» pattern, and then ask to the Invoker to provide a list of valid functions according to the state of the receiver class. I used the same in order to provide functionality to different interfaces that were supposed to call my code, some of the options were not available depending of the current state of the record, so my invoker ...


1

One approach to this problem which has been extremely successful in the wild is hypermedia - the representation of the state of the entity is accompanied by hypermedia controls that describe the kinds of transitions that are currently allowed. The consumer queries the controls to discover what can be done. It's a state machine, with a query in its ...


1

First, lets make a clear statement about performance: in 99,99% of all real world cases the performance will be literally the same, so - as usual - performance is not a useful criterion for making such a decision. The primary questions you should ask yourself here is: "can I imagine a situation where I need different database connections for different ...


0

A config class is probably best as it will be DRY and implement a interface (keeps it testable). The interface must have a method taking in sql strings and returns a object. Several implementions can be done for different environments.


1

...I need to use the IOffice they belong to, and each office has a different way of delivering that package to that Employee. It sounds to me that the code should be employee specific rather then office, package and employee specific. Each employee should implement their own way of receiving a package and each office will only know that each employee ...


0

If the set of constants is somewhat small without much potential to grow exponentially larger, I consider it acceptable. I would strongly recommend using an enum return type, rather than a string, to allow the compiler to catch errors before runtime. Your initial approach may seem less than desirable in part because you are introducing an unnecessary ...


3

Note: If your actual code resembles the Animal/Food example, please go with the suggestions in the other answers that cover the double dispatch/visitor pattern technique. The answer to more general question, "Is this ever appropriate?", is a qualified yes. One of the times when these sort of methods are appropriate is when implementing algebraic data ...


0

What is missing from the code examples is what you are expecting it will look like actually interacting with the classes. It sounds like you are starting with a reference to an Employee. In the first approach, sending a package looks like: employee.Send(package); And in the second, more like: var office = offices.Find(o => ...


1

This strikes me as very similar to dependency injection, the only difference being that a dependency is only set once and an animal may be fed multiple times. My preferences (in order) would be... Let the animals create their own food (only possible if food is easy to create). Create a type-specific food factory (e.g. a MeatFactory for a Dog) and pass ...


0

There are probably other ways to go about this also. How would you do it? I would start out by considering the boundary between the real world, and the digital model. Employee and Office are fine entities, but they are in the real world; you can't change the real world by sending a command to your model. When little Bobby Tables enrolled, the model ...


1

I measured the overhead of direct and virtual C++ function calls on the Xenon PowerPC some time ago. The functions in question had a single parameter and a single return, so parameter passing occurred on registers. Long story short, the overhead of a direct (non-virtual) function call was approximately 5.5 nanoseconds, or 18 clock cycles, compared to an ...


23

There are two possible approaches here. The simplest way to solve this if every Animal knows itself what they are supposed to be fed. So: interface Animal { Food wantedFood(); } This might completely solve your problem, and if so, is a good solution. But while this is simple, this is often unsatisfactory: your Animal interface will grow and grow ...


16

Tell, don't ask might help you out here. switch (animal.getAnimalType()) { case "DOG": Food food = new Meat(); break; case "FISH": Food food = new Bread(); break; default: return; } Notice what this code fragment is - a switch on behavior. That's a "code smell" in ...


-2

I would not do it this way. What you are doing is coupling your interface with your concrete. This will defeat the purpose of using your interface. If you continue this way, you may end up with what is called an Entourage anti-pattern. You are right, this is essentially a cast in disguise (at the bottom of your code snippet especially). Calling new and ...


1

Quite likely, implementing your grammar as multiple interdependent parsers is only going to make your code more complicated. The data flow will become less obvious, and you will duplicate some behaviour. It is OK if a class is large. However, many languages can easily be split into different levels, and handling these separately could be sensible. For ...


4

Create a Scanner or Tokenizer class, which takes the input data (the text to be parsed) and holds the position of the current token or similar state. It can also provide some shared helper functions. Then provide a reference (or a shared pointer) to the Scanner object to all your individual xyzParser objects, so they can all access the same scanner. The ...


1

State design pattern perhaps? It is pretty much straight-forward inheritance, with the parent - abstract - class containing a reference to the current "state" object, i.e. parser. The pattern coupled with delegates, extension methods, etc. should give plenty of flexibility. Be wary of breaking apart a class arbitrarily. These smaller classes also need OO ...


0

Separate writes and reads. Below is a way to allow both to occur at the same time to the same file. Maybe you need for writing or changing the state of the media. It has a list of writers and a parallel list of states. If the write fails beacuse it violates an invaraint, change the state. It would notify observers list with the state. The medium state ...


1

The two usages are actually completely unrelated. The LHS is the declaration of the type of the variable obj. You can put any type there, not just a class. E.g. in both Java and C♯, you could put an interface there, in Java, you could also put a primitive type there, in C♯, you could put a struct there, in Scala, you could put a type alias there. Some ...


0

Both of the type names in each declaration are just that: "types". The left-hand type is the type of the variable, and the right-hand type is the type of the object you're assigning to that variable (or initializing that variable with). When the two types are different, in most languages that's only possible if the object type is a subtype of the type of ...


1

You are declaring the type of the variable (static type) and then instantiate the object that the variable will hold (runtime type). So, your sentence: In Xamarin, SqlCommand.ExecuteReaderAsync(CancellationToken) throws a runtime error and so in the declaration, SqlCommand command = new SqlCommand(), the static type must be changed to DbCommand.


0

I would fix this by adding new class and get away from throwing too many design patterns where they are not really true in the domain. For the plants, there is a amount of new steams, flowering steams, and fruit bearing steams. It also has a 2D point for its location. This is a property with only a get as plants don't really move. Same with amount of ...


3

If you want a reference to the Plant object in the to-be-notified Herbivore object, change the signature of notify to include a Plant object. notify(state: Maturity, plant: Plant)


1

The design of an interfaces should be based on the components that will use it (consumer), and on the components that will implement it (implementor). Implementor side Would you ever want to write a class that only draws a circle, but not any of the other shapes? Maybe you have a DefaultGeometryManager with hardcoded algorithms for each shape. But the one ...


3

From what you've described, you don't need a circular reference at all, so the best thing you can possibly do is get rid of it completely. in Column class I have a build function which return a string by combining table and column like "tableA.colB". That why column need to know what table it belong to.These entities are used for building SQL statement. ...



Top 50 recent answers are included