New answers tagged

0

Ended up removing all classes in my codebase—outside of unittest.TestCase)—and just using defs: In [1]: import doctrans.transformers In [2]: doctrans.transformers.__all__ Out[3]: ['to_argparse_function', 'to_class', 'to_docstring', 'to_file', 'to_function'] In [4]: import doctrans.docstring_struct In [5]: doctrans.docstring_struct.__all__ Out[6]: ['...


0

Helper is a commonly used name appendage. However, it communicates very little about what it does. Every time I have seen it used I have found it to be a suboptimal name. In fact I consider it to be a code smell that indicates more problems underneath. Example Suppose we see the name "WidgetHelper" (here "widget" is a stand-in name for ...


2

That’s not the way a saga works: every involved microservice performs a step, which is locally handled as a transaction. every completed step shall result in an event to be triggered the events must be handled in a reliable way for example using an event queue the update of the local database shall be atomic with the event message. This is key to ...


1

What is validation? Its a border guard between the unruly, disordered mess out there, and the nice well-behaved order in here. There are a lot of borders. There is the border between the keyboard on the input control. The border between the input control and the ui code accessing its value. The borders between various parts of the UI, as the data is passed ...


1

The name of that particular anti-pattern is procedural design. In short, you are separating data from behavior, which arguably disqualifies this kind of design from being called object-oriented at all. More importantly it pushes the responsibility to handle these data things right to the caller, which is exactly your problem. The way to fix this, is to hide ...


2

The general relationship you have between your classes (0..1 User to 0..1 Thing) is a perfectly valid kind of relationship. It's less common, but valid in the right situation, which this seems to be. However, you need to be very careful here. Your current setup creates a lot of room for contradiction. Part of this is because you store this information twice. ...


1

One way to ensure consistency of circular references such as this is to implement idempotent set/unset operations which call each other recursively unless the target condition is already satisfied. I don't speak C#, so please accept pseudocode: class User { public Thing curThing; function setThing(Thing aThing) { if (this.curThing == ...


6

Whenever you have tightly coupled objects with circular dependencies, you have one of three cases (in an order of likelihood that I just pulled out of thin air, but sounds plausible): You are missing an object, and the two objects are actually three objects. The two objects are actually one object. The business domain you are modeling is indeed circular, ...


1

Whenever I modify one of them, I often need to call a corresponding function in the other class. If I am not careful about which functions call methods in the other class, I can end up with a stack over flow. When reading this, my first thought was that User and Thing really should have been one class, but that then doesn't match with moving a Thing ...


65

For long-running operations, it often helps to model the active job as a REST resource with its own structure and/or sub-resources. For example, starting a job may return a result such as 202 Accepted Location: https://example.com/jobs/123 At that URL, the client will get a structure such as { "status":"running" } as long as the job ...


2

Including any public properties in base class is an anti pattern to begin with, or at least it's a code smell. In most cases, you should follow the tell don't ask principle, and the matters of property wouldn't even become an issue in the first place. In this particular case, the options could simply be a matter of render(), getDefault() and validate() ...


5

Having a property in the base class which is used in only one of several subclasses is a common antipattern. This can easily happen when creating the superclass, by either pulling too many things into the superclass when creating it or forgetting to pull the property into the new subclass (depending on how the initial refactoring happened). Better naming ...


0

To start, PyCharm's warning about accessing a "protected" member is naive. If it sees the underscore prefix, it considers it to be "protected" and doesn't consider uses by first party code different than third party code. So that is just something you will need to deal with when developing a package and not wanting to expose the entire ...


5

Error Codes Essentially you need to mark every error with an error code, and that error code needs to have a language specific translation/format string. The backend as such is unaware of language. Any error message generated alongside it is purely for internal consumption by dev and support. Where the error code is translated into a consumer language ...


1

I’ll assume that your set of results is finite and that you perform the prioritization when the set is fully known. First naive approach The prioritization corresponds simply to a mapping function s(o, r)->int which takes as argument an object o of the result set to be prioritized, and the whole result set r and returns a priority score. You may then ...


0

A helper is something that works across the project and does a small thing. Helpers are often not even organized into a class, they merely extend the functionality or capabilities of the language itself. Here's what I consider a very good example of a helper: function linesOf($mls) { return preg_split('/\s*\n\s*/',trim($mls)); } This tiny function can ...


3

The priorities aren't complicated - they're still just numbers. The logic that assigns the priority number is more complicated. Combining multiple factors by adding (or multiplying) them is normal - that way you can have an arbitrary number of classifiers and easily combine them without entangling the logic.


0

The Other Option Dependency via a reasonably defaulted property. class Kitchen { } class Restaurant { private Kitchen _kitchen; public Kitchen Kitchen { get { return _kitchen ?? (_kitchen = new Kitchen(/*reasonable defaults*/); } set { //an validation logic here ...


3

There is no one-size fits all answer here. Context is key. First option: hardcoded private dependency The main issue here is that you're hardcoding (and hiding) the Kitchen dependency of Restaurant. If you want to be able to unit test them separately, then you can't do that as you're now unable to test Restaurant without using Kitchen. In other words, any ...


1

I'd go for dependency injection via constructor and/or parameter passing. Let's debunk the cons: App now has to know how to instantiate Kitchen. There's no problem with that, as long as instantiation of concrete classes happen only in a factory class of factory methods (abstract factories, builders or any creational pattern that is suitable). Somewhere in ...


0

accept is a statically type-safe way to permit an if-ladder based on something's type. if ( thing instanceof Foo ) { Foo foo = ( Foo )thing; BODY1 } else if ( thing instanceof Bar ) { Bar bar = ( Bar )thing; BODY2 } else if ... becomes new ThingVisitor() { void ifThingInstanceOfFoo( Foo foo ) { BODY1 } void ...


0

In your particular example the memento doesn't really serve any purpose (or, at least, the reasons for having it aren't obvious). If you had a more complicated internal state that you didn't want to expose to clients, but you still needed a way for them to temporarily hold on to that state, then Memento helps. Simultaneously, you can have getters and setters ...


0

When the conditions are not that complex you could use the specification pattern to map your conditions to classes, so having a class per primitive condition which you can combine with logical operations (Specification pattern). Maybe have a look at Java predicates/bipredicates. For generating your specification hierarchy from the JSON, you could write a ...


0

There are a number of factors here but we can definitely lay out some principles around these kinds of situations. Let's start with the basic framework. Consider the following visualization: time it takes to load |----------| time it takes to process |----------| The length of the line represents time. The units involved matter in practice but not at ...


1

For many formats you have no choice but parsing the complete file. For example, with JSON adding a single zero byte to the end of a perfectly fine JSON file makes it invalid. And parsing the complete structure is likely easier than having a function that processes line by line. That said, you avoid problems with very large files by passing largish blocks (...


4

You can always measure, but you might be surprised at the results, especially for sequential access. People don't think about optimizations done at lower levels of abstraction. For example, your operating system is caching files to memory: $ free -h total used free shared buff/cache available Mem: 31Gi 4....


1

For 90% of problems most people would encounter, reading the file in its entirety and then completely parsing them is faster, simpler, and easier. This should be your default choice when working with smaller data. You should only use incremental parsing/stream processing when your program may be used in a context where it need to process a very large input, ...


2

in my program in the DAO_USER class, it imports the MDL_USER class just to make the class instances of it A simple approach to solve this is by introducing a "data transfer object" DTO_USER which is created by DAO_USER and passed into MDL_USER for construction. The DTO will only contain the data, no business methods or database related methods. ...


1

This is often a tradeoff between memory usage, and ease of implementation As you already noted by yourself, reading a file entirely first has the drawbacks of requiring more memory and making it more complicated to report progress. However, reading a structured file entirely first may be necessary (or at least simpler) when further processing cannot be ...


1

Is anything I wrote above wrong ? Am I still missing important points in understanding the motifs behind the pattern? No, what you wrote seems pretty reasonable. There are two big things I think might help: You seem to be a bit focused on SOLID, when your second bullet is more key. SOLID itself is meant to help decouple things, and generally lead to better ...


2

CQRS is about two types of interactions, one that mutates state (writes) and one that does not mutate state (reads). It says you shouldn't have everything into one place, since you usually treat writes and reads differently. Writes for example need more constraints when it comes to transactions, which you are forced to have in place also for reads because ...


2

The builder pattern is meant to encapsulate the steps of the creation process: CarBuilder2 is a variant of Joshua Bloch's builder pattern. The main intent is to facilitate the creation of objects that require many parameters in their constructor. CarBuilder1 is a lighter variant of this pattern that is possible if an only if the Car constructor has no side-...


1

Variables consume 64 bits or so, so 8 bytes. Primitives all fit in that, and objects are kept as references to the heap. So, we are talking about 16 bytes or so. I don't think that matters that much. Also, I just want to mention: Don't use getters/setters, they are bad for you! Setters more so than getters, but they're both bad. Object-orientation is about ...


2

The origins Lambdas, std::function and std::bind were introduced in C++11, so this exact technique as such is not older than 2011. In the title you say that it's about configuration via lambdas. But lambda is a specific example: the configuration in your code is in reality based on a std:function. So the exact same technique work with lambdas, with ...


2

Is this code a valid Flyweight implementation? Yes, it is a valid Flyweight implementation, although not where I would have expected to see the Flyweight pattern. But for teaching purposes, that is not a problem. Can I use singleton in a Flyweight factory and still be a valid GoF implementation? Yes. The GoF patterns were never meant to stand alone. On ...


0

There are two cases: One, you have a function that should either be run or not, depending on the situation. If the function itself cannot decide, the caller must decide. Two, you have a function that will have to do work or not, depending on the situation. Usually the function will be able to decide itself. And sometimes it is very hard for the caller to ...


1

Dear StackExchange readers: You have called upon this post to provide an answer to the question. And I want to write this methodanswer to be personalized to you. It's clear that you're a StackExchangeReader – but, that's an abstract type with many sub-types. So, what kind of StackExchangeReader are you? Instead of writing a generic answer based on only the ...


3

Your question is a common one when designing and developing a multi-layer application: how much data should be in the data objects that are returned by the service layer. As you explain in your question, the Campground entity is a complex entity in the sense that it contains other (sub) entities. Then the CampgroundService should not return a complete ...


1

You seem to limit the purpose of the Repository pattern. In small and/or simple projects, you often have a 1-to-1 mapping of repositories and DB tables/entities, and repositories are useful too in this simple way of working. But the point of a repository is to enable you to abstract away how you persist your domain objects. They could be all in RAM, in a ...


2

Enums are generally okay, they serve a meaningful purpose to represent a data type that can only take a limited number of concrete, possible values. The two major problems with enums are: They are often used in situations where polymorphism would make a lot more sense, would be easier to extend and would lead to more stable and easier to maintain code. If ...


1

Or maybe is something wrong with my Command Pattern implementation and Execute(Game game)? The implementation of the command approach isn't wrong, but you should be implementing it on a much more granular scale (favor many small commands over few big commands). Let's say that I have a command that does a lot: modifies some data, plays sound etc. Using ...


3

1. Commands are simply messengers. A command is used to transport a "request to do something" from one part of your code to another. It should do very little besides passing on the request when asked to do so. A "magic spell" by itself is not a command, however "casting a spell" could be, and it might look something like this: ...


4

Your problem seems to be that your command reaches deep into the innards of other objects, so there is minimal encapsulation. Also, some objects seem to be of technical nature (like gameState, soundPlayer, specialEffectsPlayer). For object-orientation to make sense, you'll have to pretend objects are living things, and ask them to do things, instead of "...


Top 50 recent answers are included