instruction
stringlengths
34
36.1k
I have two types of microservices: Data Collector and Data Processor. They communicate with each other via Azure Service Bus Queue. Data Collector collects data from different sources and, once done, sends a "start processing" message to the queue. An instance of Data Processor receives the message and starts data proc...
If I am working on a single feature, I would usually commit multiple commits. Should every commit start with feat? Or should only 1 commit have the type of feat and use a different type for the other commits? e.g: feat: add part 1 test: add part 1 test feat: add part 2 fix: something in p2 feat: add part 3
I have been spending quite a bit of time recently researching the "best" (read most elegant. robust, simple to use, and resource friendly) ways to develop low-level hardware abstractions for embedded systems in C++. My current goal is to come up with some way to represent, configure, and interact with Port Pins. Here ...
I have worked on a library which processed data through multiple steps. It was written in R, a dynamic programming language where one could just add fields to existing “objects”, which were just glorified named lists (dictionaries). After loading from file, each object would contain a handful of members: two arrays wit...
I'm working on a project with 3 other backend developers and 3 front end devs. Also playing the role of architect for 3 other projects. One issue I see is that most developers are not formatting code, not paying heed to the results of static code analysis (part of issue is time, part managers who are more interested in...
Assume we are building a Progressive Web App(as everyone does these days) that communicates with the server through a rest API. Now I need to show a list of world countries to the user to choose from. I have a table with valid world countries in the backend that I use to validate requests, but the problem is, it seems ...
I've been refactoring some of my procedural code to OOP, and I'm wondering if using the adapter pattern is overkill in this case. Basically, I created a Order class. All class properties are a field in the database: class Order { private ?int $id = null; private float $value; private string $date; priva...
Suppose of having a library exposing the following piece of functionality: public static class AwesomeHelpers { public static async Task<int> ComputeSomethingImportAsync(CalculationInputs input) { int result = 13; // actual implementation is not relevant for this discussion return result; } } Suppos...
Consider the following code: public class User { private String password; public void changePassword( String oldPassword, String newPassword) throws WrongOldPasswordException, NewPasswordTooWeakException { if (passw...
I'm currently re-designing my hobby project and I'm trying to apply what I've learned recently from design patterns. Summary for context: the project listens for TCP commands from my phone (using another project not related to this question) and controls my PC using the Win32 API. This question concerns the Windows app...
Just like how Mac or Windows gives incremental names to new folders, how can we implement such a system in a database? Let's say I have currently 3 folders (default names) i.e., "untitled folder", "untitled folder 2", "untitled folder 3". Now if I delete "untitled folder 2" and try to create new folder again "Mac" will...
I work on a system that utilizes a form of n-tier architecture in that we have data and service models. The service models derive from the data models: public class FooDataModel { public int FooProperty { get; set; } } public sealed class Foo : FooDataModel { public bool Destroy => FooProperty < 0; } A lot of ...
I am using AWS dynamodb for my project. One can choose to use a simple key (partition key alone) or a composite key (partition key + range key) when creating a dynamo db table. But once it is created, the decision is baked in. For example, if a table was created with a partition key alone, and I need to add a range key...
I'm thinking about using an Event Sourcing / Event Store pattern in my RDBMS designs. What I mean by Event Store is a pattern where each data mutation (INSERT / UPDATE / DELETE) is persisted as an INSERT into a suitable table of events. At the same time, hopefully in the same transaction, some piece of logic updates a ...
I follow the Layered architecture Like this: But with two differences: I use Blazor Assembly for UI Layer. I have API layer(REST) In between the presentation layer and the service layer. My question is related to the Api design. If I design the solution for HR system and for example It has three modules: Recruit...
I have a case in my startup where I need to fetch images in bytes as fast as possible. At the moment I'm storing the images in Azure Storage then I fetch them on the run and cache them into my database as bytes. On future requests these bytes will be fetched from the database directly. Fetching the bytes from the datab...
I have the following requirements: Write a GUI app for automated testing of some custom PCB hardware. The system must be usable for a technician with little to no advanced PC skills. The test setup has 4 different serial port interfaces: DUT (Device Under Test) USB-C port. (Used for debug and sending test commands) D...
I am writing a class that has one function that I want to test. The function, textToPdf, takes a list of text files and creates and saves a PDF at the file path argument. In order to test that this function works, it seems like I would need a list of "example" text files and an "example" pdf which was made from those f...
Often I find conditional statements such as: if (life_max < max): if (expand): do life_max = max else: if (life_max > max) and not (expand): do life_max = max; Although readable, it feels a bit clunky and I'm curious as to the best way to simplify it while still keeping it readable.
It's common knowledge that the order of records from a simple one-table query is not guaranteed to be in the order of the primary key/clustered index. Adding a simple ORDER BY is no problem of course, but I'd like to understand why this is the case. Shouldn't ordering on a clustered index always be quicker than a noncl...
I'm designing a REST API that returns a collection of elements that can contain some verbose metadata, similar to one that might return books from a library. Is there a REST API design pattern to offer two different responses to a /books GET query, one which returns a full listing of books and metadata (title, author, ...
I tried to find some insight in how to handle the duplication of client-side and server-side validation in my app. If, for example, I have an User Entity like this on my back end: type User struct { Id int `json:"id" validade:"required"` Email string `json:"email" validate:"req...
I have a need to translate data from provider A to provider B. The data is typically pretty consistent, but, often has minor differences; for example: public sealed class ProviderOneFoo { public int Bar { get; set; } } public sealed class ProviderTwoFoo { public long Barr { get; set; } } My present idea is to ...
So lexers are supposed to emit tokens for key structures like INDENT and DEDENT for indentation stuff, or these: NUMBER ::= [0-9]+ ID ::= [a-Z]+, except for keywords IF ::= 'if' LPAREN ::= '(' RPAREN ::= ')' COMMA ::= ',' LBRACE ::= '{' RBRACE ::= '}' SEMICOLON ::= ';' What does it do for template strings lik...
PEP 8 states the following about using anonymous functions (lambdas) Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier: # Correct: def f(x): return 2*x # Wrong: f = lambda x: 2*x The first form means that the name of the resulting function object i...
My software has an Experiment as the central Entity which contains lots of details about how scientist does what he does. Basically 99% of the functionality happens within the Experiment and there could be thousands of objects stored in it. I have difficulties understanding Aggregates and mapping them to my domain: To...
I am struggling to design a board game architecture since I am trying to keep it as generic as possible in order to improve its flexibility to extensions in case of new features, but doing that I'm over-complicating its architecture (maybe it's a case of premature-generalization?) Just focus on these three elements tha...
Liskov Substitution Principle states: "if S is a subtype of T, then objects of type T may be replaced with objects of type S without altering any of the desirable properties of the program (correctness, task performed, etc.)" Preconditions cannot be strengthened in the subtype Postconditions cannot be weakened in the ...
Should i include the different functions of open account, close account , withdraw in the customer class(as shown in the picture) or should i include it in the account class
Background: different developers are building an e-commerce system using Spring. Some are working on the user facing arm, others are working on the CMS, while the other group are working on the vendor bit. My first thought was to combine all three into a modular monolith, since I imagine the 3 of them will have cross-c...
I have some static functions in a Python class. The advantage to using the @staticmethod decorator is that it informs the reader that the method doesn't require any information from the class or instance. However, what I've discovered is that if I have another static method that's called by my first static method, th...
Suppose that you have an abstract class representing a generic animal (called Animal) that provides a method called absorbedFat that taking a generic Food (class Food) computes how many grams of fat an animal absorb: interface Animal { int absorbedFat( Food food ); } interface Food { string getName(); } Which a...
I currently working on a parser project in C# and have run into problem. I have an entity folder within my project and within it I have: Entity IEntity.cs (defines a contract for entity classes) Contact.cs (main entity class) Address.cs (struct for contact class to store address fields) EntityType.cs (enum of e...
I have 2 implementation of the interface: public interface MyInterface{ void getCollectedData(MyData mydata); } public class MyImpl implements MyInterface{ public void getCollectedData(MyData mydata){ ServiceResult result = new ServiceResult(); ..... result.setName(myData.getServiceN...
I always adopt a practical attitude towards agile & scrum. I am more concerned with customer collaboration, small/continuous release, incremental development than following scrum rules strictly. I also find that some level of a self-managing/self-organizing team will always emerge if doing agile process (whatever "agil...
I'm currently using git to manage a "modpack" for a game, the modpack is made of several smaller mods, each of which is a branch. Some mods may also depend on, potentially multiple, other mods. These branches will never be merged into master, as they are optional modifications to the base game. When releasing a new ver...
Background I'm a scientist and trying to incorporate better software development practices in my work. In my niche field there's a standard model everyone uses that accepts a whopping 56 arguments. I'm attempting to create a public toolset that helps create and organize all the necessary inputs. The motivation is twofo...
Suppose I have a server with the following two jobs: Handle a payment using Stripe Connect to a DB with a list of posts/products/items What would be the best approach: Have all the calls go to /api/ eg. /api/payment and /api/posts Or since the payment is not as extensive and is a smaller function have it separate: ...
Grady Booch in Object-Oriented Analysis and Design with Applications says: The state of an object encompasses all of the (usually static) properties of the object plus the current (usually dynamic) values of each of these properties ... Then: Another property of a vending machine is that it can accept money. This is...
I'm implementing the steps of a feature with Specflow and I have a problem with one of the steps. Here is the Scenario : Scenario: Cancel a yearly running subscription after legal retractation Given I'm logged as "patrickTho" And a running "Yearly" subscription When I cancel my subscription the ...
I'm working on a website that has different languages, being English the master language. Most of the site is fully translated but English content has a bigger team so it usually goes a bit ahead of other languages. Long story short. The requirement for dealing with this situation is to serve the English content in the...
I'm working with another developer and we're trying to clean up and modernize some legacy code; all the while, trying to keep things readable and remain somewhat surgical with changes [1]. There's a method called GetResponse that returns a RestResponse object [2]: private RestResponse GetResponse(); Sprinkled througho...
Note This is a bit lengthy to have give a better understanding of the situation and to get some context. You might spot other architectural flaws (it's from an ancient application). I appreciate any feedback on this, but to stay on topic, I will mark the core question at the end in bold! Let's assume that I have an ap...
A GET should never change data on the server- use a POST request for that I heard this recommendation countless times over the internet and always try my best to conform. But how should I implement UTM tracking, while staying compliant to this requirement at the same time? For example, http://example.com/?utm=r3ct59 ...
I was confused by the distinction between REST and HTTP, and I found this article that cleared things up for me. In summary, it explained that REST is a set of general principles for web communication, whereas HTTP is a specific application-layer internet protocol. The article pointed out that HTTP lends itself to foll...
Which are the technical reasons/considerations for the sort() and reverse() JavaScript array methods to be in-place operations instead of returning a new array without modifying the original one, like the filter() or map() methods do? I want to understand the technical reasons that drove such decision, why those method...
It’s frequently taught that downcasting is bad practice. I have a case where it seems necessary, but I’m wondering if there is an alternative way to design this. Suppose interfaces are kept small through interface inheritance. Let’s use this example (source): An advantage of interfaces is that a ParkingLotManager can ...
Is this an acceptable use of member variables: One method sets the variables so that another method can use them. Would it be better to return the value in a list or tuple from func1? If I don't do that, is this as bad as a global variable? class test { int a; int b; int c; private void func1(){ ...
so for the past several months, I've been working on a personal project. It's a comically large, highly open, handcrafted text adventure game packed with inside jokes and fun little surprises for my friends to play around with and experience. I've got a few barebones prototypes working, and they've gotten a lot of "oh ...
what is the best practice when creating a database schema for the first time? Do I need to write schema migrations, or create it from the DBMS tools?
I was looking at the C++ library <complex>, and noticed that functions such as std::conj and std::norm are free functions i.e. static functions not placed inside the std::complex class. Why is this the case? I would've thought that, from a C++ OOP design perspective, it would've made more sense to have e.g. complex<T> ...
Suppose I'm writing a C++ class with the PImpl idiom for the usual reasons of providing a stable ABI and/or reducing #include dependencies. I want the class to have value semantics: modifying a copy of the object has no visible effect on the original object. Assume doing a semantic copy (copying the implementation memb...
Suppose I have a products API: /products GET: List of products POST: Creates a product /products/12345 GET: Get a specific product PUT: Updates a specific product So is this a good idea for the response: { message: // Containing the list of products } If I encounter an error, I would just put it in the message. O...
In the process of refactoring non-testable code we are re-designing some of ours classes so that it can be easily replaced by a stub or mock during unit tests. Here is an example of such class (implementation is omitted for simplification): class LightController { public: void turnOn(); private: CanBus m_canBus;...
I'm developing a system in C# who consists in a desktop application running a UDP server and a android app and this app sends data (byte array) to be read by the desktop application with commands and parameters for these commands. The goal is to achieve the best possible performance. With that in mind, I thought about ...
I have this simple UC diagram. Firstly, when the customer enters a repair order, the system checks whether the order can be processed (if the repair company can repair this model of device) - UC "Enter repair order". Only if company can repair this device, customer will start another UC "Select repair type", in the en...
It can be found in many advices on topic that having Singletons is an anti-pattern. Especially for cases of testability. Can someone please advice/critique on this way (please see code below) of dealing with this kind issue. Also please kindly confirm/correct that the presented way of passing a reference to ISingleton ...
We are building a system that scrapes data from many websites (curated list of 200+). Same data is scraped from all websites every fixed amount of time, but every website is required its own unique scraping function due to its DOM structure. Creating a dedicated function for each website results in re-deploying the sys...
I'm working at a startup, as a solo mobile application developer as a contractor. This has been for around 5 months now. I work part time. I have 3+ years of experience as a developer. We have a strong user feedback loop, which also means frequent and fast changing requirements. With so many frequent changes, I miss ou...
In Part 5 of Wizards and Warriors, the blog proposes the concept of a "Rule" and rulebook to address the issues with solutions in the previous parts. One of the issues was the need for double dispatch using a Visitor pattern: Player player = new Wizard(); Monster monster = new Vampire(); player.Attack(monster); Playe...
I'm creating a very simple compiler PoC that only has Procedures Calls to procedures. The syntax of the language is really simple: Main { Call("Proc1"); } Proc1 { // Empty } I want to create an algorithm to get THIS STRUCTURE (that is, in fact, a directed graph) Script { Procedures: [#1] (Procedur...
So we work in a structure with three week sprints, and we want to give testers time to test. Currently our process is, write functionality > write unit tests > code review > deploy to testing environment. What I thought of is that when we have functional code, why are we not deploying it to give testers more time to te...
For some more type safety I wanted to introduce a PageId type in my application. However, I am not totally sure what the best option to do so is. I want the IDs to be GUIDs, so I thought I just create a PageId class which inherits from the Guid class. Unfortunately the Guid is a struct, which does not support inheritan...
As a learning project I started looking into how to mimic some basic features of a no-code platform. I usually code in Java/Python, have good knowledge over Javascript/HTML, but wanted to use this to pick up React or Vue frameworks. I am more of a backend dev than front end. I understand the mechanics of the drag and d...
I am challenging my OO design skills and started an ambitious project that is supposed to be highly reusable and extensible. It is supposed to be kind of a framework for evolutionary algorithms. Maybe there is somthing out there on GitHub, but my research didn't come up with anything I'm looking for and anyway, I'd lik...
Would anyone here recommend using debug statements such as the following in production quality code? I think these are personally one of the easiest to include or exclude, but they make the code hard to read so alternatives would be better #ifdef DEBUG perror("open"); exit(1); #endif // Otherwise here we just ...
I have moderate Golang experience and lots of experience in other programming languages such as Java, Python, Rust, Scala, and others. I'm comfortable with building REST services and most of the other related topics, so the concept in general isn't new to me. Background I'm building a REST API in Golang using gorilla/m...
I need some code from some deprecated libraries, one small class (150 lines) and two functions (24 lines). The libraries are part of larger set that we use a couple of but both are being deprecated. The packages are still up on the registry but they are removed from the GitHub and not going to worked on or included in ...
In short, "functional core, imperative shell" can be summarized as: functional core implements logic; you unit test it. Your tests call real functions just like in production real functions are called; ie compared to mocking / faking, you don't run a risk that mocks / fakes mildly mismatch behavior of the real depende...
I am working in Python so attribute privacy isn't enforced. I have a Library class that stores a list of library Items related to that library. I want to be able to access the library Items through the Library class. Right now I accomplish that by returning the "private" items attribute. However, any class would then b...
A good auth system contains access and refresh tokens. I know what access-tokens are for and I know what refresh tokens DO - but I don't understand their meaning. For example: If I authenticate myself successfully to an API, then I get an access token and a refresh token. If a bad guy steals my access code, he can acce...
If you haven't heard of Kent Beck's TCR, it can be summarized with this: any time your tests go green, you commit; anytime your tests go red, you git reset --hard. This post is about how to practice TCR correctly. It ISN'T about the merits or deficiencies of TCR (although that would be an interesting topic for another ...
We are building a system that runs on our cloud and that needs information from our clients network that must not be exposed openly. We have concluded that the only way this could work, is if our clients can install an agent in their network, that would gather the required information and push it to our system through ...
My friends' company is using the incremental method to update/deploy a new version of their app to the customer site. But what kind of surprises me is their update/deployment is on granularity of files, not the services. For example, suppose the finally built app in version 1 consists of two files A and B: web_app (ver...
When doing TDD "by the book" we should only -- as far as I understand -- write failing tests. This means tests for unimplemented functionality. I often find myself wanting to add tests for edge cases that expect to work with the current implementation. This means the test does not drive the implementation, it is merely...
How does phone number based authentication work, and what are its best practices? I've noticed there are apps with streamlined sign-up/log-in processes where only a phone number is required, simply the phone number and then a verification code sent to the user via SMS. A good example is the dating app Hinge. I don't re...
Okay, first of all I understand the concept of IoC container! It's used to implement automatic dependency injection so you won't have to manually inject dependencies to class. It can automatically detect that if a class requires, let say for example IEmail dependency, inject Gmail class into it. I noticed that, IoC con...
I have a large collection of (C#) objects and these objects have a large number of properties, mostly strings and numbers. This collection is stored in a database. When a new object is about to be added to the database I need to check if similar objects already exist in a database. One way of doing this would be to enu...
As I got to know there are 256 possible combinations to get for 1 byte. If I understand it correctly, it should mean that you can display any number out of numbers 0-255 and this very number would use only 1 byte of your storage on your computer. Displaying a number out of the numbers from 256 to 65535 would however co...
I have an eternal discussion in my work about why "error first" is "worng". In order to ensure what I try to tell with error first is the following code pattern: if condition: raise Error() code Instead of if-else approach if condition: code else: raise Error() I think that the first one (error first) is...
Background I've taught myself Python over the past year-and-a-bit, and would consider myself an intermediate Python user at this point, but never studied computing at school/university. As such, my knowledge of theory is a little weak. Python is the only language I know. I'm trying to wrap my head around the Liskov Sub...
Suppose I'm building a web application using Django. Some of the views need to touch multiple database tables or rows, and there is some kind of state consistency that I need to ensure among the records. Here is a simple example, albeit a bit stupid. Suppose we're talking about an application for the management of clas...
Consumer software often has interpreter dependencies. How should a situation where the required interpreter is not by default installed on the targeted system be handled for consumer software, soft for non-technical people? Bellow, I give an example with Node.js and macOS, but my question applies equally to other platf...
I need to create some commands that share the method Execute() and a property that gets the result of such execution: List<IResponse>. I have the following interface: public interface Command { public IEnumerable<IResponse> Responses; void Execute(); } Each class that implements command needs different inputs ...
We have function DoStuff. It can return Stuff or Error. What is the cleanest way to do this in C#? I know that it's best to throw in error case, but it has its own downsides. Also consider case where there are 2 logically different results, which are not errors. what then? Important for me is that code is readable and ...
I've been running into a common pattern when requesting data from multiple sources: Have a list of objects from one source (e.g. a list of Cars) with an id property and a few other properties populated (e.g. make, model, year). Call some service (second source) with the list of Car ids to get data for a few other Car...
Frequently in applications we encounter situations that could throw a NullReferenceException; for example, assuming the following method's argument is a user defined reference type, accessing the reference without first checking if it is null, can result in a NullReferenceException: public void ProcessObject(MyObject o...
Our software product is not complete, but it is functional enough that one of our clients is using it. We produce release notes with every sprint. The notes are divided into sections such as "New Feature", "Improvements", "Fixes" and "Known Issues". Frequently we get a change that would never appear in the release note...
I wrote a Java web service using Spring that handles REST calls from the Internet. The web service uses a Postgres database underneath to store, modify and read data. The Postgres database is used exclusively by this web service, no other program accesses the database. The web service uses a database user th...
Today, I updated ZBateson\MailMimeParser the PHP e-mail parser library from 1.x to 2.x. Soon enough, my PHP error log started filling up with errors. Noting where it happened, I found out that it had to do with their ::parse(...) function: https://mail-mime-parser.org/upgrade-2.0 An additional parameter needs to be pa...
I have various types of financial securities. Each one of these securities shares a common set of methods. For instance, they all pay some amount of cash interest between two dates. Each security has a different way to calculate that amount, however, that can require totally different inputs. Think of this as trying to...
I have been assigned a ticket to update all node packages and dependencies in a react project to the latest possible version without breaking the application monolith as it is now; no further meaningful development of features is planned for this application. Although I plan to finish the task without much questioning,...
I’m struggling a bit to design the following class: It’s a service class with multiple methods. It depends on a http client interface which must be created in the factory method and can’t be passed externally. If property1 is set to ON, it is expected that the url property is set. Then it’s required that it calls the e...
I am writing functional tests for my application that scrapes some data online then sends the results in an SMS text (on a weekly basis). My understanding is that functional tests are meant to test the functionality from the users' point of view. So, how do I "test" that the user receives a text? I am using Twilio API....
Right now I'm working on a project that's basically a marketplace. The project separates backend (Django + DRF) and frontend where frontend can hit different endpoints based on user interactions with web interface. The project has two distinct but related entities: buyer; supplier. So original engineers decided to co...
I recently joined another team part time where I kinda know several of the people, and they know me for my design work mostly, but I'll be doing design and some development with them. There's a lot of things I've noticed in the space of the first week that are just not done right, but I don't want to bring up a huge li...
In a golang project, I have mocked external services. But in order to check that mocked services has the same behaviour as real services, I have done some common testing on the interface with both mock and real, so with real credentials. Let's say that I have : repositories/serviceA/mock/mock.go repositories/serviceA/m...
I have the following code and I am not sure if the builder factory is the best approach to solve this code duplication. createA(a, b, c, e: {e1, e2}){ return{ a b c e } } createB(a, b, e: {e1, e2, e3}){ return{ a b e } } createC(a, e: {e1, {ee1, ee2}, e3}){ return{ ...
Consider the following approach to validation of an API class (POJO or what have you, I mean a class which just acts as a container for some properties), we make all constructors private to the API scope (and actually let us insist there only be one constructor), and the constructor does validation of its inputs, throw...
I am working on an application for awarding organizations by the CEO based on a somewhat complex criteria of multiple dimensions. The process consists of 3 nested workflows: Award workflow (opened → closed → endorsed → approved → published) Nomination workflow (submitted → reviewed) Nomination Review workflow (started ...