Tag Info

New answers tagged

0

Just to supplement what other people have said, worrying about virtual function dispatch time is worrying about trivia. A large hierarchy has another, hidden, source of performance issues. You need to know how to clean these out, on an ongoing basis, while developing the code. Here's an example. The hidden source of performance issues is this: Most lines ...


1

I'm finding it hard to believe, under the presence of a data-store or persistence, that you would need to have objects with this kind of depth at any given point in a run-time. Is this for CRUD GUI's? If so, then I would suggest changing your approach from the start. IE: Identify the substructure necessary for the Student to show, and statefully store its ...


0

Do all the classes really need access to the entire object? Otherwise, this looks like a correctness problem (but not in a bad way), rather than a design problem. One approach is to consider a code contract enforced by a caller: f(g, exchange-object) { /* pre-condition/invariant */ assert(exchange-object.open() == true); g(exchange-object); /* ...


0

A couple of points about optimization, first: the overhead for a virtual method dispatch vs entering a case statement is roughly the same; unless the rest of your code is extremely efficient, it is unlikely to make a noticeable difference. regarding cache usage, unless the per-role routines are small enough to fit more than one in a single cache line, ...


0

You can use Visitor pattern. Visitor pattern with C++ templete is highly efficient. class T1 { public: void do(Node& node) {...} }; class T2 { public: void do(Node& node) {...} }; class Master { public: template <typename T> void traverse() { T t; for each node in the tree { t.do(node); } ...


3

Consider the concept of a closure (see e.g. this question and its answers). A closure saves you from passing around extra arguments that are known in a given context. For example, instead of writing: def addTax(taxPercentage, amounts): def computeTax(perc, amount): return perc * amount / 100.0 return [a + computeTax(taxPercentage, a) for a ...


5

So we're looking at a big fat static method broken down into bite-sized pieces. I would definitely recommend putting it into a class, even if it is for a single purpose. Your process has a state and that state can be maintained through class members, so yes absolutely. Just be careful to distinguish between operation parameters and process parameters. ...


0

So if I understand correctly, you want a sort of Data class that allows you to read and write to it without knowing the underlying details of how it works. You can do this by using an AbstractFactory pattern which provides these Data classes for writing/reading. Each factory will have its own implementation with a method to initialize and a method to ...


0

Where you're going to gain with the granular approach is if you have to configure your program where you need a different six roles at different times. This would keep you from having to load or even think about the other 24. And if you need another 30 roles, it's much easier to add those as individual classes than have another 6000 lines in your switch ...


2

You've possibly already seen some variant of Donald Knuth's "premature optimization" quote: We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. This is a good quote, but it's equally accurate if you replace "premature" with "misplaced". You talk about traversing large trees and executing ...


0

I like this builder. Do you really need a Builder in your case ? Liking a pattern is not enough to justify its use. Upto 4-5 arguments, creating instances of your class directly by the constructor greatly simplify your code, plus allows you to make your class immutable. public final class Example { private final String first; private final ...


0

Looking up a simple example (https://github.com/facebook/flux/tree/master/examples/flux-todomvc/), “stores manage the application state for a particular domain within the application.“ That is, they contain data about the state of an aspect of the application and all the code to change it. Whenever there’s an new update from the Dispatcher, all the Stores ...


0

Depending on how you will implement your application you can create a resource/API to generate a token as @Telastyn said (or you can use an authorization server - a different application to generate and validate these tokens) and pass it as a header field (usually people use the Authorization header) and your API check it's validity (in the same application ...


3

In general: User logs into some authentication system. Authentication system provides a token that effectively says "Authentication System X asserts that you are Bob, until 3:00 PM 8/31/2015 UTC". User then passes that token as metadata (header, some data envelope) to the various APIs. The various APIs look at it and decide if they trust Authentication ...


0

It's a pretty good instinct to balk at creating one hundred very similar classes. That's generally a sign those should be instances instead. You might try something like: monitors.createIntMonitor("Floor", "DM141") monitors.createBoolMonitor("Front door open", "DM142") monitors.createEnumMonitor("Direction", "DM140", ["Up", "Down", "None"]) // or ...


0

I would try to find a middle-ground. If there are, as you wrote, a hundred or more of types of information, the chance is high there will be a lot of similar types, with similar interface signatures. For example, instead of having an ElevatorFrontDoorStatusMonitor and an ElevatorRearDoorStatusMonitor, create ElevatorDoorStatusMonitor, where "Front" or "Rear" ...


0

The path you'e gone down gives you something that's "type-safe" (one specific type per thing to observe, more-or-less) and is more loosely coupled. That explicitness of each type to monitor individually allows loosely coupled observers. The only issue, as you've seen, is the amount of work to support each one of those unique items. Code-gen might be ...


1

One solution to this problem I've used in the past (where a large number of decorators add facilities to a relatively simple base, with many possible interfaces) is to have a base class for both the decorators and the classes they wrap, regardless of interface they implement, that has a method declared (using Java's syntax): public <T> T ...


3

First of all, I wouldn't approach a clean architecture in PHP. One of the main goals of clean architecture is to allow the user interface to be considered as essentially a plugin to the application, allowing you to change between types of UI easily. By going with PHP you are restricting yourself essentially to web-based interfaces. If you are familiar with a ...


6

I see a few options depending on what you need: (1) if there are many unique instances that follow a common algorithm, (2) if there are many similar objects or you will generated objects at run-time, and (3) if you want to dynamically modify the object's behavior while running. Note: you can combine all of the patterns I mention here, if need be. If each ...


0

We used put together a single method that did nothing but determine what things had to be set up and returned a value that was passed into a second method which was really just a giant switch statement. Each element (such as isGpsAvailable) had its own method that was placed in the appropriate case depending on the environment.


0

It depends on your concrete repositories, but generally speaking, I would add a service layer on top of the repositories. Depending on your repository implementation, they might be specific to your persistence store. It makes testing easier as well and leads to a hexagonal architecture, instead of a classic layered architecture (which I consider a benefit), ...


3

It depends. When A and B obtain their data each on its own, this has the advantage that both are independent from each other, and A may be used without B, and B without A. The disadvantage is that you might need to pull the same data over the network twice, and that the data displayed by A and B might not be always consistent because the content changed ...


1

Yes, the service layer is an overhead if you don't have any business logic there. Layered architecture looks like an overhead when a layer (in your case service) is not doing much. But a layered architecture provides your loose coupling which is generally good for adapting requirements in future. If you can guarantee that you will never need to do anything ...


1

According to Vaughn Vernon it is best to use entity framework as state objects when designing aggregates when designing aggregates because they are inflexible compared to other ORMs. With that in mind. Why are you starting with entities? In DDD you need an aggregate root to maintain the consistency boundary. An aggregate root may have entities and value ...


1

A contractor can be assigned to several sites. A site can have multiple contractors assigned to it. When you fetch sites for a contractor, will you also fetch each site's associated contractors? And will you then fetch their sites? Letting the lazy evaluation and reference resolution already implemented in EF do the work for you really pays dividends in ...


0

In general, you need more concepts and more relationships between them, or you'll have problems as your modeling expands. For one, it seems to me that you are missing a notion of Contract. The notion of start date and end date relate more to the specific contract rather than the contractor (the contract then relates to the contractor). I think you should ...


0

When a user interacts with a React view, the view propagates an action through a central dispatcher, to the various stores that hold the application's data and business logic, which updates all of the views that are affected. For an example let's say we have two views: menu and content. They represent typical main menu and content area of a web page. When a ...


0

Given that you're using Rails, the most common way to achieve what you're trying to do is to use a before_save or before_create ActiveRecord callback. class Model < AR::Base before_save :normalize_attributes private def normalize_attributes # Whatever logic you need end end my_object.attr_a = get_the_stuff_from(ref_one) my_object.attr_b = ...


11

The problem you are addressing is quite fundamental. I have experienced the same problem when I worked for a company that made a large J2EE application that consisted of several hundred web pages and over a million and a half lines of Java code. This code used ORM (JPA) for persistence. This problem get worse when you use 3rd party technologies in every ...


0

Both Have a central controlled table with: ID int PK Code varchar Then let app have table with: ID PK FK to central add as many flag columns as they want This way you still have one column for Code Another option is an app table CountryID FlagID Value This way your columns become rows Problem you have here is rewrite a lot of queries


7

The problem you facing is an old one: code for persistent objects often looks similar for each class, it is simply boilerplate code. That's why some smart people invented Object Relational Mappers - they solve exactly that problem. See this former SO post for a list of ORMs for PHP. When existing ORMs do not suffer your needs, there is also an alternative: ...


4

The answer may be simpler than you might have originally thought: replace the "Countries" table shared across monolithic database-centric apps with a microservice, or simple webservice that exposes the same functionality with a simple REST call (note: I'm suggesting REST though that is not your only option, though it is probably the lightest-weight option). ...


2

The benefit of immutability is that it doesn't matter as much what you do with your references to it. Globals, static classes, and singletons are much less problematic than their mutable counterparts, because you don't have to synchronize mutations and track the order dependencies that creates. However, they still have the issues with mocking out for unit ...


-2

(This entry is a wiki. Please feel free to improve this answer) Here is argumented how using static for immutable might be preferable, and related concepts. Constants themselves are defined as global. Objects that wont change not only during runtime, but wont have alternatives values (like a filesystem path might change depending configuration) a priori ...


4

Fundamentally, there's no problem described in the question that actually needs a solution. You've given no reason for a Foo holder to exist, or what it should be able to do. So really, FooList is completely useless. If you need a Foo, there's a language feature for that- new Foo(1). There's no reason for any additional holding to be baked in to the Foo ...


7

The problem is that you've effectively created a global variable for accessing these objects, the Foolist class. This has drawbacks for things like testability and is in general just poor design. Global state doesn't help make code easy to read and the consuming classes can never be isolated from the Foos (look up mocking) d when testing. Avoid the static ...


0

I think a nonpublic set for "user editable" properties is just making work for yourself. I'd leave them public (for changeable properties, i.e. not Id) and then either use the DAO-style .Edit and .Update state change methods (where attempting to change before calling .Edit throws a runtime error), or simply always allow changes and supply .CommitChanges to ...


2

How about simplifying the call to virtual int matchCount() by removing all arguments, and instantiating each Strategy with the arguments of the matchCount method in your question. Then you inject the concrete strategy into your Context. Here are some ways to use the strategies (I'm not sure how it works in your real problem because there are no details in ...


0

I agree with @BartvanIngenSchenau : add the validate inside toString. Also: toString would be much better be renamed to build, to more strongly suggest a Builder Pattern. Unlike C#, in PHP the convention is to NOT use the letter I in interface names getters are not necessary maybe mark the validate method as private. From what I now, in the context of the ...


1

It looks like you want to spool the result of HTTP requests. Indeed, you might use some caching HTTP proxy like squid (you might use it, instead of coding your own). You could use both HTTP client libraries (like libcurl) and HTTP server libraries (like libonion) in the same process (but probably in different threads, or thru some event loop like libev or ...


1

Should, for example, each tile store the data of its reward or there should be a reward manager for checking how many tiles are consecutive next to each other to give the reward to the player? How I would do it You have a Reel object that can be spun randomly You have a number of Reward objects that have a threshold required to win, and a prize amount ...


0

I have encountered this exact problem. I was not satisfied with the way I solved it, so I didn't answer your question right away. But on the other hand, neither does any of the other answers here. My solution: class IAlgo { virtual int matchCount(AlgoParameters *) = 0; } class AlgoA1 : public IAlgo { virtual int matchCount(AlgoParameters * ...


3

As indicated in the comments, there is no mixed usage of algorithms from the different families. If there is no use-case where an IAlgo can refer to either an AlgoAN or an AlgoBK instance, then there is no reason to have a shared interface for the various families of algorithms. The best way forward is to introduce a new interface for each algorithm ...


0

Optional arguments. Declaring the new arguments as optional allows you to add parameters and not break the existing code. Overloads. Split the strategy interface into multiple methods. Messages. Create a hierarchy of argument objects and pass them to the strategy instead of "loose" parameters. The mature calling code, will keep sending the messages, ...


1

List<String> parcelList = new BufferedReader(new InputStreamReader( inputStream, StandardCharsets.UTF_8)).lines().collect( Collectors.toList()); Welcome to the world of Java 8 and stream-based operations! This means that the subsequent explicit looping using a parcelListIterator is unnecessary... you can simply daisy-chain your steps as such: try ...


6

When the HTTP request is completed, it will return some data, and the model gets updated by the responsible part of your system. Then raise an event which tells everyone who subscribed to it "new data has arrived", but do not pass the actual data in this event, only the relevant information for the subscribers which part of the model has changed. The event ...


2

Keep your DTO's simple You are right that having a command with 9 arguments in the constructor is ugly. But do you really HAVE to put those things into the constructor? Make your fields public, create your command with an empty constructor and just assign to the fields. The point of constructor arguments is to have guaranteed valid entities, since you are ...


0

In my app, the logic flow goes Controller builds DTO Controller dispatches to Command Bus Command Bus Calls Events Event Handlers dispatch to the Command Bus as well Command Handler returns a response DTO to the controller Controller generates a response to the client based on the response Your application seems similar. Decoupling is also an issue for ...


2

Most dependency injection containers can be configured to create the dependencies as well as inject them. No need to have a separate process to create dependencies. Here is a simple example using the PHP Pimple container(http://pimple.sensiolabs.org/) // This is the importer service definition $dic['arbiter_schedule_importer_games_with_slots_xml'] = ...



Top 50 recent answers are included