New answers tagged

0

Without knowing too many details about the responsibilities of this class hierarchy, it sounds like you may be violating SRP. I would consider using constructor injection to pass in an object that can calculate a path. This is an application of the strategy pattern. This way you decouple the responsibilities of the class from the responsibility of knowing ...


2

When an API uses an abstract base class, the (only) way to provide a version of that API is to subclass the abstract base class. Because in C# and Java we can only have one super class, it is, in some sense, a scarce resource. Requiring that each API implementer subclass from that abstract base class means they cannot subclass from a class of their choice. ...


2

Besides not being able to use multiple inheritance, as Robert Harvey has pointed out, when using an abstract class, you usually do so to group common behaviour of children of this supertype together, respecting the DRY principle. But by doing so, you are sometimes introducing more data to the class than the single interface would probably need for it to ...


6

You can't use multiple inheritance with abstract classes.


1

First of all, a std::basic_streambuf is basically the building block of a std::XYZstream. Using one or the other is not choosing between two implementations, it is a choice between a basic building block and a more advanced stream interface that people expect. Use a stream. Based on your comments, it appears that you may be getting hung up on the idea of ...


1

Here is how I could understand your problem. You have a community of Developers (StackOverflow). Some people have edit privileges when they reach higher reputation milestones. Now there are also some posts that are "community protected", and cannot be edited, even by those "acknowledged" users. In this case you would be checking for the user's status of ...


0

As the question is tagged with Java I will focus on it in the answer: The main reason for these classes were that Java did not have any simple method of passing a function as a parameter (e.g. C(++) has pointers to functions). One good example for when this is really annoying is a generic sorting method. The only way to pass a custom comparison method to ...


5

Objects are models. They don't have to correspond to real-world objects. Sometimes actions need to be modelled. Take, for example, the typical Bank Account Scenario, that is used in many introductory OO courses. The design that is taught looks a bit like this: class BankAccount { Money balance; void deposit(Money amount) { balance += amount; } ...


2

The code is not strictly TellDontAsk. There are a number of methods where an object is giving some information about itself. Particularly: AnimalWithCollar::hasCollar() ItemForFetching::animalCanCarryIt() AnimalThatCanFetch::canCarryAnItemWeighting() Collar::belongsTo() Collar::hasOwner() You can see that these methods are questions, thus you're asking ...


-2

Agree with flohack that OLE, COM and ActiveX fall into the category of out dated technologies. ActiveX for the browser is dead. Some aspects of OLE are dead. But some aspects are still alive. I think at this point I would not create any more interfaces but if you have to work with older software you may need to consume (and understand) some this technology. ...


4

There are some reasons which can make this design the better alternative: GenericHelperClass ghc = new GenericHelperClass(); // ... // using `ghc` here for other purposes //... ProjectSpecificClass psc = new ProjectSpecificClass(ghc); if the construction of ghc is slow or needs lots of resources, it might be better to construct the object only once if ...


1

My own thought on these sorts of helpers are in effect filling in lacuna in the standard library. They should therefore be held to the same sort of rigorous standards that the standard library is held to. Particularly if this helper class(es) is being used in multiple project, it is essential to validate it with extensive testing. Just as the presumed high ...


1

You're going to need an overflow area, perhaps a stack, or some chunk of memory. You'll also want to get the generated code correct before optimizing it, because optimizing broken code is basically impossible. So , given a stack, you should have something like: PUT b,2; Push b; Put b,7; Put c,3; ADD; Pop b; MUL and if using memory, PUT b,2; Store b @1; ...


0

You're looking for AutoMapper. Lose the inheritance though and duplicate the properties in the ViewModel. Inheritance, especially in this case, will bring pain. Use AutoMapper to handle the assignments automatically, that's what it's been designed for.


0

Personally I rather keep patterns as being emergent, as in, the solution you came up with can be identified/recognized as being the 'strategy pattern'. As soon as you start to use or apply patterns they quickly become a solution looking for a problem. Can one type of expense have multiple ways of calculating tax, for instance depending on persona? Then ...


7

The big hint is in your question: "interface inheritance". Basically, an interface is nothing but a set of method signatures. In a traditional OOP language, the only thing a class needs to do to satisfy an interface is to have implementations of those method signatures, and declare that it implements the interface. Since it's not inheriting implementations, ...


1

Whether or not you use generic parameters as @DavidArno suggests, your interface should probably be written in terms of other interaces, not in terms of classes. It is perfectly reasonable for an abstraction of concepts to require several interfaces. But an interface that consumes and returns classes is probably not fully abstracted. So, keep going until ...


4

The type system can do many things for you, but even the best type system cannot do everything. There is no problem with having several methods with the same type signature but different contracts. Look at it this way: if everything could be expressed machine-verifiable via the signature, we wouldn't need programmers - just spec writers and compilers. The ...


0

In an article titled Design Patterns for Dealing with Dual Inheritance Hierarchies in C++, Uncle Bob presents a solution called Stairway to Heaven. It's stated intent: This pattern describes the network of inheritance relationships that is needed when a given hierarchy must be adapted, in its entirety, to another class. And the diagram provided: ...


-1

To decide whether a code should be duplicated or moved to a function which is called twice, try to determine which is more probable: It will be necessary to change both uses of the code in the same way. It will be necessary to change at least one use of the code so that they differ. In the first case, it will likely be better to have one function handle ...


5

Duplication is OK in some circumstances. But not in this one. That method is too complex. There is a lower limit, when duplication is easier than "factoring out" a method. For example: def add(a, b) return a + b end is stupid, just do a + b. But when you get just a little, tiny bit more complex, then you're usually way over the line. foo.a + foo.b ...


0

You cannot violate the Single Responsibility Principle because it is just an esthetic criterion, not a rule of Nature. Don't be misled by the scientifically sounding name and the uppercase letters.


0

In a project of any size/complexity, I want to be able to find code when I need it for the following purposes: Fix it when it's broke Change the functionality Reuse it. Wouldn't it be lovely, to either join a project in progress or continue to work on a project for several years and when a new request to "connect to internet and show connection results" ...


0

You are violating the single responsibility principle (SRP) as you are both representing data and performing logic in the same class. It sounds very reasonable for me. Model might not have public properties if exposes actions. It is basically a Command-Query Separation idea. Please note that Command will have private state for sure.


17

is it acceptable to copy and paste ... No. For me, the deciding argument is this one: ... it is commonly used ... If you use a piece of code in more than one place then, when it changes, you have to change it in more than one place or you start to get inconsistencies - "odd things" start to happen (i.e. you introduce Bugs). it is ...


0

A class and/or a function is better, at least in my opinion. For once, it makes the file smaller which is a very heavy gain if you deal with web applications or applications for devices with little storage (IoT, older phones, etc.) And obviously the best point is that if you have something to change due to new protocols, etc. you just change the content of ...


7

This doesn't really have anything to do with copy and paste. If you take code from elsewhere, at the second you take the code it's your code and your responsibility, so whether it's copied or written completely by yourself doesn't make a difference. In your alerts you make some design decisions. Most likely similar design decisions should be made for all ...


53

No. In fact, even your "simple" code should be split into smaller parts. At least two. One to make the connection and handle the normal 200 response. For example, what if you change from a POST to a PUT in some cases? What if you are making zillions of these connections and need some multi-threading or connection-pooling? Having the code in one single ...


87

You need to consider the cost of change. What if you wanted to change how connections are made? How easy would it be? If you have a lot of duplicated code, then finding all the places that need changing could be quite time consuming and error prone. You also need to consider clarity. Most likely, having to look at 30 lines of code isn't going to be as ...


2

For what it's worth, this actually has a semi-practical use. In the scenario you have set up, you can only use objects of type A or B via the interface defined by A. The function B::f is only callable via virtual dispatch, not directly. For example: B * pb = new B {}; A * pa = pb; pa->f(); // fine, calls B::f via virtual dispatch pa->A::f(); ...


0

My solution is have a config file where you have a property associated with the method in config. This will be used in a builder class. And also have a config where you give the properties in a xml/properties/json. eg Builder Config name=setName() category=setCategory qualityLevel=setQualityLevel Value Config name=Jack category=metal qualityLevel=1 ...


4

if(input.getId() < 36 && input.getId()%3 = 1){ //if the imput's ID is less than 36, it's a metal, and if ID % 3 = 1, it's a ruined metal, meaning it is smeltable. Giving magic meaning to the id numbers is asking for trouble. What if you want add a new type of metal? What about removing one? What about adding a new state? Multiply this across all ...


3

When developing games it is often a good idea to separate the game engine from the game content by moving such information to external files. It allows to tinker with values without having to recompile the game, it allows non-programmers to edit these files and it makes the game more modding-friendly. However, keep in mind that file access is very slow ...


1

It's absolutely intentional. Changing the visibility must (at most) change whether your code compiles or doesn't compile. It must never, ever change what the code does. If B::f() were public, then you would expect B::f() to be called. The fact that you made b::f() private cannot change this, according to the rule above; it is only allowed to change whether ...


1

I do have some further insight that I can provide. First, about your classes, since the name of an institution should probably remian the same and not change, upon instantiation is the only time that you should allow external implementation to modify that string for the Name -- make it immutable from the class perspective. This would be proper encapsulation; ...


3

I think you're getting a bit too caught up in comparing unrelated types of graphs, and perhaps in thinking about data-flows rather than contract dependence. It sounds to me like you've had a discussion with someone who's talking about the call graph of a piece of software, and/or the associated control-flow dependencies between functions. In a call graph, ...


2

I don't think either of the options you presented is fundamentally wrong. I see you have not suggested the one thing that I would call flatly wrong: hard-coding the role codes in functions outside the Role class. That is: if (user.getRole().equals("Administrator")) ... I'd say is definitely wrong. I've seen programs that do this and then get mysterious ...


2

While I largely agree with the suggestions to avoid constants and have a method isFoo() etc., one possible counterexample. If there are hundreds of these constants, and the calls are little used, it might not be worth the effort to write hundreds of isConstant1, isConstant2, methods. In this particular, unusual case, using the constants is reasonable. ...


1

"most likely clients of this Repository will want to get and use objects through IBusinessObject interface". No, they won't. Let's consider that the IBusinessObject has the following definition: public interface IBusinessObject { public int Id { get; } } It just define the Id because it is the only shared functionality between all business objects. ...


0

If a system — might it be a software, an operation system or an organization — deals with roles and permission, there comes a time when it is useful to add roles and manage permissions for them. If this can be archived by altering the source code, it might be ok, to stick with enums. But at some point the system's user wants to be able to manage roles and ...


5

In addition to what others have posted already, you should keep in mind that using the constant directly has another drawback: if anything changes how you handle user rights, all those places needs to be changed, too. And it makes it horrible to enhance. Maybe you'd like to have a super user type at one point, that obviously also has admin rights. With ...


48

First off, please note that doing something like entity.underlyingEntity.underlyingEntity.method() is considered a code smell according to the Law of Demeter. This way, you're exposing a lot of implementation details to the consumer. And each need of extension or modification of such a system will hurt a lot. So given that, I'd recommend you to have a ...


8

It seems daft to have a function to check whether the code that is stored is the admin code. What you really want to know is whether that person is an admin. So if you don't want to expose the constants, then you also shouldn't expose that there is a code, and call the methods isAdmin () and isUser (). That said, "if User.getRole().getCode() == ...


1

One thing I would like to point out is that all your Add methods are not necessary. If you expose the List<T> like you do, you can use them for adding. And you can use the collection initializer syntax for that: var institutions = new List<Institution> { new Institution("My college") { Terms = { new ...


3

When it comes to reference types (classes), you're already ok since those have Equals and GetHashCode implemented properly even without overriding. When it comes to value types (structs, enums, ...), these should always override Equals and GetHashCode in meaningful manner as well as be immutable as per MSDN design guidelines - struct should implement ...


4

Is it a good practice to use List of Enum values on User? Short answer: Yes Better short answer: Yes, the enum defines something in the domain. Design-time answer: Make and use classes, structures, etc. that model the domain in terms of the domain itself. Coding time answer: Here's how to code-sling enums ... The inferred questions: ...


1

You're right not to use inheritance, and in fact I think your design is fine. Let's take a look at one of your uses of your code. MessageBox.Show(Institutions[0].Terms[0].Courses[0].Assignments[0].Name); While the [0] uses here are standard for testing, in most uses of a class-based design, you would not be accessing the lists directly by some index, eg ...


2

It's not bad for a newbie. You're right to be concerned about accessing objects through multilevel lists. Also, hard coding the indexes will hurt you eventually (but it's OK for now). You might try changing AddNewxxx() to return what was added. For example, if you change Term's AddNewClass to public Course AddNewCourse(string NewCourseName) { ...



Top 50 recent answers are included