instruction
stringlengths
34
36.1k
I have been using queues and PubSub patterns for years but never really came across the terminology "event bus". After some googling I didn't really find a clear distinction between "event bus" and "PubSub". Are they the same, just semantic differences? In the AWS world PubSub seems to imply SNS and event bus seem to i...
I've got a pretty simple web service that I need to add a PUT endpoint for that can handle upserts. This application is primarily a middleware layer to handle logging, caching and instrumentation in front of a third-party API that doesn't do anything useful like that, so it's fairly simple. Once the endpoint receives a...
I find when I am programming and I fix a bug in one area of the codebase, sometimes something slightly related or maybe unrelated breaks, and as a result I usually copy and paste the fix to a temporary file, restore to the last backup and copy and paste the bug fix and the unrelated bug gets resolved. My question is, i...
How do you document the logical data model of a document-oriented database like MongoDB? For relational databases, Entity-Relationship diagrams or UML class diagrams are used. What is the practice for NoSQL document databases? In particular, how do you describe the existence of nested entities versus referenced entitie...
I have a system where properties can be stored, and linked with multiple other entities (each with their own schema). Let's say that Documents can be linked with Users and Assets. What is the best practice format for linking these things together? Here are some example tables that exist (each of the schemas containing ...
I found this practice question online and I am very confused by it Given the use case diagram below, select the CORRECT statement(s): a. A user cannot Rebalance its portfolio before having all the stocks listed. b. The customer service representative interacts with the system whenever a user rebalances the portfolio....
I can't see how having a namespace for each folder makes sense. As near as I can tell, the point of having namespaces is to avoid name conflicts. But, Microsoft, in their namespace naming conventions, says: ❌ DO NOT give the same name to types in namespaces within a single application model. For example, do not add a ...
Context: 128kB RAM, freeRTOS. Considered solutions: Exceptions. Discouraged by both the memory size and the code style guide. Late bool init(...);. Has worked for a decade but has it's problems - can be forgotten or repeated, error status can be ignored. private: bool ok_; which every method checks at it's very beginn...
I want to build a code analysis tool for personal use when programming in kdb/q. In order to do this, I need to be able to parse q code into an AST. I have never written a parser before. ANTLR4 seems to be a very mature, well documented tool so I thought it would be a good choice. I found this grammar for a language wh...
I am working on a system that allows users to track their musical practice. The system allows users to create 'exercises' that store a few pieces of information like name, description and external links. These exercises are created by the user and will belong to the user: the user ID is a property of the exercise (one-...
I'm in the process of redesigning our entire process control system (a daunting task, really!), and want to make the right decisions to how each system in the ecosystem communicates with each other. In particular, I want to control how systems trigger actions in separate systems. Some background: In our current impleme...
The answer to this question is A however I can't wrap my head around how there is a inheritance given the only information is the quote below (ie. a player is not a kind of team). It would make more sense to me not assume a inheritance, and just go with B where there is a simple association. Possibly the answer key is ...
When writing unit tests, I feel that there is a trade-off between code repetition and test logic. Example of my current (likely flawed) approach: To test this function (overly simple function for illustration): from warnings import warn class AmbiguousSignWarning(Warning): pass def product_sign(arg1, arg2): "...
Considering the following state machine diagram, it is CORRECT to state that: Select one or more: a. the Restart event will always be executed in the Halted state. b. After a Halt and Restart event and assuming no previous history is available the re-enter state will be State1 c. Assuming the current state is State2 a...
How do applications like twitter handle notifications at scale. For example @BarackObama has 131.3 million followers. When he tweets, how is that notification sent to all 131.3 million followers. I supposed you could load all 131.3 million followers one page at a time and update some state point to that new tweet, but ...
I'm learning about the Factory Method Desing Pattern and I'm having a hard time to understand exactly what it tries to solve and how. Let's first introduce the example that Wikipedia uses to have a basis for the discussion. So basically the products are MagicRoom and OrdinaryRoom, both derive from Room. And for the cr...
Java used to have green threads, i.e., implemented inside the VM. The description of Python Eventlets says "Eventlet is built around the concept of green threads (i.e. coroutines...).... Green threads cooperatively yield to each other" But as I understand it, Java green threads do not use cooperative multitasking, but ...
Consider the following: Let's say below is the multi-dimensional, and you are given the starting point of [2, 2]. const WORLD = [ ['P', 'P', 'P', 'C', 'P'], ['P', 'M', 'P', 'C', 'P'], ['P', 'M', 'P', 'C', 'P'], <---- That would result the "P" at the 2nd index ['P', 'M', 'P', 'P', 'P'], ...
How to expose an API using the traditonal request-response style while internally it handles it in event driven way (pure or partially event driven), given that if callback style may not be possible due to the circumstance ? In event driven microservices, the microservices react to events, very often it may go through ...
For this question: Considering the following sequence diagram, it is CORRECT to state that: Select one or more: a. Message 4 might never be executed. b. Message 5 is not complete until the Customer receives an message confirming creation of the ShoppingCart. c. Message 7 corresponds to behaviour belonging to the Shopp...
I need to send personalized emails to a filtered set of users (~100,000) on every fortnight. I am using Marketing cloud API for it. The way I am thinking of designing the system is as follows: Scheduled job runs every fortnight and gets all user ids that match the filtering criteria Then it queues the tasks to process...
I am a bit confused about best practices when it comes to where and how to initiate the Flask() or FastAPI() for a data-intensive web API. The vast majority of the code available online is using this structure: app.py from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "...
A few days ago I stumbled upon a silly "problem" that made me reflect about encapsulation and OOP design. I have a class called User that has a method hasMinimumLegalAge() that checks if the user is legal (above 21 years) to perform some operations in the system: class User { ... private static readonly MINIMUM...
How to perform basic CRUD operations (especially batch) by playing with DDD and CQRS? Let's say I have a list of IDs in my controller that need to be removed (soft delete). Currently, I treat this operation like any other command: The controller iterates over the IDs and sends the command to the domain, The aggregate c...
This site mentions such thing: http://software-pattern.org/Reflection. It says that it is possible to replace part of the application behaviour dynamically. Does it mean that we can achieve partial deployments in monolyths? This of course is possible with careful use of microservices nowadays. In principle we can ensur...
I found the following definition of Repository Pattern: Repositories are classes or components that encapsulate the logic required to access data sources. They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the...
We are porting an old monolith application and we are trying to apply the DDD concepts, we started looking for what we think are the Bounding Contexts of the application. We have what we thought would be a bounding context which is what we call Location, it has a country, which has a collection of provinces where each ...
From time to time you need to do technical updates, like: Update versions of your dependencies Update the version of your parent POM, you build tool etc. Leave out those updates that have a firm deadline or directly induced by business needs. I mean the updates that are not urgent, but should be done every couple of ...
In a TDD (Test-Driven Development)-based Java project built by maven, lots of classes needs to be tested with text-based input files such as .csv. At the beginning, I put them into the src/test/resources directory. But along with the increase of the amount of test input .csv files, to know which input files used for wh...
Let's say that I have an articles table that have two columns: title and content, and let's say that this articles table doesn't have any relationship with any other table. Why would this articles table have a primary key? I mean, what problems could I face if the articles table doesn't have a primary key? Having ident...
Background: I'm coding an app, the core idea is simple - I can choose a 'Task' (consists of name, code to perform aka Runnable, progress) through GUI, start it, stop it, start all 'Task's and stop all 'Task's. Each 'Task' has to be dispatched on different thread (long operations). The problem: As mentioned, 'Task' clas...
Currently we have a MicroserviceA which has a database of objects that need to be hydrated with some KI calculated data. For this it queries MicroserviceB via REST in batches and inserts this into its own database. This works but is of course synchronous and sometimes blocking as batches are pretty large. MicroServiceA...
I have inherited a badly architected and organised ASP.NET MVC application, which is an online booking system for healthcare providers. It seems to have been designed with very few object oriented principles used at all, and little abstraction or SoC. So, I am rewriting a lot of the backend code. I have implemented Ent...
I am working in the data department of a middle-sized logistics company who is shifting from an 'old-school' on-premise BI data warehouse to a more 'modern' cloud-based data lake approach. Another piece of context: the data team is separate to the application development team. Probably quite common, but a precision tha...
I started to work on a 16 years old .net framework app that didnt receive any love for a decade and I have some time to "put it up to standards". One of the things that ruffle my feathers is the direct connection between a desktop application on end-user workstation and the database. In the future, I will move business...
Just say I have list APIs, and provide find() to search node. With this design if something went wrong during pre-conditions, client would have no idea about it because no status code provided. bool find_node(list_t* me, int key) { /*check pre-conditions*/ ... ... /*if find return 1, otherwise return 0...
I have the following requirements: a list of queries (rather long list ~ 100K - 1M items or even more) that I need to perform in a certain period of time and the execution time must be predictable. This process should be run daily each query is performed against an external API track progress of the entire process i...
Preface, TL;DR This question is about the implied tradeoff between the speed of development and the quality of code. I am looking for methodologies which can be followed in order to optimize development speed, even at the expense of code-quality and the accumulation of technical debt. I am not looking for ways of commu...
I am new to Python (~ 1 month) and am having a hard time figuring out a clean, fast way to simultaneously append rows and columns to a dataframe automatically. As a representative example, I will initially have data in the form like df = pd.DataFrame({'name': ['Bob', 'Tom'], 'January': [1, 2], }) And will obta...
I am working on a problem with lots of if-then-else calculations. I am trying to compartmentalize the logic to make it more maintainable and less error prone. But, as I try options, I don't see what the best practice should be. By way of example, suppose I am building an order fulfillment system. One thing that must...
What is the best way to program a graph like this: I know I could use Adjacency list or Adjacency matrix: //https://stackoverflow.com/questions/5493474/graph-implementation-c //Clearer's answer struct edge { int nodes[2]; float cost; // add more if you need it }; using graph = std::map<int, std::vector<edge>...
Let's say I have this service abstraction exposed from a library. public interface INavigator { ImmutableList<IPageViewModel> Entries { get; } void NavigateForward(IPageViewModel page); void RemoveEntries(int indices); void NavigateBack(); } The library also exposes a default implementation that takes i...
I've read and tried the Transactional Outbox pattern for communicating between services. It is clear to me what are the benefits of this pattern, as it has two main parts: By using a transaction, we promise that if the resource was saved correctly to the DB, so does the event in the outbox table, so we know an event w...
I often find myself ovewhelmed by questions, I'll explain my self in a practical example detailing how I think about my tasks. I'm often critized on how I approach the problems, and the general consesus in my area is to program first and ship the product, if it fails, it failed, back to square one. By the way I wrote a...
I'm calling a validation function from 2 places in my code, which perform a series of validations on the input I receive. As a result, the function outputs a list of all validations that broke. My problem is that when in one of those places I should ignore one of the validations. In this case, I have 2 approaches: Cal...
I'm facing with problem that in every function (with serves as service for endpoint) I need to check what is value of query parameter (mode). I need to check it on many callables, E.g. def create(self, arg, mode: Optional[Mode]): if mode: if mode == Mode.READ: do_something() elif mode ==...
My restraints are that I have to use: Django and MongoDB I am trying to build a website that will read some JSON input and then parse all the properties and objects in the JSON and display results. This is so that I can check which properties in the JSON are missing and what the actual values are to the properties. In ...
We are creating the backend for a web app using a sort of layered architecture. The service layer is supposed to handle the business logic and passing data to the repositories. This service layer is going to be called from 3-4 projects (.Net Core MVC projects). Many of our services are starting to run into an issue of ...
I'll be using Uncle Bob's terms, so i'll call the use cases "interactors" and the domain entities "entities". As far as I understand, the most specific business rules that are most likely to change should not be in the domain entities, but in the application layer (in the interactors). And the business rules that are l...
I am distributing a proprietary library that includes multiple serializable classes (serializable to a file). I want versioning to the serializable classes, i.e. when serializing I put the version together. Should I have different serialization versions for the classes (e.g., for mylib v1.3, class foo and bar have v1.0...
From my understanding, a QR code is just a static link which get opened up when I scan the code with my phone's camera. Once opened, a customer can keep the browser tab even after he leaves the restaurant. If that's the case, my question is: How can I prevent a naughty customer from refreshing the page and placing an o...
I currently have a monolithic web application. Some API calls need a lot of processing resources and I would like to take that part out of my "backend" monolith and put it in its own service. I use Docker Compose to develop my application. My database is a MongoDB replica set, to simulate what I have in production, whi...
Let's say I have a REST API with resources that look something like this: /users/<id> { "id": <str:user_id>, "firstName": <str:first_name>, "lastName": <str:last_name>, "favoriteColor": <str:color_name>, "lotsOfStuff": {...} } /groups/<id> { "id": <str:group_id>, "name": <str:group_name>, "members": <a...
I have to create a CLI application following TDD. The app should present a menu of items that can be added to an internal structure, and process those items according some rules. My question is if I should add a test for the menu, since it would be a string and it will not be opened to change.
C standard library has strncpy function, declared as: char *strncpy(char *dest, const char *src, size_t n); It's a strange beast, as it fills n bytes of memory pointed to by dest. It does this by first copying from string src as much as it can (either n bytes copied or end of src reached), then if n bytes isn't full y...
This is a "doxygen style/etiquette" question. I have a function which takes, say, an int *buffer. Now, buffer is actually a multi-dimensional array, with different dimensions in each axis, and the coordinates each having some significance. In a more typical doxygen comment, I might write: @param[in] foo The quick brown...
I have an application that has different granularity for each record type. Assume that inventory type A is planned quarterly, so it has 4 values, and inventory type B is planned monthly, so it has 12 values. Assume that monthly is the lowest time horizon, so the table has max of 12 values. From UI perspective, the UI n...
Here's what I'd like to do in the form of working code, since it's difficult for me to explain otherwise: from typing import Callable, Generic, TypeVar from typing_extensions import Self # The type checker (Pylance / mypy) whines about an incorrect # type for the first argument to the method (what should be # `self`...
I have a product listing service, and it will give a list of products for the logged-in users, and the list is paginated, with ten products per page. I implemented this pagination using MySQL LIMIT query. Recently I got a requirement to integrate it with a relevancy service; this service will give product attributes re...
I've been trying to better understand (at least at a high level) why the early versions of HTML were designed the way they were. Most of the decisions make sense; I can deduce (at least at a high level) the probable thought process that lead to the design. But one design decision doesn't make sense to me - whitespace c...
I've got a class that is a facade class (encapsulates complex-ish behaviour for reusability). It has a function called manage (the class is called Manager): function manage() { $entityBuilder = 'Some builder'; $someData = 'Some data'; foreach ($someData as $someDatum) { if (!$entityBuilder->doesNeed...
I have a collection of many millions of objects, each with a unique id, each composed of tens to thousands of values. Values in this case are simply arrays of floats, with dimensions in the tens to a hundred. The same value can be present in different objects, thus duplicate values are many, taking up to 70% of the vol...
After doing some research regarding the actor model, Im still not really sure what an actor actually is.. and what its supposed to "replace". From what I have understood an actor is supposed to be an entity of some sort.. (a thing), and we use the actor model to change state of entities by sending and consuming message...
I'm wondering how a rule tailored for a specific UI is handled in a context of DDD and hexagonal/onion architecture? For example, if you have a screen for an inventory app where you can create product which are displayed as a list. The specifications tell you that newly created item should appear at the top of the list...
I'm struggling on how to name classes for use cases. Because I know that is "bad" to use verbs in classes names(Uncle Bob) but at the same time names of use case classes should explain what they do(Clean Architecture). So if I have an use case "create user" Is it ok to name it " Class CreateUserUseCase" or how should I...
I have this use case (I've simplified it): Each student can apply for one or multiple activities. As of now we only have Swimming activity onboarded on the system, but we expect to have more. Base activity is not abstract because it's the base activity if the student doesn't like any of the activities on the list. I w...
I'm not a frontend dev, but I recall that a few years ago, the this keyword was commonplace in frontend codebases. In recent years, I haven't seen this get used anymore. In the last few frontend codebases I've worked on, I haven't seen it get invoked at all. Did it get obsoleted by recent developments in JavaScript, or...
I have an application which is configured through a web management interface accessed from the same network as the application is running on. I've been asked to make it manageable from the cloud using an HTTPS outbound connection (the customer in mind is doing MITM decryption on their web firewall and wants to sniff th...
To use a dumb example, assume that particular users (labourers) can move boxes around. How would you go about representing that in your system in a semantic way that scales. I'm currently inclined to do the following. class User { // .... lift(box: Box) { if(this.role === UserRoles.Labourer) { box.setPosi...
I have a function to be tested fn doNothing(Student student) { //do some other operations here. but student is unmodified return student; } And my unit test is var student = new Student("Deepak"); assertSame(student, doNothing(student)); But if someone calls a setter on the student in the source code (student...
Here is the conundrum, I have a fairly complex Value Object and I don't want to expose it's internals. It should not be an Entity since there is no need for attaching an identity to it. According to Eric Evans in his DDD Reference book it is Ok to use a Factory in order to create complex Value Objects: Shift the respo...
I have a system landscape consisting of multiple applications. Each application provides REST interfaces to communicate with the outside world. Each application has its own data storage (some kind of database). Each application writes persistent messages for other applications to consume. Each application builds its r...
I have a repository, which is a fork of a public project. The fork contains several additional commits with custom features - nothing fancy. Recently, I have been wondering what would be the best approach of incorporating upstream changes into the fork. Currently the setup looks like the following: The fork has the ma...
I find myself often adding more and more methods to a specific class, is this class heading in an unmaintainable direction? Or is this class fine even if it has 50 or more methods? let's call the class PowerSource182, it handles the details of creating commands that are sent to a "PowerSource182" power supply (an exter...
Let's suppose I have a processing workflow of: Where: The workflow can have many instances running at the same time. A1 -> B1, C1 -> D1 A2 -> B2, C2 -> D2 and so on... Each node is an independent process Result produced by each node can be stored in a buffer database The node D relies on the result of both B and C...
How does antivirus protect itself from malware? Some types of malware will kill the running processes and since antivirus is just another software like any other why they can't just kill the antivirus process? I understand that antivirus will scan the malware before it can kill the antivirus process but still it does n...
In the company I'm working in, we try to make our monolothic application evolve into a microservice architecture. The monolithic app has of course a user table, let's say it's called UserA, and it holds the main user information (name, email, password, ...). The module I'm working on is an application on its own, but ...
I am implementing a CQRS pattern in ASP.NET Core with MediatR, and I am wondering what the general consensus is for handling duplicate validation logic for queries/commands which operate on the same underlying model/entity. For more context, I am looking through Jason Taylor's clean architecture project here as a gener...
I have an application that has use cases relative to where it is used. A local client and server, where all the server data is in a single location and the client queries that server knowing it is all from that single location. However the 2nd use case, the client application may connect to several of these location-b...
Feature branch names already contain the issue key (ticket number). Should commit messages also contain them? Pro: easy to see where a commit belongs to. better for third-party software tracking commits for issues. Contra: developer needs to repeat themselves. Issue key is already in the branch name, and retyping it...
In REST APIs, http error codes 4XX, 5XX are used to convey error messages on the server. When the API itself is dependent on another backend API, is it a good practice to expose error codes or error information from the backend API call? Is there a standard for it? Can we share the the following in the error response w...
Context Let's say I have a navigation service that allows me to navigate to a page. The Navigate method is async because an animation (about 250ms) is involved. public interface INavigator { Task<IViewModel> Navigate(Type viewModelType); } Problematic use-case: Concurrent calls Now imagine that have a botto...
So, this is probably a repeated question, but I couldn't find a question which solve my questions. At the beginning of the year, I started as a Junior Java Developer in a company that is in the market for 20+ years, so I deal with a lot of legacy code. So far, so good, but something in architecture is bothering me. We ...
I'm writing a virtual CPU, and I decided to create a class for each command, to make it easier to replace/add/remove commands without changing too much. The original idea was that ICommand would be given an ICPUState to operate on, but then I released I'll have more than one type of virtual CPU. Most of the VCPUs will ...
I wanted to learn Kotlin but after reading online most experts seem to agree that learning Java first would be a first step in the roadmap of learning Kotlin. Their argument based on the fact that Kotlin developers may use Java Library. However, I don't understand what is the point of learning Java if I'm at the end on...
By "Automatic Reference Counting", I am refering to the specific feature of the Clang compiler. By "Garbage Collection", I am refering to Tracing Garbage Collection, not to "Garbage Collection" in general. The main difference as I understand is that ARC gives you control over making optimizations if needed, while in a ...
In my domain there's a part where I have a root entity, with some fields, and then some other entity inside that aggregate, like this: class AggregateRootEntity { ... some fields ... Entity listOfInstancesOfThatEntity = []; } Given that the aggregate can have, for instance, 200 instances of Entity in that list, ...
In front-end projects(made in frameworks like Angular or React), when we correctly encapsulate complex functionalities, the components that really have some relation to the business logic normally became simple as a Form with default validations provided by the framework(or lib). So, does unit test as "testing if wrong...
For instance, if we have a complex library with many functionalities, how can we make this lib a plugin such that it can be replaced with another lib more easily. The answer obviously is the dependency inversion principle, but how would this be done. If we try to create interfaces that have the same properties and meth...
I am trying to figure out the best practice for manual testing where there are multiple valid routes to reach a step in the test. For example, a test for changing a password could be:- Test 1 User invited to the system via email User creates login User changes password Test 2 User navigates to website and creates lo...
In the beginning, I would like to state that this is not meant to be a discussion. But I would like to receive only suggestions for possible solutions or, at least, a comment on my proposed solution: I'm in my first steps to create a small tool that should help evaluate data from my master thesis experiment. In this ex...
I am working on a project that generates an API with the possibility of doing CRUD operations based on a high-level description of the resources that the user would like to have in an application. In the process of generating the code, multiple steps have to be taken (for some context, I am generating Python code from ...
I came upon a situation where multiple classes manifest duplicated logic. They all delegate to a worker object, but when interrupted they have to stop the worker. class A { Worker w; public void OnSleep() { w.Stop(); } } class B { Worker e; public void OnSleep() { w.Stop(); } } class C { … } The issu...
I have an application in which the user can describe an analysis job via a yaml like analysis: learner: name: LinearRegression args: solver: liblinear and then it is parsed to instantiate an sklearn LinearRegression model. Basically I want a whitelisted eval where I am "instantiating" user-input strin...
I am designing a multitenant SaaS platform where the database will hold information for different clients. The application consists of an Angular frontend and a REST API Backend. Some of the clients want to assure the confidentiality of their data, so even though we accessed the database tables as admins we couldn't re...
In my formal employment in software engineering/development, I've noticed a pattern. When I understand the domain reasonably well for what I am developing for, I can be much more effective by at least one order of magnitude. For example, I recently worked on some SQL database systems and simply having used databases wh...
TL; DR Where/When to check data format in MVVM + Repository Pattern is the best practice? Any suggestion or theory? The Scene Our team is working on an Android Project. We have a MVVM+repo structure: View > View Model > Repository > Model In some feature, we need to pass data from View all way through the struct, such...
In my domain model I've got two principal entities: User and Event, both which I've decided to make aggregate roots. Users and Events have a one-to-many relationship wherein Users can create several events. However, an Event does not necessarily have a corresponding User (i.e. created by the admin) and has its own set ...
I am trying to store user preference for notifications. One way to do is store types of notification in separate collection and store UUID of that notification type in user table. e.g. notification-type { UUID: 'a81ef539-290b-4f28-b364-548970307a66' name: 'newuser', title: 'new user joined your project.' } and t...
First a bit of context: My company develops a software and middlewares to make our software interacts with other software. One of a client has a proprietary software we should interact with, he gave us the .h/hpp and the .def file which are needed for the interaction. He has some dlls that are used when our software is...