instruction
stringlengths
34
36.1k
Let's take at random a well-written piece of Rust code: let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { label: Some("Shader"), flags: wgpu::ShaderFlags::all(), source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()), }); I'm nowhere near being a Rust expert, but what f...
There are metrics for class and module cohesion and coupling, but I didn't find anything yet for a single function. Some functions are obviously doing too much, like doThisAndThat (should be doThat(doThis())) or getDataForThis (should be convertForThis(getData())), and it would be very nice if there were an automatic w...
I'm working on a data science project that involves data ingestion, cleaning and various aggregations and functions of timeseries equipment data primarily using Pandas. I began the project just writing various functions from the ground up, but am now at a point where I need to make critical decisions about the codebase...
I have a RESTful API service that has three layers: Application/Domain, Infrastructure, and Presentation. Application/Domain contain my interfaces and models. I currently have three different types of models: DTO - These are the models my controllers return to the client as well as the models that are passed around al...
A problem I'm currently solving is that at a glance I want to see the status of various services, including both frontends and backends, across dev, test and prod environments. That is, I want to see: Is the service running? What version of the service is running? ie. A semvar Latest commit hash What features is th...
i like to think out a function using comments before writing it. I'd like to keep the information in the code as comments somewhere but i don't know where it should be kept. At the moment i keep it at the top of the functions code like this: int Lattice::Width() const { /* * Description 1 * ------------- ...
I am designing an API whereby some other system can supply an image in their POST. As such this is an API for integration purposes, with no front-end. Postman is used for testing the API. Below is the DTO for the expected POST body written in C# public class VideoEventCreateDto { public double Confidenc...
When I buy a house or a car, the product is already completely ready. It's very seldom that an error will be noticed later by the customer. In software engineering, on the other hand, errors (bugs) are normal and occur frequently. Even in production bugs can be found, so that software receives updates regularly. Suppos...
I am trying to implement RBAC to a system but I endup creating an ACL instead due to my low understanding of this archtecture. What I already have implemented: Created User model. Created Groups with different permissions from User model. Designated each user to each group based on their permissions. For instance, th...
Abstract The case: Application contains a lot of views with a list of data. Data views (lists of records) have pagination, filtering and sorting options. The user must be able to select a "sorting property" to sort the shown data by a specific property. The user-interface contains a selection control (ComboBox) the use...
I'm working on a 'slideshow'-type presentation (e.g. using LO Impress) which involves me showing people different alternatives for writing some pieces of software code. We're not talking about large pieces: Some of the changes I suggest are alternative formulations of individual lines; others involve transforming block...
I have the following classes, which have quite similar method implementations. Only the classes' method inputs and outputs seem to be of different types. When I put it like this, it sounds like a case for inheritance, however, the fact that the inputs and outputs are different and are related to two lambdas, make me wo...
I have a task that I need to make sure it only runs once in my dockerized environment (managed by k8s), running the post-upgrade script is one example. Because each dockerized app can run the task and the docker containers may restart, I believe I need to store a state that indicating whether the task has run or not in...
Consider this code, rather than hardcoding the hour when we execute a certain command I query the CQS engine and asks when it will be executed. Though now we have a high coupling to another command. You consider this ok? public class CancelInvoiceCommandHandler : ICommandHandler<CancelInvoiceCommand> { private read...
Let say, user A has the name of 'James' and trying to change it to something else like 'John'. It might be stupid to ask this question but how do you apply this change? I retrieve the new data from database and send back to Frontend to rewrite the data. However, it seems like it could increase network traffics. I was t...
A client requested that we implement the following authentication/authorisation flow: User authenticates using OIDC via a IAM (Salesforce in this case). If user is an external user, then a flag is appended to the JWT payload which indicates we need to query Active Directory for the users' group associations/permission...
I have a problem with proper API design. So there's an app where users can track their sport Activities. User can later access and view them. It can be done by making GET /api/activities/{id} request, where id is an id of the activity. Internally I am searching db by user id and activity id, so that another user cannot...
I like the concept of Extreme Programming (as I understand it), that there should be many smaller functions with descriptive names, instead of fewer, longer ones, even if those functions are only called from one piece of code. I do this all the time, but it does tend to litter the class definition quite a lot. I alread...
I am interacting with a 3rd party program that will request 2 user inputs to start running a process. I know what they are going to be and want to preempt them, so that I don't need to enter them every single time. predict_user_input_1 = 'variable1...' predict_user_input_2 = 'variable2...' 3rdParty.start() #this...
I'm following Uncle Bob's clean architecture for my application. However, I wish my application to be extensible via plugins. More specifically, I want the plugins to be able to add new entities and use cases. How does one go about adding support for plugins in an application that follows the clean architecture?
In my spare time, I like to develop various small libraries and CLI utilities that solve a real problem I have, but are also likely useful to other people with the same use case. When I say small, I mean that the LOC count is modest and the scope is limited - but the program itself is not trivial does solve a real prob...
I am developing a middleware application where the application workflow is: handles rest requests performs some business logic calls another rest service I would like to use DDD to model the business logic as it is very expressive. But as the application mainly serves as a gateway or facade, the aggregate root ends u...
Consider this hypothetical scenario. I have a user form that has a collection of controls that are made available/unavailable based on certain criteria. One important criterion is product type. On selecting a product type, certain features on the form are made available. These features are also dependent on other crite...
I am getting confused when objects interact using OOP. Here i'm trying to model the interaction between a vending machine and a coin. The coin is inserted into the vending machine. The interaction is represented by the functions InsertCoin() and Insert(). The resulting main() is very confusing, how are we to know which...
Currently, our architecture uses an "API-first" approach in building our product. This product is divided across multiple teams handling different microservices. The above image succinctly shows our approach. There are JSON Schema files that are shared between all microservices. These JSON schema files are used to aut...
I am preparing the software architecture for my client project based on APIs REST The idea is that any data exchange between my client and his partner will be via API REST call The specification is that my client have a large data store ( SQL database) which must me updated by data got from the partner My question is ...
I am making a web system using Asp.Net Core with individual user accounts (Identity), and I was thinking about how I should store the users' personal information in the database. The system will have different kinds of users. Some are Members, some AdminUsers and some are ExternalResourcePersons (people). Each of the d...
Lets imagine some vendor code that we want to extend on our project level protected function getDefaultFormClasses() { return [ new FormClassA(), new FormClassB(), new FormClassC(), ... new FormClassZ() ] } On project level we want exactly what this function will return ...
Say I have a set of objects from an "old system" that I want to convert to a newer set of corresponding classes. Each specific class has its own way of being converted. So I have this: interface OldInterface {} class OldA implements OldInterface {} class OldB implements OldInterface {} interface NewInterface {} class ...
I am looking for a method to measure the time difference between: the time it takes to load and completely reach TTI for example.com/page-B given that example.com/page-A is loaded. the time it takes to fetch the "main content" of example.com/page-B and replace it in example.com/page-A via Javascript and reach "TTI st...
Let's say I have Service A that publishes Message 1 to be processed by Consumer A The same service A that publishes Message 2 to be processed by Consumer B I need to make sure that consumer B processes Message 2 only after Message 1 has been fully processed. What is the common or best approach to this kind of situati...
I have tried to look this up online a lot but have found no concrete explanation that answers my question hence hoping someone can help me answer my question—- My question revolves around cookies and what cookies are sent to the server everytime I make a HTTP request. Lets suppose that I have logged into www.facebook.c...
In a case where we have multiple source of data, we need to : persist each source of data in its raw form. process the data source eventually with each other to transform them in a presentable state (into a queryable database). The first approach I could think of would be to store the data generated by the source usi...
I am designing the API architecture for my client: My client actually exchange huge files (csv) with his Partner with MFT ( SFTP ) **Partner ==> MFT ==> Client ** The requirement is to move to API REST exchange mode to replace MFT ( csv file) **Partner ==> API ==> Client consume GET API ** For example : The partner...
We are currently in the process of doing an infrastructure overhaul. A bit of background of what our business model currently is: We are an aggregator of bills and payment services for businesses. Utilities, mobiles and much more. We are making it easier for companies to connect to these services by just connecting to ...
I'm trying to understand and learn how to build microservice messages the best and came up with this task for myself: Services given: Accounts Service Token Service Email Service When a user registers the account needs a token for the verification email. The token service will issue tokens with a life time that can ...
I'd like to use some sort of AWS serverless technology to trigger an event when a clickstream stops receiving clicks. Imagine a website visitor clicking around a site. Within our current solution each click is being sent over http to an AWS API Gateway which uses a Lambda function to push the value into DynamoDB. I'...
So we have quiet a big TypeScript codebase at work, where each method resides in its own file. Now in a lot of those methods the variables are often declared all together at the top/beginnng of the method. I was discussing with some principal developers that it would be better to declare them only when they're really n...
I am trying to put in practice an algorithm for binary searching and compare it with linear searching: linear search: public static int linearSearch(ArrayList<Book> books, int searchedId) { for (int i = 0; i < books.size(); i++) { int currId = books.get(i).getId(); if (currId == searchedId) { ...
I was reading this article, which talks about storing location-based information. The author says that while Latitude and Longitude info for the locations can be stored in a SQL database, retrieving and searching through that information using SQL queries can be expensive, even with Latitude and Longitude mapped to the...
I'm dealing with two categories of machine learning algorithms. For simplicity, let's call them A and B. There are multiple concrete algorithms in each category, and my goal is to implement all of them. Because of this, my initial plan was to define abstract classes CategoryAAlgorithms and CategoryBAlgorithms, and have...
We are designing a shopping cart that allows customers to ship to multiple recipients, but we are stuck at the conceptual level of the relationship between items in the cart and recipients. There are two options to consider: (a) Assign items (child) to each recipient (parent) (b) Assign recipients (child) to each item ...
We are designing a multi-tenant architecture. In our multi-tenant architecture, there are different email templates that are shared across all the tenants. Email template looks like subject: {tenantName} welcomes you. body: Hi {userName} welcome to the new platform.(Generic template). But a tenant can have their own ...
I have an application which is quite old (7 years back-2014) but well built using JSF, Spring Webflow and Hibernate. This application is critical as being deployed for 50 separate clients each with different box (with tomcat as web server). Now I want to change the architecture and move to multi tenancy in web module (...
For our software development process we used to set up 3 environments : integration , QA and master. Recently it was decided to add a new staging environment that shall mirror the production environment for further testing. Our production environment uses kubernetes, SSL, Load balancing, and others components and conf...
I just finished my TDD-based REST API. And I would like to use Postman to document it for the frontend team until I realized it has its own test script. Now I'm wondering, is it necessary to double test it?
I'm building an automated test suite to integration/feature test my organization's Stripe implementation within a GitLab CI pipeline. We're running Laravel 8 and using phpunit for testing. Within this suite I'm testing both happy and non-happy paths (i.e. I want to test valid and invalid payment details). At the moment...
For fun, I would like to design a mathematical expression evaluator, with variables. It could simplify the entered expressions by factoring them, reducing them to a sum of simple fractions, calculating them, grouping them, etc... To give an example, if the user enters the following expression: (in a code format, of co...
I'm working on a project where I need to do CRUD operations on Book and Library objects. Naturally the relationship between Book and Library is Many to One, like so: @Entity @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class LibraryDao { @Id @GeneratedValue Long id; @OneToMany(mappedB...
Lets say we have a server getting upto 1000 requests per second, serving them at p99 of 20ms (strong business case for not increasing this latency). The server gc parameters have been carefully tuned for this performance and current latency is already bottlenecked by gc. We want to log structured data related to reques...
This doubt is about function doing one thing from Chapter 3: Functions of the book named Clean Code Here Uncle Bob is talking about this function: public static String renderPageWithSetupsAndTeardowns( PageData pageData, boolean isSuite) throws Exception{ if (isTestPage(pageData)) includeSetupAndTeardownPages(p...
I have single page application with an Angular frontend and a Spring REST-backend. What is the proper way to handle a list of string-based options in the fronted the enduser can select from, which shall all be shown and eventually slightly changes over time? i.e. gender ('Male', 'Female', 'Unisex') or jobs ('Student', ...
Suppose I have a Controller that takes a DTO that represents an Order. This DTO has inner DTOs that could potentially have entity IDs and/or entity data that's used to create an entity dynamically from that data, for example, an OrderProduct that has a price, qty, etc. Before this order can be created, I need to run va...
I know that we usually inject the dependencies by instantiating them in the constructor of the class we are injecting to. However, in my own experience, I just pass the class of the dependency as a parameter and do not instantiate in the constructor like the code below(I am currently working in Ruby): class A def ini...
As part of a black-box testing activity, I would like to check the executable I'm testing generates a binary file that responds to its specifications given a specific input. I'm wondering how I can check that. I have two solutions in mind but each of them has some drawbacks: Compare bit by bit the output with a binary...
I have a project where there's an external API which implements throttling. Roughly speaking, I'm allowed to perform N requests per minute. I also have a message queue (Apache Kafka) whose consumers consume API requests: a consumer receives an API URL to call, calls it, then produces another message which is processed ...
Does there exist some language whose execution model is implemented as a neuron network, or maybe as some other type of a network/grid (e.g. network of finite automata)? That is, specifically, without a central execution supervisor and main loop function, but where the execution point is moving from one node to another...
Is there any language or language feature where you can re-call the constructor on an instance of a class and is there any reason why you don't want to do this? For example, //let's say you have this: var person = new PersonModel("John", "Doe"); // is it possible to do this: person.constructor("Jane", "Doe"); Reason:...
Python loop generator Looks like I’m missing something with for loop generators… I deliberately made this simple code to test what was happening when I converted my list comprehensions to generators. It showed that the generator var can’t be used more than once: lst = [1,2,3] plus = (i+1 for i in lst) for i in plus: ...
The commonly endorsed, and considered the most reliable, way of evaluating the security of a program is through examining its source code. That is, this method is based on the fundamental assumption: "what you see is what is run". But if the program's memory has both 'writeable' and 'executable' attributes and the prog...
I have created a dashboard for rendering a list of clients into a DataTable. Below shown is the data model structure: When I had a few records in the clients schema, let's say a thousand rows, the request time was fairly okay. It would take around of 4-5 seconds for the whole trip, from requesting to processing at bac...
In my doctor's appointment booking system, I identified the following entities: Doctor Patient Appointment I also identified an aggregate, which is Doctor (aggregate root) and Appointment. It's an aggregate, as it has to hold an invariant of making sure that appointments assigned to them do not overlap. In pseudocode...
One of the complaints about C++ is the lack of automated bounds checking, which lead to memory errors. But the C++ STL containers provide a quite convenient .at() method for bounds checking a container access. Sure, it comes with a small performance impact, as opposed to the more popular operator[], but usually this is...
According to the definition by Robert Martin, high level modules should not depend on low level modules, instead both should depend on abstractions. So if I have a domain entity Invoice that uses an interface InvoiceRepository for persistence, and an infrastructure layer where this interface is implemented in a class P...
Until this moment, I have seen a lot of variations and combinations of the Repository pattern, implementations that simply queried the required information, some used something like a mapper, some used something called Units of Work, and some used something called CQRS that separated the reads from the writes, updates ...
If i wanted to encrypt a password on my website before its sent to the server, would i have to encrypt the password in javascript on the frontend for it to be hidden over the interent or could it be encrypted in my flask backend code over the interent somehow. Im just a little confused on what code is actually sent to ...
I have been creating new ASP.Net web apps for my workplace intranet (it is a closed system, not accessible to customers) and also re-creating some existing Windows programs as web applications. One colleague always suggests that things work more like a Windows desktop program - things that would take extensive effort w...
I am designing a timesheet app for logging user tasks using React for frontend and Django REST Framework for backend. The database is PostgreSQL and I have a table for recording the tasks with 4 columns: date, start_time, duration, description. I need a way to support the updating of a task after the user had created s...
I am a newbie to microservice. Currently I'm learning microservices by creating 2 microservices with CQRS pattern, with NO event sourcing, but each service has separate DB. Each service has separate end points for Command and Query. There is no separate Read store and write store. The services communicate with each oth...
I have a code-coverage requirement of of a certain percentage, and face the following tradeoff: Should I sacrifice in-method sanity checks and error handling for ease of (unit-) testability? Lets consider two variants of a simple method addAndSquare. Variant A: double addAndSquare(double a, double b ){ re...
tl;dr - I want to stream text data from one writer process to multiple reader processes. I'm thinking of using a file to achieve this. Is it a good idea? Using a file would avoid having to maintain client connections in the server and send data on each of those connections. The file would have a single writer which wou...
I have a method where I fetch user input, check if certain values exist, and based on that build my own custom input object that I would use to search in a database. The code for the search method is as follows. public SearchDocumentResult searchData(EmployeeInput employeeInput) { EmployeeInput getEmployeeInputForS...
There are two logical entities, Customer and Account where a Customer is associated with one or more Accounts. How to design a system that ensures Customers can update their Accounts concurrently, but for a given Account, the requests should be processed in order based on a time attribute? Example: Customer A has 2 Acc...
My understanding is that it's rarely a good idea to compare two floating point numbers due to inherent inaccuracies. However, my understanding of those inaccuracies are that they are deterministic and will always show up the same way given two identical inputs and identical transformations, hardware errors notwithstand...
The UNIX load average gives 3 numbers over 1/5/15 minute time intervals. It's supposed to be an indicator of how busy a UNIX machine is. The global load average is an exponentially decaying average of number of runnable/uninteruptable tasks. I'm interested to implement such kind of exponential decay algorithm in my pro...
If Pet is a class that implements the interface INameable, and dog is an instance of Pet, what is the name of the relationship between dog and INameable? In casual conversation and while talking with other devs, I would unthinkingly call dog an instance of INameable. This is always understood but might not be technical...
In the documentation about discriminated unions in typescript, here it says: Discriminated unions are useful for more than just talking about circles and squares. They’re good for representing any sort of messaging scheme in JavaScript, like when sending messages over the network (client/server communication), ... Co...
I am learning stuff and have made 2 microservices, Listener and MyApp. Listener is a jms listener (consumer of messages) and MyApp is the app sending messages to queue. I have 2 type of events CREATE and UPDATE and I want to maintain a single queue. So, my initial solution looked like below, here the Event class repres...
I don't work for an development company, but we have been working in partnership with one to develop an application for use internally within our business. The application is somewhat "niche", and so while we have the ability to scale it and roll it out to our other locations (we are an international company), it is u...
I've got a large, old application with a clunky, extremely manual deployment process (essentially, tribal knowledge combined with random scripts / build jobs scattered across servers). The application is largely written in C# with a little C here and there and is source controlled in one monolithic Accurev repo about 5...
We have an enterprise solution which consists of multiple components which are in turn comprised of micro services. We cater to both onprem and hosted models. The challenge is to keep track of the GIT tag and version details of the components/services that are delivered to customers. I am looking for a tool that would ...
I run unit and integration tests on my system. These create, start, stop and delete Docker containers. I want the exact same state in my Docker environment at the end of the tests as I had at the beginning. What would be the best way to restore the original state after the tests run? Option A: I create a class in the m...
So I want to write this function that downloads a file and unpacks it in python using TDD. The function will look like this approximately import urllib.request import tarfile def download_and_unpack(tarball_url, destination) datastream = urllib.request.urlopen(tarball_url) thetarfile = tarfile.open(fileobj=dat...
In his article RESTful Casuistry, Tim Bray claims that rebooting a server is not idempotent: But I don’t buy it, and here’s why. If I want to update some fields in an existing resource, I’m inclined to think about PUT. But that doesn’t work because it’s supposed to be idempotent, and rebooting a server sure isn’t. Wel...
Consider the following fictitious toy example: There is an aggregate root DayChecklist that holds a list of Tasks planned for the day: class DayChecklist { String id; DateTime today; ... List<Task> tasks; // lots of other business logic } Task itself is modeled as: abstract class Task { DateT...
I want to implement a search feature in my chat application like a messenger, skype, whatsapp has done. What they have done is when we search a word then it would not only show the message with that word in the current viewable message list but also on the past messages. To see the message with matching word, they prov...
I'm developing a Command Pattern with Undo/Redo support. The environment is Unity C# but should be mostly language-agnostic. My initial commands comprise of adding and removing objects to and from a space, but I'm encountering commands that lose their reference to their object. Removing an object means destroying it, s...
This doubt is about Switch Statements from Chapter 3: Functions of the book named Clean Code Here we have a function: public Money calculatePay(Employee e) throws InvalidEmployeeType { switch (e.type) { case COMMISSIONED: return calculateCommissionedPay(e); case HOURLY: return calculateH...
I would like to find the best way to solve the following problem: I need a database for a software. The software needs to use the data to populate the UI and allow the user to interact with them (edit, add, delete etc). There are multiple instances of that software (desktop, mobile, another desktop etc) all linked to t...
I was reading articles about TDD and I found the following one. https://blog.cleancoder.com/uncle-bob/2017/03/03/TDD-Harms-Architecture.html In order to answer this question I think someone should read the full article, but in any case I'll quote the part I'm not able to grasp or to picture in my head. The right side...
I've seen a couple of talks on Hexagonal architecture where they illustrate problems with N-tier architecture. Specifically, they show a spaghetti of service layer dependencies as the software grows. For example, the image below is from the Hexagonal Architecture with Grails talk: https://www.infoq.com/presentations/he...
as the title, how to know? is task manager the best way as my friend told me? I code in python.. I'm new here sorry if my question was in the wrong place.
on design stage , after finding my main objects , I am always find my self writing "manager" or "controllers" classes in order to handle the connection between them. some of the logic is in those classes. i know it is an antipattern Anemic Domain Model and that each class should have its own behavior. my problem is t...
I am thinking of creating two applications, one of which (App 1) will be in Django (DRF) and other (App 2)might be Django but might be another more lightweight framework (maybe Flask or plain Django or maybe different language altoghether depending of how efficient will be the script in Python). Anyway the idea is that...
I have question on how to design an order management microservice. An order has different workflow based on the previous state or based on the business needs. I'm guessing at some point cannot keep on adding if/else/switch because it would be very difficult manage workflows and this will also leads to more bugs. Order ...
I hope this is the right place to ask. I'm an experienced developer, and have used MVC for much time. This question is in the context of iOS/macOS development for the most part, (SwiftUI). Using MVC in iOS I always found the paradigm and architecture simple. Views contained view related code (layout and reactive code)...
In this post, Uncle Bob writes: Entities encapsulate Enterprise wide business rules. An entity can be an object with methods, or it can be a set of data structures and functions. It doesn’t matter so long as the entities could be used by many different applications in the enterprise. If I understood correctly, entiti...
My develper team includes Android, iOS, PHP, Web Front, .Net developers, but every type of developer only 1 person, and they don't know other's programming languages very well. We have setup Jenkins with some static analysis tools such as Sonarqube, but it's not enough to find out some logic mistakes. Is there any sugg...
I want a database table that can hold all of the group chat messages from all of the group chats. The max amount of users per group chat would be 20. The max amount of group chats per user would 25-30. Using Python3 Flask as my backend. (Clarifying for speed expectations when looping on the second option) The colum...
i'm trying to design a game program, but when thinking about which objects to introduce there seems to be far too many. For example for main object "Player" there are a lot of peripheral classes that should exist for e.g: PlayerRenderer - renders the player PlayerMovementHandler - moves the player So on and so forth.....