instruction
stringlengths
34
36.1k
I'm very new to DI, and must admit, am having a hard time understanding to what extent it should be used in an application. Even in a basic project, you can have hundreds of classes that have constructors which take in one or more dependencies. Should all these types be registered by your DI container? or only the root...
My code looks roughly like 40 def send_pubkey( s: socket ) -> None: 41 '''Transmit own public key unencrypted.''' 42 _, pub = crypto.read_keypair() 43 s.sendall(pub.save_pkcs1()) This...
This seems to be a commonly encountered and brought up code smell, and is a common feature in multiple coding design books which I wasn't fully able to understand. Say I have a function def train_model(model,useSGD,initWithZeros): if initWithZeros: model.initWeights(method='zeros') else: mo...
I'm working on an AspNetCore application, with a requirement to raise and handle certain events asynchronously using an external event queue. I'll use AWS services as examples here because that's what I'm using, but this would apply to any queue infrastructure. Here is my design for connecting my external event queue. ...
According to the standard ISO/IEC 25010:2011, the "quality of a system is the degree to which the system satisfies the stated and implied needs of its various stakeholders". The standard defines 8 categories of quality characteristics: Functional Suitability Performance efficiency Compatibility Usability Reliability S...
While I was learning functional programming I have encounterd two for me very similar terms: immutability and persistence. Also I have read simular questions from stackoverflow, but I am still confused. Wikipedia says: In object-oriented and functional programming, an immutable object (unchangeable object) is an objec...
I'm reading the book The Secret Life of Programs by Jonathan E. Steinhart. In it, he mentions in passing: many consider the handling of whitespace in Ruby to be a replay of of a mistake in the original C language that was fixed long ago What mistake is that?
I've seen a variety of discussions talking primarily about the question of the difference or not between the Repository and Data Mapper persistence system design patterns; but I think I have a decent understanding now - Data Mapper, as the name describes, simply maps objects in/out of a database, but Repository can inc...
I am contemplating the use of the design pattern API Gateway, specifically the Backends for Frontends derivative. We have a number of 3rd party software packages that expose an API. Over the course of the past few years I have been creating custom APIs as wrappers for the functionality of these 3rd party APIs. These fu...
Consider a class that follows the obfuscated function call anti-pattern. I've also seen these called "stupid classes". The definition of such a class is that it only has one public method and one public constructor. As the name suggests, such classes should "just be a function". For illustration purposes, here is a suc...
I am not sure if I have been using the term wrongly (and including it in my CV), so some inputs from the community will be appreciated. I am not a DevOps, but a noob machine learning engineer. So I basically developed certain pipelines to perform batch processing jobs to automate stuffs like Read raw data from a cloud...
It's rather common knowledge that aggregate root provides an interface for every state change within that aggregate. For instance, aggregate root checks some business rules before some dependent entity is modified. Now, according to Microsoft guideline for API design, URI /customers/1/orders/99/products should be split...
I have an angular SPA that runs in an office add-in (word) that I need to authenticate against Azure AD using Oauth2, consume resources from multiple apis and make graph calls. I have been successful doing this in a standard web app but not with the introduction of office add-ins and using the office dialog api. Curren...
The CppCoreGuidelines contain the following: T.65: Use tag dispatch to provide alternative implementations of a function [...] Example struct pod_tag {}; struct non_pod_tag {}; template<class T> struct copy_trait { using tag = non_pod_tag; }; template<> struct copy_trait<int> { using tag = pod_tag; }; template<clas...
A common scenario I have is this: I download a new codebase. In order to have me understand the code, I need to litter it with my own comments about what each section of code does. It seems inappropriate to then push these messy comments back upstream. So now I have a problem: my own codebase has a bunch of my own note...
In my work, which is a UK university, we currently have no specific way of recording and tracking business logic and rules as they arise from stakeholders for our in-house software projects. We use Agile Scrum and put things into the usual product backlog items, etc. but the logic is often clouded in multiple different...
Context I'm designing the software architecture of a safety critical software written in C, under DO-178C (DAL A) and with a Code Standard based on MISRA-C 2012, but no fully compliant. It is the first time I do this, and I don't want to fall in design issues that could be avoidable in advance. Program description: The...
I want to achieve user authentication and keep state with cookies between client and server. Webapp runs with domain1, backend runs on domain2. I am having lots of trouble letting session cookies be exchanged back and forth between the web app (the browser) and the backend, because of the different domains. I have to ...
As a fellow SW developer in EU, I hope that you know that there is a proposal for a new law, called Cyber Resilience Act, that will, if approved, will affect all digital products on the EU market. In the proposal there is two annexes, I and II, that contains requirements on the product and the development of the produc...
In C#, it's possible to create a strictly sealed set of classes that inherit from a base that cannot be further extended like so: public abstract record MyBase { public sealed record A: MyBase; public sealed record B: MyBase; public sealed record C: MyBase; private MyBase() { } // My base props } ...
I hope this isn't too off-topic/opinion-based, I'm new here. I want to pass three elements of the same type into a function. The three elements are unique cards of a deck of cards, so they're not intrinsically connected (unlike, say, the coordinates of a point). The array or tuple will only exist for the sake of compar...
I'm not sure if I misunderstood these codes. First Alice generate her keypair and sent the public key to Bob. Then Bob uses the parameter in the public key to generate his keypair and sent the public key back to Alice. So Alice can generate a shared secret based on Bob's public key and vise versa. Here's the question, ...
I am fond of writing Streamlit applications (when a front-end is needed) and fastAPI backends when I just need a REST API. I've seen many blog posts where these two are combined - with the Streamlit app basically just querying fastAPI endpoints as needed. But I'm unclear on the benefits? If I am writing a function: def...
While researching the topic of Coupling, I still have a little misunderstanding about what counts as less / more Coupling. I will take as an example two options for setting delegates in Unreal Engine C++. Example One: We wait for an entrypoint and get the owner of our component. Hoping that this owner is not nullptr, w...
I'm writing a script for a webapp, which I can only copy my code manually to its platform and not push it from my machine. In the code there are parts that use its API and parts that don't. I cannot split it into multiple modules as well. Everything should be on one file. To be able to debug it on local, I need to chan...
I have a function that looks roughly like this: async function getValue(connection: Connection): Promise<number> { const value = await connection.getValue(); return value < 0 ? value : 0; } The important thing to note about this is that Connection is some huge megaclass and mocking it would take a significant ...
According to Why define a Java object using interface (e.g. Map) rather than implementation (HashMap), when creating objects, I should declare the most abstract type, eg : Map hashMap=new HashMap(). However, I don't think it is a good idea, because it seems suffers from the same problem as primitive obsession. Let's co...
In this toy example some_function is... some function that takes a dict as an input and modifies it in place somehow. def some_function(dct: dict): """Do something to the items in the dictionary. Args: dct: A dict that ... some description. """ I happen to know the caller of this function will oft...
Currently, I am developing a software in C# (.NET 6) that tests devices after production. Therefore, it runs specific tests, e.g., voltage measurements, using the connected hardware. If the voltages are not in the expected range, the tested device will fail. I implemented the voltage measurements using a generic IVoltM...
I'm writing this library in which the user can provide custom code defining the algorithm used for finding an optimal solution. In the papers that I have read, the targeted user thinks in terms of finding the hyperplane that maximizes a measure of impurity. Since I want the user to articulate its code in a way that is ...
I am responsible for implementing search functionality for our web application; I take search text from a user and come up with a list of products, score them, and return them to display to the user. The search itself works fine, however, the team wants to be able to guide the user's search by way of presenting filters...
I am building a website, where the main data source is Snowflake, a cloud data warehouse. This cannot be changed, but we can add other technologies. There is a lot of data in Snowflake, and the calculations for each web page are quite complicated. We believe that computing everything in real-time would not be acceptabl...
I am thinking about how to build a language VM. I have been able to get some of the basic constructs right, including jumps to functions within the chunk of bytecode that is currently loaded. But now I am thinking about how to handle (dynamic) calls to functions that are in other chunks of bytecode that have not yet be...
Presume I have a function that does some precise calculation on a large amount of data, call it calculateResult(data). This function gets very slow with increasing size of input. Luckily, I only need the approximate result in some cases, so I write a second function that does the same calculation much faster but with a...
I have the following interfaces to allow me to generate "drawing" of some product. public interface IProductDrawer { public string Execute(ProductScope scope, ProductConfig config); } public interface IProductDrawer<in TConfig> : IProductDrawer where TConfig : ProductConfig { public string Execute(ProductScope...
Please help with a diagram in which there are sequential requests. The logic is the following: Service 1 sends a PUT Trigger an export request to Service 2 If the response is 200 OK, then after 10 seconds sends a GET Retrieve an export request until the status is COMPLETED or ERROR I don't show the 400 response. If the...
I was programming today and encountered something that just feels like I'm doing something wrong (maybe?). I've encountered this situation before, but I wanted to reach out and ask if there's a better way to handle this. I have a situation where I realized my function direct_data could save a lot of execution time by e...
In software design and security, why would it not be a good idea for users to send you their passwords and it would be a better idea to delegate: use public-key auth or logging in with one of these: OpenID connect, "sign in with Google" or "Facebook", etc. I am curious to understand more about these topics. I recently...
I have the existing code provided below: if (!$existing_records && !$has_required_field) { return 'Skip Update, no records found'; } elseif (!$existing_records && $has_required_field) { syslog(LOG_ERR, "some field is required but no regulatory records found. id=$id"); return 'Error some field is required bu...
According to Why is Global State so Evil?, I believe we should avoid global state, so suppose I have an App that count user clicks in all pages like it: public class GlobalState{ public int clickCount=0; } public class Page1{ public void onButtonPressed(){ GlobalState.clickCount++; } } public class ...
I am not a native english speaker so I have the following question related to naming I have a class that has generic filter method of type: filter(Predicate predicate) In the same class I have some more concrete filter methods of type: filter(EventName eventName) or filter(Datafield datafield) Is it acceptable to use ...
I went through various blogs but nowhere I can find the reason of having virtual constructors in C++. Why is virtual constructor needed and lets say if we go through the wrong way of creating virtual constructor how would our code look like and what would be the problem with it? And how does the factory method helps us...
I've been learning about threads and processes and I understand that threads allow you to write concurrent code: where executing threads switch very quickly from one to another, giving the impression that multiple programs are running in parallel (but not truly in parallel, for which we would really need parallelism us...
I need to perform the following task: for a user user@domain.com, store a blob of data into their dedicated data store. DataStoreService is what actually stores the blob of data in the user's store, however it needs a StoreClientFactory which owns the logic for picking which store belongs to the given user. StoreClien...
I'm required to write the Low-Level Requirements of a Software Component which shall perform signal processing over arrays of 200k elements of integers/floats which lives in the main memory of the program. The program is single thread. The software shall be certified in the context of DO 178-C (DAL-A). The signal proce...
Say I have a module that can to do two things: It can check if condition A is met and it can create an artefact B. The caveat here is that if condition A is not met, artifact B should not be created. If I am calling this module from the outside, should this check be performed by the caller or by module? Version 1: // O...
I have Service A that publishes an event to RabbitMQ. I have two instances of Service B that will use the event to write to its database. I have two instances of Service C that will send the event data back to a client via websockets. Only one instance of Service B should handle the event so data isn't written to the d...
I have a system design question that I'm looking for some guidance on. I have two different systems that need to have a basic level of communication. This is abstracted via message queues. For example, System A is responsible for user account registration. A user access System B and enters the user registration flow. A...
I am currently learning system design. I wonder if I should put load balancer in front of multiple instances of API gateway or put an API gateway in front of single load balancer. which one is valid design?
... or technology stack for compliant web applications. GDPR among other includes cookies usage defining four cookie types: strictly necessary cookies , preferences cookies, statistics cookies, marketing cookies. I am researching for a solution to develop a stateful web application without using cookies to avoid gettin...
I've recently just noticed that IDictionary does not implement IReadOnlyDictionary. I'm using two third-party libraries, one of which provides a ToDictionary() method which returns an IDictionary containing the contents, and another which consumes an IReadOnlyDictionary. In order to make this work, I've had to write th...
According to Origin of "a method should return a value or have side-effects, but not both", a method should either return a value or have side-effect, but not both. However, I often see some situations that I need both the result of modify objects and the process of modifying it, for example, a function that modify an ...
From the article JavaScript 2D Array – Two Dimensional Arrays in JS, I see one way to store data is to put all properties of each element into one array: let dataRepresentation1 = [ ['John Doe', 20, 60, 'A'], ['Jane Doe', 10, 52, 'B'], ['Petr Chess', 5, 24, 'F'], ['Ling Jess', 28, 43, 'A'], ['Ben Li...
A module app.js includes another module service.js. The service.js module/file contains some functions but also does some module scoped initialisations(registry variable). // service.js const registry = database.connect() function getItems(){ const items = registry.getItems(); return items; } function doSomethingE...
I'm working on a fairly large but standard dotnet core API. Here's a simplified sample: // Simplified example of a controller public class VehiclesController : ControllerBase { private readonly IVehicleService _vehicleService; public VehiclesController(IVehicleService vehicleService) { _vehicleServ...
I'm not sure if this is the right stack exchange site for this, or maybe this is more of a reddit question, but don't rake me over the coals for asking. Happy to go post on another corner of the internet if need be. I'm wondering what would be the best approach to identifying duplicate transactions within an accounting...
I am curious about the utility of something like monads in the C# world. My experience with these kinds of things is mainly through Rust but I'm a dotnet dev for work I was thinking about the difference between Rust's result type and exception handling https://doc.rust-lang.org/std/result/ The scenario I'm thinking thr...
I'm relatively new to structuring code in a composition style, and I have a situation where a component is also a component of a sibling component. I'm trying to figure out if there are likely to be unexpected issues with this. Explaining the relation in more detail, I have a composite C that has components A and B. Ho...
Assume that we are doing aggregate design for a ride hailing application and we have created the following aggregates: DriverAvailability aggregate, which has a value object containing the status (available/unavailable) and DriverLocation aggregate which has a value object which contains the latitude and the longitude...
Context: This is from a practice exam, and we aren't sure what the proper answer was Question: What is a possible order of actions for this activity diagram? Options: A->B->D or A->B->C->D A->B->C->D or A->B->C->D->E A->B->C->D->E or C->A->B->E A->B->C->D or C->A->B->E Diagram is illegal The first bar is called...
I am the maintainer of a Python library that uses semantic versioning. Skip the next paragraph if you are familiar with what it means. The rough and dirty explanation of semantic versioning is as follows. The library developer uses a version number of the form MAJOR.MINOR.PATCH where the first two components are increm...
We're trying to update our style guide (using google's guide as a starting point) and I'm currently in the middle of a debate with my colleagues about column limits. I believe we're all in agreement that they're generally a good thing, however I'm upset that a string (or simple string template) assignment would necessa...
Most weakly typed languages do not have a concept of a pointer. Instead, most of them use references. However, is it possible to introduce pointers to such a language. From a naive point of view, to have pointers, you almost certainly need to have a concept of a type system that can be used to declare things (which mea...
I want my projects to be SemVer compliant. I follow a trunk-based development approach. I also want to keep things as simple as possible. I assume that each commit on main (default branch) is a possible release candidate. So my CI/CD pipeline looks at the M.m.p version number in the codebase, and build & release artefa...
Over and over again we're told, "globals are bad" and with good reason. However, I'm working with a logger that needs to be accessible everywhere in the program. Why shouldn't I create a global logging object? The alternative seems to be to pass the logger object into every object I instantiate and that seems very repe...
I have a bucket with several csv files at differing paths. The problem is that I want to update these csv files transactionally. The s3 bucket should represent the "latest" consistent set of data, and if any update to one of the s3 paths fails, then no update should happen. My s3 bucket for example would look like this...
I am starting to work on Core Data applications with SwiftUI. I have a view that looks like this: struct ContentView: View { @FetchRequest(sortDescriptors: []) private var todoItems: FetchedResults<TodoItem> enter code here var body: some View { List(todoItems) { todoItem in Text(todoI...
In MDN article on WeakSets, an example is given for using weak sets to avoid infinite recursion on circular references: // Execute a callback on everything stored inside an object function execRecursively(fn, subject, _refs = new WeakSet()) { // Avoid infinite recursion if (_refs.has(subject)) { return; } /...
Consider Mastodon as an example - basically open source Twitter. Tweets can be up to 500 characters long. Of course, since it's open source, you can modify it to allow longer tweets. Unmodified Mastodon can connect to other copies of Mastodon, including modified ones. Mastodon will accept long tweets from other servers...
We see a lot of 3D configurator web applications on the web and even other type of configurators in embedded systems, such as LED Totem displays. From real time car configurators which every major car brand has on their website, to retail and marketing content configurators. I always wondered, especially watching the r...
I am trying to build a travian-like web browser game (static strategy game). I am currently working on my tables and data model. I don't have much experience with relational databases and I am wondering if I am not doing to much normalization. So in this game, everything is about resources, there are 4 different types ...
I want to build an app with a SPA (Angular) frontend and a REST API (Spring Boot) backend. I want a modern account system for this app: users log in through OpenID Connect, using either a social login like Facebook or Google or a custom account with us (achieved through the use of an OAuth authorization server like Key...
I just happened to stumble across the following question on stack overflow: In gatomic.c of glib there are several function declarations that look like this: gboolean (g_atomic_int_compare_and_exchange_full) (gint *atomic, gint oldval, ...
What is the best way to store a recursive data structure in a program? (in C++) I'm reading data from file, and want to keep it in memory while I validate the data and the user can manipulate it. It will then be written back to file. I have a many values I wish to store, and each value can be a string, List (== vector,...
I recently started trying to implement a monte carlo tree search based algorithm for playing cops and robber. The game is based on the cops and robber game and is played on an arbitrary graph (not multigraph). There are n cops and one robber. The cops try to catch the robber by moving all at once per round on the graph...
In a test, asserting if a simple method throws an exception under a certain circumstance, is such a test considered a unit or integration test when the exception object thrown is from the standard library of the programming language?
I am working with a library that is somewhat poorly written. In order to function, it requires several global variables to be declared and sometimes even maintained by my own code. I really don't like having to put a whole list of global variables at the start of my main file, and even less also having to extern the...
I have a service (S1) that is deployed on kubernetes having multiple replicas (pods). S1 requires some data from database (Cosmos Cassandra Api) for calculation. This data is constantly updated by another service (S2). There is a scheduler(@Scheduled) written in S1 codebase to fetch data from DB and keep it in memory (...
Background I have an authentication microservice that handles the user authentication and returns 2 JWT cookies (access_token and refresh_token). I want to incorporate an API gateway that does the JWS validation on only the access token that is sent in the cookies. The concerns Most API gateways do not support cookie v...
My application follows Clean Architecture wherein the Application Layer wraps the Domain Layer. I try to adhere to DDD more-so as a "guiding light" than a strict rulebook. Within the Domain Layer, Repository contracts are defined as interfaces. Those are implemented in the Infrastructure layer with various technologies...
I apologize in advance for a long-read question, but i'm hardly stuck here and don`t how to ask for help using fewer words. I need to implement a middleware service which should be placed between two big systems: First - Asterisk virtual telephony station; Second - our company enterprise core. Enterprise core consist f...
I have a CouponReservationService in an e-commerce project. It is called when a coupon is reserved to be applied to a basket. It checks that whether the coupons are already reserved. If they are reserved then throws an exception to prevent re-usage. If not then reserves them and allows to be applied. Currently the rese...
I have been researching and trying to find the oldest possible implementation of the wildcards and how the asterisk * became the (almost) global standard when it come to represent a wildcard character. There's many languages that use it that it's actually hard to find which used it first. The Oldest possible language t...
This is more of a philosophical question. I have recently started working on a new team and I see here a pressure on developers to fix bugs in their own code. Whenever a bug is found in a feature, the person who coded the feature is assigned that bug. As a result, I see a lot of anti-patterns in the code and faulty ass...
Bridge design pattern is something which is very confusing and GOF does not do justice with beginners in the definition. I was asked in my current organisation to add one more dimension to our class and use Bridge pattern for it, knowing nothing about it I went through some blogs and have implemented the same for our c...
I am working with a system that connects a number of voltage reference devices to a measurement device, it does this by "setting a relay". When defining the name of this function I have a feeling that SetRelay conveys the idea of setting some property of the software object rather than setting the physical relay to the...
I had an idea for a piece of software using .NET C# as technology. Basically, in my idea Im thinking of using reflection to do the mapping between a class to another class using interactivity with a user. About the interactivity right now Im just using console writeline and readline, but in future it can also be someth...
There are tools like dependabot or greenkeeper for npm and others for other languages. Now at first glance they improve security by keeping open source dependencies up-to-date. But I am wondering, do the benefits outweigh the risk of a hostile party taking over or sneaking in a seemingly harmless commit, which will the...
I recently finished a large merge with many complex conflicts that needed to be resolved. The branches had been separate from one another for several months while different teams contributed to each branch. Ideally the two branches would have been kept in sync with one another, but that did not happen in this case fo...
My problem is the following: inside a method I'm creating an object like this: MyObject* myObject = [MyObject new]; Then I want it to perform an asynchronous task like this: [myObject doSomethingAsyncWithCompletion:^{ //do something else upon completion }]; This brings me to a dilemma of how to retain this objec...
I'm currently scratching my and my colleagues head about whether and how we could test SyncService::syncFoo in any meaningful way that does not involve basically recreating the whole call tree as mocks. Edit: It is not a microservice its a Service Class within one project - there was some confusion in the answers/comme...
What would the appropriate design pattern to avoid deadlock when several functions use the same mutex ? It is quite easy to forget what method uses the lock and so it happens that you call a function that do a mutex.Lock() inside a function that already locked the mutex --> deadlock. For example in the following code, ...
I have two microservices, USERS and PRODUCTS, the second one creates objects referred to first one so it needs first to check that exists First I though in a redis cache, but then I realize that for other cases I'll need to communicate with kafka, for example for payment microservices where requires fire and forget. Th...
I was looking at an SQL query recently and found what I think is likely a bug. It was related to case statements on inequalities. I was trying to replace it with a min/max type alternate and when testing, I was getting different results. Here's a simplfied example of the SQL that I was trying to simplify: CASE A > B...
Asume these two bounded contexts: Book Management: manages the creation of books and its attributes: Book(id, name, author, summary, ISBN, length, cover photo) Book Order: creates orders related to books. Order(orderId, List<Book>, deliveryDate, status, etc.) The Book Order context has an independent web applicatio...
Lets say that a enum exists: public enum SomeEnum { FirstValue, SecondValue } It's use is spread through the code and all sort of wonderful logic hangs off it. If we now add another entry (ThirdValue?), we'd have to find all the places in the code that make use of it and update. Either that or run the risk of ...
According to Wikipedia, "an operation, function or expression is said to have a side effect if it modifies some state variable value(s) outside its local environment, which is to say if it has any observable effect other than its primary effect of returning a value to the invoker of the operation." This is the most use...
So I have this problem where a specific ValuesA enum value is to be mapped to a respective ValuesB enum value, The trick is there can be multiple ValuesA mapping to a single ValuesB enum. So for the following example: I have randomly chosen a max range of 3 ValuesA enum values mapping to a single ValuesB enum value. E...
I'm building an HTTP server in C using epoll and pthread. The idea is to have an event loop in the main thread monitoring file descriptor and a thread pool to handle computationally-expensive operations. What I'm struggling is that what type of operation should be done by an event loop and by a thread pool. Here is wha...
How to apply clean architecture concepts in a software that depends on External APIs. Example: A business that offers some kind of subscription to its users. Its convinient to store some subscription data and how its related with the users inside our database. The Subscription use case is responsible to receive data fr...