Tag Info

New answers tagged

0

I'd suggest you come at the ISP from the perspective of client code. In how many places is your class being used? Is there any client class that only needs one method but not the other? If all client code needs both, there really doesn't seem to be a case for two interfaces. If you do have two different places where your class is being used, with each ...


0

I'd implement a BanCommand class, which takes care of this. Domain models don't necessarily have to have state; sometimes they represent actions that take data and do something. That's pretty normal OO too; objects are behavior + state, but sometimes the objects don't really need any state to do something useful. That's why I always list behavior before ...


1

Composite often goes hand in hand with Builder pattern to address exactly the problem you have mentioned here. You can create a separate class, call it PageBuilder (or whatever suits your fancy) and move all the building logic into that class. Although I don't know the internals of your code but considering a very generic composite/builder duo here is some ...


1

I would call one object's method from the other, to avoid code replication. I would find a way to do this like that : class BanService() { public function __construct(IUserRepo $userRepo) { $this->userRepo = $userRepo; } public function banUser($userId) { $this->userRepo->getUser($userId)->ban() } } or ...


0

The approach I've used a few times (I'm not sure if it's recommended or not) is as follows: Code business logic into dedicated business logic classes Have your entities use these business logic classes so that they aren't anemic Whether they're injected at construction, or simply directly instantiated is up to you. Any time I need a certain entity's ...


0

No, you don't need them, and I consider it an anti-pattern to automatically make interfaces for every class reference. There is a real cost to making Foo/FooImpl for everything. The IDE may create the interface/implementation for free, but when you're navigating code, you have the extra cognitive load from F3/F12 on foo.doSomething() taking you to the ...


3

That's exactly what interfaces are for. The programmer doesn't care what types of objects might be in the list, as long as they provide the method calls expected of any Observer. This way, your list can contain instances of MyTopicSubscriber, MyFileSystemChangeSubscriber, MyMailboxSubscriber, etc. (these are fictitious titles, of course). By using ...


2

Unless you come up with some specific code that changes my mind, I'm going to say that MVCS is just a slight variation on MVC that makes it clearer that the Business Domain lives in the Model, and is technically separate from the data Store. MVC just includes S (the data store) as part of the Model, but the business domain always lives there.


1

If you are getting major push back from the rest of your team, you should probably stop writing/refactoring things into that pattern, and use/leave the prevailing style instead, at least until you can find a persuasive argument in favor. In your issue tracking system, do you have a body of fixed bugs where the problem was in the area of confusion over ...


0

I am working on my own Java 3D engine with LWJGL which leads me to my answer below. I don't know much about JOGL. Both LWJGL and JOGL are just Java bindings to accomplish the same thing, which is to call native code that changes the OpenGL state of the current context. For example, in the current thread, a call in LWJGL to glCreateProgram() will call the ...


0

Ok, the actual question was about how to handle the difference between {FOO, 54} and {BAR, "hello"}. This is classic use case of an union: struct A { int id; union { long val; std::string s; } un; }; unfortunately, unions don't handle constructors very well, so std::string wont work very well inside union (unless they changed it recently :-). But there's ...


0

What I ended up when writing serialization was the following: class ParserPairBase { public: //virtual std::type_info TypeInfo() const=0; virtual size_t SizeOf() const=0; struct PtrSize { char *ptr; size_t size; }; virtual PtrSize BaseParse(std::string s, bool &success) const=0; virtual std::string BaseCreate(PtrSize psz) const=0; }; ...


0

I will approach it from different side of things - in this case you will get the advantage of branch prediction. If you say you have a sorted sequence, this should be ideal in your case. The idea is your original if statement will be extremely fast before the crossover and shortly after. So, chances are it will be faster than actually having logic around ...


3

The simplest code doing the job is the best. The first version just works. And it is very simple: All it has to do is to evaluate which of two functions to call, and then to call the right one. Little chance of error. Trivial to change if the determination what to call changes. Now you are making things complicated. You assume that once the second ...


6

What you are proposing looks like a Replace Type Code [or a conditional] with State/Strategy refactoring. Possible reasons for doing it: Conditionals have become complex, or are anticipated to become complex in the future. The conditionals incur delays or tax resources. Reasons for not doing it: The conditionals are simple at the present, and the ...


0

Yes and no and it depends. MVC is one of the terms which once had a very specific meaning, but then have grown in use to become a much broader and less specific term. The original use of MVC was specifically as a oo design pattern used when coding desktop GUIs in Smalltalk. The pattern was specifically concerned about separating the data displayed in a form ...


0

The Timeless Way of Building, which introduced the idea of Patterns was written in 1979, and it took another decade until programmers started to take Christopher Alexander's ideas and apply it to software (Design Patterns: Elements of Reusable Object-Oriented Software was released in 1994). The original MVC paper(s) were written starting in 1978, before the ...


0

I would strive for data-driven design. This means that your code is driven by customer specific data. This data may be stored in database or configuration files or whatever suits you best. This way you don't have to build different binaries for each customer with the conditional build directives. In cases where you need different behavior for different ...


1

I am creating my own answer (after a discussion on meta) because I believe that the correct answer is in fact a combination of everything so far. Firstly as DavidArno put, the pattern that I have asked about is more of an anti-pattern because it is just hiding the problem somewhere else. However I believe the suggestion of using the builder pattern from the ...


1

First thing you should check is how many lines of code a typical Organization class implementation has, and how it is structured. If it has less than 100 lines of code, and the class consists mainly of properties providing some flags or data, do not worry. If it has more than 2000, and it contains a lot of business logic, you should consider to split it into ...


1

I think you are almost there. You are getting the State and the Strategy. The way of selecting maybe would be a Factory or a Builder maybe reading a configuration file or a database just as you pointed. At the end it will depend on your own requirements, but the strategy mixed with the Factory or a Builder Pattern to create the object which contains the ...


0

As Doc Brown says, joining properly indexed tables is efficient You make it easier on your application by defining appropriate views and dealing with the views rather than the underlying tables e.g. (Tested on SQL-SERVER, you didn't specify an RDBMS) See Fiddle CREATE VIEW URLsInPage AS SELECT Links.[Name], LinksInPage.[Page URL], ...


3

Have a look at the Builder Pattern. It solves exactly the problem you are having - too many parameters in a constructor. You wind up with an empty constructor (typically in Java this will be a private method, if you use an inner class as the Builder) and setter methods (which may also remain private), then a Builder class with chained methods which call ...


11

I'd call this the "Elephant in the Room" (anti)pattern. You are focusing on the minutiae whilst ignoring the bigger problem. If you have a class that requires 15 constructor parameters, then this a warning sign that the class is doing too much and thus needs too much configuration. The "pattern" you need here therefore is the Single Responsibility ...


-1

The Factory pattern is the most overused and abused design pattern. I have come across numerous cases where a Factory class is coded when a simple constructor would be adequate. Dont use a factory class unless:- You depend on an external resource but you don't know exactly which one yet. Construction is expensive and you want to build once and reuse many ...


1

Here are my views on the various observation patterns. I may update this list over time if comments seem to require it. Callback with closure: This is great if you have some sort of one-shot thing (like a network response), or multiple responses that all need to be handled the same way. Not so good if you are expecting multiple responses which need to be ...


2

This is kind of an opinion question - but I would say yes, keep them separate. While keeping them together may be less complex in the short run, in the long run, separate repositories make scalability, updates, bug fixes, and extensibility much easier. In terms of scalability: if you decide to host the frontend in multiple places, you can simply build and ...


0

I have encountered this issue several times and found the following solution at best. Please keep in mind this is my approach and your preference may be different. I always try to keep any form of SQL interaction inside the repository. Therefore the create method should be declared inside the repository. Now the issue with the ID persists. When looking at ...


0

I solved this when I started using service providers with a dependency injection container to implement a module system. Treating modules as service providers for the application is what worked best, whether they are providing new services or providing to data to existing services, like routes. The admin panel has itself become a module that simply ...


2

A competent production-quality industrial-strength compiler, with optimization turned on, will automagically transform Snippet2 into Snippet1. If your compiler falls into that category (and most do), there's no real reason for a preference. Personally, being one who believes in being terse, I'd've coded it as: private static void Snippet3(string[] args) { ...


3

Tomorrow your boss will tell you that they want to have most of the messages in RED color and a few in BLUE with extra padding... and you are pretty much into major refactoring with both of your approaches. Your Program class is responsible for decision making and printing at the same time. That way Single Responsibility Principle has been broken. So, I ...


2

$this->$data['id'] = $db->insertANewProduct($data); I think is a bad practice, because breaks de Single Responsibility Principle, the product class knows it's been persisted. You are loosing what you win with the repository pattern. If you want to do that another option (less OO) is Active Record. I would choose the option 1 public function ...


3

I also believe that it's more clear to have an unique invocation if this one need to be changed later. The uniqueness of the invocation can be subject to change, too. Maybe you don't want to print anything any more if there is no argument and you don't want to call Print at all in this case. I don't think there is a definite answer to your question ...


3

I'd clearly choose the extra variable approach, because DRY. The varaible name additionally conveys the meaning of the argument (e.g. it could be warning or log_entry, etc).


0

Maybe you are missing a layer. Without knowing the details of your application (requisites, architecture, etc) I would do something like Client (whoever it be) -> Application Service -> Domain Model The application service layer is allowed to interact with the repository and the domain model containing the business logic. So you can have something like: ...


2

configuration object or config object are the terms often used to describe this construct. It allows to rearrange the parameters in any order, because the properties of the generic object have no ordering. And you don't need a long list of optional parameters.


0

You would typically want UI strings like this to be pulled in from a string table instead of being hard-coded in the source code, for localization and ease of updating. So the approach I would take would be to use the inputs to build a lookup key, so something like: var lookupKey = "SALUTATION_" + gender1 + "_" + gender2; var format = ...


1

The data structure that you're describing is often used in JSON documents where you have a list of objects, each with attributes (keys to dictionaries) and their values (the mapped portion of each dictionary). In the DS that you give, you can think of obj_1_id and obj_2_id as objects and key1 and key2 as those objects' fields.


2

It's neither a pattern nor an anti-pattern. There's no specific name for it. It is exactly what it appears to be and its quality is determined by the program using it. Does it make sense? Not to me, not without context. Could the outer array be removed and the IDs moved into a single object? Maybe, depends on the program. Could the nested objects be ...


0

The pattern you are referring to is called Dependency Injection Basically, in most cases, the application calls the library/object for the information it needs, but in some cases, the object needs to first get configured what should it serve the application with. But if a generic object assumes or gets it from a hard-coded location (say config file etc.) ...


8

Titles really belong in the database, but you stated you have no control over this. You have not specified a language tag but the syntax is in the C family, so this will be pseudocode that is almost C++: map<string, string> titles; titles.emplace("M", "Sir"); titles.emplace("F", "Madam"); cout << "Dear " << titles[gender1] << " " ...


3

ratchet freak's answer is quite a good idea if the sentences are all the same pattern, but with two insets, one each only dependent on gender1 respective gender2. Phil W.'s answer is probably the most flexible answer as it allows explicit control over the greeting, though he's quite correct it's a radical change. You might not have the data in that form. ...


17

Radical solution: Let the user specify their own title (from a predefined list that you provide). Your solution (as viewed through English eyes) only appears to cater for Lords ("Sir") and ladies; most men would be addressed as "Mr", most women as either "Miss", "Mrs" or "Ms", depending on their marital status and personal opinions. Then there's a whole ...


0

I see you use php, try to stick to the psr coding styles: psr-1 and psr-2. Look into the decorator pattern. this is a pattern commonly used in these kind of situations. Edit: added a small example You probably have some kind of LineItem class that is used to represent items in your cart. They probably look something like this: interface LineItem { ...


2

If your language allows you to do it, you can write switch(gender1+gender2) { case "MM": print "Dear Sirs"; break; case "MF": case "FM": print "Dear Sir and Madam"; break; ... It's not necessarily better than your version, since there's still duplication, but it does avoid the nested switch.


29

Add the title to the parameters of the printf: char* title1; switch(gender1){ case 'M': title1 = "Sir"; break; case 'W': title1 = "Madam"; break; case ...etc. } char* title2; switch(gender2){ case 'M': title2 = "Sir"; break; case 'W': title2 = "Madam"; break; case ...etc. ...


1

A Factory or Factory method is a way of creating objects without having the calling method be aware of the specific class of object that is being created or the dependencies it has. It takes away the complexity of instantiating objects for which (some of) the properties are not known at code-time but can only be known at run-time. Your Entity Translator ...


-2

Opengl has been designed as a C library, and it has the characteristics of procedural software. One of the opengl rules coming from being a C library looks like this: "When complexity of your scene increases, you'll have more handles that need to be passed around the code" This is feature of the opengl api. Basically it assumes that your whole code is ...


0

What you need is CQRS(Command Query Responsibility Segregation) The idea is that what you save and what you load back and edit later is not the same object. This way you have control over what fields are private and what are public. What can be updated, and what can't. In CQRS you have Command Model and Query Model. Command model is responsible for ...


1

One of the problems of using global variables is that it can lead to conflicts when you use them with other modules that also uses the same variable names and are also declared global in those modules. Say you have a Javascript file call it main.js and in that file are codes where there are global variables A, B and C. Then, your colleague who is also ...



Top 50 recent answers are included