Tag Info

New answers tagged

1

I think you're looking for 2 things, but I answered this question a while ago This is a very clear example of the Command Pattern Basically it goes like this: Look up the thing to do Do it If you use a defaulting map (there are implementations around) then, in the event the command was not found, you can do the default which can use the Null Object ...


0

From what you wrote, it is still a little bit unclear what you are after, but I guess when a "Tiger" fights a "Lion", you do not want to have printed "Tiger fights" or "Lions fights", but something like "Tiger fights Lion". And that is nothing for which you need double dispatch or the visitor pattern. Just separate the "output part" from the "who fights" ...


2

The strictest Object Oriented definition of a subclass relationship is known as «is-a». Using the traditional example of a square and a rectangle, a square «is-a» rectangle. By this, you should use subclassing for any situation where you feel a «is-a» is a meaningful relationship for your code. In your specific case of a subclass with nothing but a ...


0

In the example you gave, your partner is right. The two data helper builders are strategies. One is more specific than the other, but they are both interchangeable once initialized. Basically if a client of the datahelperbuilder was to receive the systemdatahelperbuilder, nothing would break. Another option would have been to have the ...


1

As others have mentioned, these methods likely violate SRP. What I do in cases like this is I refactor out common code. Maybe a block of code is frobnicating widgets, but if you take a step back, it is really only transforming one data structure into another in a way that can be generalized. Maybe that is used in both methods: pull that out into a third ...


1

One common way to refactor code like this is through inheritance, using abstract or virtual methods for the behavior that may vary. Let's say you have a method to pay employees, and another one to pay the CEO: void PayNormalEmployee() { // do stuff // do more stuff // give meager bonus // do final stuff } void PayCeo() { // do stuff ...


1

If you are looking for a class for code that calls a winner of 2 animals fighting, then the solution is a third class that does that. Imagine you have to write a compare method that compares objects of 10 very different classes. Obviously you can't have code doing the comparing spread out all over those 10 classes. It's much cleaner to write a Comparator ...


4

First of all, you're setting up Animal interface with generics in order to make the Animal instance passed to fight as the same as the one implementing Animal. In other words, Lion can only fight a Lion. A Tiger can only fight a Tiger. From the sounds of it, you want to be able to fight any animal. If you don't need to use A for any other reason in ...


2

The most common use of such subclasses that I can think of is exception hierarchies, although that's a degenerate case where we would typically define nothing at all in the class, as long as the language lets us inherit constructors. We use inheritance to express that ReadError is a special case of IOError, and so on, but ReadError need not override any ...


2

Too difficult to assess without having a code segment to analyse. Method consolidation should definitely be applied here, you're just going to need to keep a few principles in mind. Have a read through this article on Jeff Atwood's blog: Curly's Law: Do One Thing Pay attention to the three core principles of modern software development, namely: Don't ...


6

This is difficult to answer without looking at the code. However, it is clear that these methods are trying to do too much. They are almost certainly violating the SRP. I would suggest that you begin by looking at where the methods are different and why. Perhaps you could use method injection to inject different code into the method, based on who or what ...


1

Let me first note that as the code is written, the sub-class is not actually more specific that the parent, as the two fields initialized are both settable by client code. An instance of the subclass can only be distinguished using a downcast. Now, if you have a design in which the DatabaseEngine and ConnectionString properties were reimplemented by the ...


1

I use constructor only subclasses quite regularly to express different concepts. For example, consider the following class: public class Outputter { private readonly IOutputMethod outputMethod; private readonly IDataMassager dataMassager; public Outputter(IOutputMethod outputMethod, IDataMassager dataMassager) { this.outputMethod = ...


6

If something is a pattern or an antipattern depends significantly on what language and environment you are writing in. For example, for loops are a pattern in assembly, C, and similar languages and an anti-pattern in lisp. Let me tell you a story of some code that I wrote long ago... It was in a language called LPC and implemented a framework for casting ...


0

In the second version, where you have for (i=0;i<r*c;i++) *d++ = *(mat.d)++;, the key difference to note is that you will be changing the value of d (and mat.d), which is almost certainly something you don't want to do. After the assignment d = new double [r*c]; d is pointing to the new array, and presumably you still want it to be pointing there after ...


1

I think the key to answering this question is to look at this one, particular usage scenario. Inheritance is used to enforce database configuration options, like the connection string. This is an anti pattern because the class is violating the Single Responsibility Principal --- It is configuring itself with a specific source of that configuration and not ...


1

A subtype is never "wrong" as long as you can always replace an instance of its supertype with an instance of the subtype and have everything still work correctly. This checks out as long as the subclass never tries to weaken any of the guarantees the supertype makes. It can make stronger (more specific) guarantees, so in that sense your coworker's intuition ...


45

If all you want to do is create class X with certain arguments, subclassing is an odd way of expressing that intent, because you aren't using any of the features that classes and inheritance give you. It's not really an anti-pattern, it's just strange and a bit pointless (unless you have some other reasons for it). A more natural way of expressing this ...


7

No, it's not an anti-pattern. I can think of a number of practical use cases for this: If you want to use compile time checking to make sure collections of objects only conform to one particular subclass. For example, if you have MySQLDao and SqliteDao in your system, but for some reason you want to make sure a collection only contains data from one ...


13

Which of these intuitions is correct? Your coworker is correct (assuming standard type systems). Think about it, classes represent possible legal values. If class A has one byte field F, you might be inclined to think that A has 256 legal values, but that intuition is incorrect. A is restricting "every permutation of values ever" to "must have field F ...


0

I think you are missing 1 or maybe 2 layers in your design which is why you are not sure where to put business logic or 'builder' code. You should consider adding a service and possibly repository layer. The service layer is a layer that interfaces between controllers and the model/repository. It may contain business logic or may just be a thin API layer. ...


5

My problem is that the code that I have inherited is, in my opinion, absurdly over-engineered. I have enormous problems following the program flow and finding any concrete implementations of anything. The amount of abstractions are totally mind-boggling and there is no documentation whatsoever. Its not you, I find that a lot of C# and Java (and ...


0

So in the ideal world your controller should not contain any business logic or business objects. These should be completely located in your domain model layer. Referencing to "Patterns of Enterprise Application Architecture" by Martin Fowler the controller is even part of the presentation layer, so only responsible to pass the input data to your business ...


2

No, Chain of Responsibility doesn't make sense here, because it assumes all components have same interface. I don't think Java's type system is good enough to make this fully generic, so I would opt in to type erasure and some kind of "manager" that pipes output of one module into input of next one, while encapsulating the erasure. The module's interface ...


5

For the use case you've described, I think it's a valid pattern. However, there is no name for this, AFAIK. In Java 8, there is a Map.getOrDefault method, which almost does that: String greetingKey = "Hello"; Map<String, String> i18n = new HashMap<>(); i18n.put(greetingKey, "Hola"); String greeting = i18n.getOrDefault(greetingKey, ...


1

This doesn't sound like any Dictionary class I've heard of, but it could be trivially implemented by wrapping a dictionary in another class (or inheriting from it) and modifying the Get behavior.


3

It's just a class within Noda Time. It's not a specific design pattern that I could name. It's used to build up a text parsing/formatting pattern which consists of a number of steps. When formatting a value, we basically start off with a value (e.g. a date) and an empty StringBuilder, then apply each step in turn, supplying each step with the current ...


0

I would recommend your solution c), but I would change it a bit: I would not display some error from the can_vote function. The user should know long before that if he can vote or not and why. The vote() function only checks if the user can vote as a safeguard, because as you said yourself there should be NO WAY your program ever calls vote() when the user ...


2

I would change few things: remove singleton, make private static $container = [] anyway you're just using static methods to retrieve it. consider throwing special exception when getting not set service. re-consider automatic caching for services (it is possible you may not want it for every service) Considering pattern/anti pattern discussion I've found ...


1

Option 2 is by far the best, if I correctly understand what you mean. Your default mouse wheel listener presumably does a certain job; let's say, it scrolls. Your client's need to set their own listener tells me that they don't want you to scroll, so that they can use the mouse wheel for something else. But you see, how you achieve this scrolling on ...


0

An alternative approach I've seen is listeners having the ability to cancel subsequent listeners. For example, DOM Events supports this. This relies on listeners being called in a well-defined order. I think it's pretty standard that listeners are called in reverse order of registration, but check your particular framework.


1

If your pages get big try to decompose them into smaller Panels. I dont like in your code that you have only one method in the constructor. If it it like this i would omit this method and write all in the constructor. We use an approach where every component is created within a function and returned from there. This allows us to keep every information ...


1

Why do you want them nested in your access layer? That API exposes plain objects, not trees of them as I can see. So, you may build your internal API mimicking that one. class Category { public static Category[] getList(); public static Category getById($id); public static Subcategory[] getSubcategories($id); public void fetchDetails(); } ...


0

When you notice large blocks of if/else, it usually means that your class or method is doing too much. Instead of trying to rewrite the logic inside the method: Ensure the method does one and one only thing. Replace the class by multiple classes which inherit from a common one. For practical examples, if you have an actual working piece of code but ...


7

The first difference can be summarized as: this refers to the Instance of the class. prototype refers to Definition. Let's say we have the following class: var Flight = function ( number ) { this.number = number; }; So here we are attaching this.number to every instance of the class, and it makes sense because every Flight should have their own flight ...


-1

First and foremost, calling Singleton2's getMyObject() method will crash the program because it does not create a new instance when it is null, and will just return null. Second, there is no getMyObject in a singleton class. There is just getInstance().


0

Much of the discourse on the topic here makes sense, though there is something very fundamental about C++ that makes namespaces and classes/structs very different. Static classes (classes where all members are static, and the class will never be instantiated) are themselves objects. They are not simply a namespace to contain functions. Template ...


3

This has nothing to do with design patterns... This is a solved problem, that has been solved over and over since .Net was invented. Just use Commons.Logging it's a small configurable liberality that does exactly what you asked: https://github.com/net-commons/common-logging


3

Congratulations, you have (re-)discovered the Object Adapter Pattern. You have one target interface (here: ILogger), and various adapter classes NLogPlatform, Log4NetPlatform, …. Each adapter class conforms to the target interface, and proxies all calls to the adaptee object which it contains as a member. If you want to make the use of this pattern clearer, ...


0

I believe what you are trying to do is to reinvent Symfony Forms and add some bunch of ORM to them ;) They indeed contain all the data from the form and all the form HTML structure described in a very declarative way with a possibility of extension. But I think you are wrong when you want forms to be able to query backend data. This is incorrect. Form ...


1

You're basically writing a compiler, which translates from SQL to whatever your datastore understands. In the end, you'll probably have the following parts: a Parser which takes SQL and produces an Abstract Syntax Tree a bunch of Visitors which do semantic analysis and/or rewriting on the AST an Interpreter which finally executes the (processed) query ...


0

Primarily Adapter to adapt native datastore commands to SQL dialect. IMHO I would advise you against exposing SQL API in such case. You are better off delivering native datastore-like commands (possibly wrapped somehow) that are supported by datastore developers. Simply - do you create costly overhead that won't deliver much value?


1

Here is a solution I have used often in the past: create a regular Excel document (typically in xlsx format) as as template, containing all column headers, including their title and a default formatting for the columns and maybe formatting for title cells. embed that template into the resources of your program. At runtime, the first step is to extract the ...


4

isValid() could be a method implemented in a Strategy pattern. IMO, the benefit of the pattern is future modifiability. That is, there will be a future need for new implementations of isValid() and you don't want to change your code that iterates and validates. In the definition of Strategy, that's the Context class. Your select block, which I believe ...


0

Use a multidimensional array like $key => $value, $key2 => $value2 and iterate? $data = array( 'column_name' => 'value' ); querysorter ( 'tblname', $data ); function querysorter{ foreach($data) //bindparam here } Hope this helps, just had to do something similair.


-2

I can write as follows: public class returnvalue { public int add(int x,int y,int a) { int z=x+y+a; return z; } public int subract(int a,int b) { int c=a-b; return c; } public static void main(String[] args) { returnvalue b1=new returnvalue(); int r=b1.add(20,30,10); System.out.println(" sum of two values is " + r); ...


0

This is a blog about the death of OOP and the conclusion at the end is that ECS are not OOP: http://loup-vaillant.fr/articles/deaths-of-oop


1

One common benefit of a creational pattern is to change program behavior from one run to another. This could be done by a command-line argument, for example. Perhaps specifying a switch to enable functionality results in a factory creating a different type of object, say by creating a different type of output writer for a file vs. standard output. Maybe ...


1

In Java, if DerivedFoo: BaseFoo, saying foo = new DerivedFoo(boz); will construct a new "blank" DerivedFoo instance and call the a DerivedFoo constructor that can take boz as a parameter. That constructor must in turn call one of BaseFoo's constructors before it is allowed to do much of anything with the object under construction or with the passed-in ...


0

Generally speaking, the more you follow the "guideline, not law" of Demeter, the more code you will be writing, as you must hide objects from one another.



Top 50 recent answers are included