instruction
stringlengths
34
36.1k
Tell me anybody, is it good practice to call service layer methods through domain object getters? Let me show you with an example: public class User { private long id; private String name; private String email; private Address address; // constructors ... // getters and setters... public Add...
I'm new to MVVM but experienced in OOP. I have an easy solution to my problem, but I'm not sure if it violates MVVM or OOP or if it is a good practice. I have a set of ViewModel classes in my WPF project. Below is my hierarchy, with an indent representing a public property. ApplicationViewModel SidebarViewModel Si...
I work for an academic research lab whose file storage footprint is growing past the point where it can be properly managed "by hand", i.e. without extensive automation. (The number of files we have now in the low millions, but growing rapidly.) I figure that this problem must have been around for a few decades by now...
I've done a lot of test writing using Mocks, and so I've learned that it makes refactoring difficult due to implementation coupling inherent with Mocks. I've done a lot of reading on the topic tonight, but cannot see a way to unit test DI'd facade-type classes without using Mocks. I would like to know the correct way t...
Suppose a user defines input arrays on a JavaScript frontend. These are sent to a Python backend via the REST API. The backend computes a result for every combination of each array's elements. It then replies with a JSON file containing the results. Here's a toy example with two inputs. The first has five types of o...
Let's say I'm writing a class that tracks a single stock ticker. In this simplified example, the StockTracker class holds a string that tells me the trend direction and a variable window that holds x amount of historical prices. Now I want to expose this class so whenever a new stock price comes in, I can call a functi...
When I started working everyone was scared of deployments. Software was deployed infrequently and people were afraid services and machines had been manually “patched” since the last release. I fixed this by automating deployments and configured all services to be deploy when an application is deployed... so everything ...
TL;DR What are common practices to separate validation logic inside a rest API & thereby keep the code clean and straight forward? (code example) Context & Example Let's say I'm developing a rest API to handle some basic authentication. This example endpoint is responsible for confirming the user's e-mail after sign up...
I have a microservice architecture running on Heroku. I am having some problems handling race conditions. The problem is, that service A: Needs to fetch the user's balance through an API call to service B, then if balance is large enough, make a withdrawal though an API call to service C. I have noticed that if servi...
I've encountered a couple of different techniques for dealing with service bus messaging (queues and topics) and I'm just looking for some input on best practices. I've encountered a couple of different techniques for consuming messages off of a topic, for instance: The first technique is that a subscriptions is made ...
I couldn't find a similar enough thread, so i'm making a new one. My question is about reducing database writes. Context is that I have an application which increments a number in a database every time a user sends a message (which is more than hundreds of messages every second, peaking thousands at times) and i'm conc...
I have question regarding system design. Lets say I want to design a Flight booking system ( such as American Airlines). So, consistency when booking a ticket is very important. This booking system is also used across the world. A high level view of the system would look some thing like below (lets say servers are in N...
When writing a library (eg. for dealing with JPEG or PNG files), the first thing library author needs to provide is an abstraction over FILE* (to allow also reading from plain memory, pipe, socket, http...). Thus something like this: #include <stdbool.h> #include <stddef.h> typedef long long offset_t; struct _src { ...
To keep it simple, I have this service that stores data in a persistent volume. There are pods that are created by an API which use a subset of the stored data to perform an operation and generate new data that has to be stored. Both the supplied data as well as the resulting data can be several gigabytes in size. The ...
Description A WinForms application with the following as part of a form: When the "Add" button is clicked, a new entry is added to the ListView, with data from the TextBoxes and NumericUpDown above. If an entry with the same "description" and "amount" already exists, then the "quantity" is simply increased by the valu...
Thinking within a Service Oriented Architecture / Microservices / Enterprise Integration framework how does one avoid infinite loops when publishing messages between systems, especially when one has limited control over certain services (e.g third party SaaS products). For example: System A tracks Entity E – I have ve...
I work for this Accounting company - as a Product Owner - that uses several external services (one for Contract management, another one for Accounting Demands management, a third one for Financial purposes and so on). My IT Director wants us to build an Event-Driven Architecture to gather all the events that happen ext...
I've got some process in Go. Here's an example counting lines in text, though the question is meant to be far more general than this particular example: func lineCount(s string) int { count := 0 for _, c := range s { if c == '\n' { count++ } } return count } Alright, not bad...
I am working on a multi-tenant application that's using a shared Postgres db for all tenants. All entities in the DB are connected (directly or indirectly) to a tenant, for example: Tenant --has many--> Buildings --has many--> apartments -- has many--> people (just an example, let's not get into X shouldn't be an entit...
I'm learning the way to use API right now. Since I want to publish the code on GitHub, I have some question about it. 1. I will use public API, however, there are APIs with authorization and those don't (as listed here). I learned that publish an API call with API key will be a bad idea, however, for the APIs without k...
In an application to handle employee leaves, I decided to try CQRS & event sourcing and came up with the following flow of events. app events leave-application-received leave-application-validation-failed leave-application-accepted leave-applied manager-notified leave-approved leave-rejected user-notified calendar-upd...
I'm not sure if static vs. dynamic mock is the terminology used to describe this comparison, but I got this terminology from types of mocking static vs dynamic and Hand-rolled mocks made easy. To summarize, a dynamic mock is a proxy generated on the fly, whereas a static mock is pre-implemented. For a Python example gi...
Many high-level programming languages have built-in features to format a number with a system-dependent currency symbol: -- Outputs $100.00 (en-US) or € 100,00 (de-AT) Console.WriteLine(100.ToString("C")); // C# ? FormatCurrency(100) ' VBA ... I've been developing business software for more than 20 ...
A colleague and I are going to be working together on a single project for the first time. This raises a few technical questions for me. Like how. I think a version control system is a must now, if it wasn't already as a single developer. But this also means that I can no longer simply upload to a development server vi...
Example Code class HumanEye { wink() {...} close() {...} } class Human { eye = new HumanEye(); } Example Usage var jose = new Human(); jose.eye.wink(); jose.eye.close(); My understanding is that this pattern is cleaner than jose.eyeWink(). Although, it feels like I am doing something wrong... I don't know...
I have an restful app that uses PUT to replace existing data. For example, there's a user management url https://myserver/users, and to replace user data, for example, to change the name and the salary of the user with id=123, I use https://myserver/users/123 with application/json encoded new user's data in the request...
Hi I have this weird situation where I have a JSON producing service that represents a very complex object graph and this bject graph does not have a JSON schema that it is based on. The reason for this is because originaly there is an EJB service and this REST service is just build on top of it with simple 1:1 mapping...
When making changes to larger modules in Python, this is my current (inefficient) process: Make needed change to code Run program to test (using pdb - python3 -m pdb path/to/script.py Program will throw an error Fix error/create an exception Run again New error appears Rinse an repeat The data processing module I'm w...
I'm struggling to come to a consensus on the right approach that can be used somewhat consistently to balance integration and unit testing. Take the following method, that is extremely common to find in a C# .NET Core application. public interface IBusinessLogicService { CalculationResult CalculateBusinessRuleResu...
Okay, I was being interviewed at a company and the interviewer asked me a recursion problem. It was an online interview, so, he had set up the problem statement and a function signature on CodeSandbox (an online code editor/collaboration tool). I was supposed to fill-up the function body. He had only one parameter in t...
I read the discussion Should CQRS Command perform a Query? But I don't understand in which database the query is performed, because I have two distinct databases - one for reads (queries) and one for writes (commands). If I need to take the customer info, I need to read from the Write Database? Is this way correct? I t...
I have been developing a service that fetches data and also has a REST API to query the fetched data. The problem I have is, when this service starts it is starting the data fetching process, and this is a problem when it comes to scaling, as soon as I spawn 2 instances of this service they are both fetching data. I do...
I am building an eCommerce website and there is a Category table in my MongoDB database which has a field called path. This field is used to store category hierarchy e.g Boots category will have /women/shoes/boots as the value in the path. I have a similar field in ElasticSearch as well. The path field helps me retriev...
What is the point of sealing a class? Why should we seal a class at all? I've found a bit contradicting answers on the internet, for example here: https://stackoverflow.com/questions/268251/why-seal-a-class It is firstly written that every class that is not to be inherited, should be sealed, and then that it is not a g...
This new project is kind of fast walk through of previous controllers's jobs but some extra steps in between, sort of working as a wizard. The thing is, it seems make good sense to create this wizard in the backend as a separate project and manage the states with new database table and manager, yet some of the works be...
I am under the impression that having created_at or updated_at columns seems to be a best practice in database design. Frameworks like "Ruby on Rails" and "Laravel" both support that. I know what they are and I guess one main use case is when my data is corrupted I can check these columns to find out when that happened...
So I have a high level module, that uses a low level module (I intend to use this example for language agnostic explanatory purposes, so I removed access modifiers, getters & setters etc.): Class SalariesHandler { // properties… Printer printer; SalariesHandler(Printer printer..) { this.printer...
I'll describe my case: I have an aws lambda that will expose an API interface that will return json data (by topic) which is cached. This lambda will also offer private endpoints to recalculate the public data, then clear cache (by topic) and return data from new. On event based system these private endpoints will be i...
Yes, I know, the question title is a bit provocatory. But let me explain. I needed to execute a sequence of async tasks in JavaScript. They are async because I need them to be non-blocking, but I still want the current task to end before starting the next one. The order of tasks doesn't matter, the only important thing...
I have a module or class Random and in it there's a method called generate(). A client will always call it as res = Random.generate(). And from the inside, obviously, it can be called simply as generate(). What'll be a good choise: leave its name as is, or rename it to generate_random()? What's the most common practise...
I am a bit confused how should I organize code base with hierarchy of subtypes. To explain, I will demonstrate some synthetic example. Let's assume we have some kind of blog, where we can have two types of posts: text post and video post. Text post can have its own settings, so do video posts. Also behaviour of comment...
YAGNI might tell us, that in the below implementation the generic version is not needed, as long as the function is only used once. But to me personally, it seems, the generic version is more readable because I'm not distracted by all the possibilities the special class has, but are not used. The generic version is exp...
Sorting is generally used to solve problems where distance between elements matters. A sorted list/array has the convenient property that the smaller the difference between the indices of any two elements, the smaller the difference between the values of the elements.* When working with lists of coordinates or similar ...
I need a data structure that gives the best performance for multi-key range lookups. I do not need to update/insert/delete. This will be immutable. The use case is in-memory filtering of values over multiple dimensions. Research suggests k-d trees and BitMap indexes (specifically Roaring Bitmaps). It seems that k-d tre...
I am designing a background web job in Azure that, given a list of users it retrieves from a database, makes calls to a separate messaging microservice (for each record) that will end up sending N number of email/SMS for each call that was made to it. Say, for 10,000 users, I make 10,000 calls to the messaging service....
I have to design a way to create, store, and use formulas to read values from meters (electricity, water, etc). Example: Take 20% of meter 1, add to that 30% of meter 2 and subtract 100% of meter 3. I have come up with the idea for user input, the user could select a meter from the list, and write next to it the value ...
I work in a company where we do administrative tasks for other companies. With covid-19, there are many temporary laws to take into account. My company did as it did before : simply creating the new field in the table and adapt the programs. I know it is bad practice because over time, we have table with 100+ columns, ...
I created a class called MpvController to handle communication protocols over a .NET NamedPipeClientStream. Now, I need to test this controller. I have a second class named MpvControllerFactory that creates the controllers. I moved the code to establish the connection from MpvController to MpvControllerFactory, so that...
I am running unit tests written by someone else, and the output is littered with print statements. I know libraries are not supposed to contain print statements, but is it bad practice for tests to contain them? My take is that they shouldn't, and asserts and other comparison statements should be employed. Not sure tha...
I am a mobile dev, now for a project need to authenticate with a backend service using identityserver4 and OAuth2. The project has things set up so it is using OIDC for authentication. BUT It is on a "password" flow, so is not implicit flow (login on a browser to FB, Google, and come back to the app after that). So bas...
First some background on the problem, we have a windows service (C Sharp) that receives new messages and processes them.It is database driven so it checks a table for unprocessed records, processes them and then updates them, this is all done within two stored procedures, one to get unprocessed messages and another to ...
I'm making a basic platformer game. I have a Game class as well as Level class. The game object holds a pointer to the current Level object. A level currently has a std::vector of GameObject raw pointers, and normally it handles the destruction of the GameObjects. However, some of them are Player objects (a derived cla...
I work in a codebase which handles two countries' energy market functionalities as- payment, energy consumption, billing statements, addresses etc. For this I need to make sure that when I am writing a new feature the country1 code change doesn't break country2 code. How is this activity called or how can I express thi...
I'm looking for a code metric for monitor and track over time the size of several projects and their components. Also, I would like to use it for: evaluate size reduction after refactoring compare the size/length of two implementations of the same specification, even across languages. I know there are cyclomatic comp...
The Elm Guide says to use Maybe for partial functions, but I was under the impression that returning Maybe solves the problem of partial functions and makes them total. It gives a value from the codomain for every value in the domain. Is a function returning Maybe (for example, converting a string to maybe int), partia...
as the title suggest, I need to handle the tenant files in a multi-tenant saas app. fairly common scenario I believe and should have been solved by the gurus already. right now the app is in infancy and does not have many clients. it may become popular, or it may eventually prove to be a total failure. so by following ...
When throw a exception inside java method, IntelliJ suggest to add exception to method signature. When I have a long call-stack as below how I manage these exceptions. method 1() -> method 2() -> method 3() -> method 4() Method 1 calling method 2 and method 2 calling method 3 and so on. Lets say method 4 throw InvalidD...
I have an 8 pointer Story. Let’s call it for example XX1234 I have created 4 subtasks based on the list of actions to follow to complete the whole story implementation: 1. XX1235 2. XX1236 3. XX1237 4. XX1238 I intend to create one branch for each task's implementation. Do we need to create each branch with the Pa...
I am using JSON web tokens, but this authentication token can be any token from which a unique user can be derived. I am designing a REST API that allows CRUD operations on resources owned by specific users in our domain. This ownership is determined by a user ID field for each document. Users know their own ID (and th...
Problem description I have a pet project to translate TEI XML to standoff JSON and back: https://github.com/standoff-nlp/standoffconverter and I am currently thinking about a rewrite/restructuring. The standoff representation is a collection of objects that is separate from the content of the document. Each object repr...
I have 2 microservices [A], and [B]. These microservices run in a load balanced environment and there may be N instances if each microservice running. The microservices communicate via a message framework (Rabbit MQ). [A] Starts a long running process loop (P) which modifies data. [B] Can send cancellation requests to ...
The design pattern known as "functional core, imperative shell" is about separating side-effects from pure calculations, where business logic is supposed to be pure and then coordinated by the top function in the call, the "shell". Is it possible to design a framework (in any language) that enforces this pattern? Here ...
Our software product promises to support major releases with bug fixes for X years after the release, meaning that in our git repository, we keep permanent "support branches" for every major release next to the master branch. In general, bug fix tickets are handled as "these have to be fixed for release A", are fixed t...
To clarify the question, here is my context (or something very similar). I have an interface, that I call IDataSource. The implementing classes contain information to retrieve data. So I have multiple classes implementing it, let's say FileSource, DatabaseSource and WebServiceSource. So far so good. Now, depending on t...
We are developing a Web Application for manage dental clinics. The app can generate PDF files through the PHP backend (for example invoices, quotes etc.). Each of those PDF file needs to be digitally signed by both the app user (the clinician) and the patient. The sign we are looking for is the Legally Signature Europe...
Consider the following: import typing class MyClass(object): def __init__(self): self.my_member: typing.Optional[dict] = None def update_member(self): self.my_member = {} self.my_member.update({"a": 1}) self.my_member.update({"b": 2}) Here what I'm concerned about is the impac...
I'm learning about various software development methodologies, and reading about Lean hasn't clarified what sounds like two contradictory principles: Decide as late as possible Deliver as fast as possible The first one: As software development is always associated with some uncertainty, better results should be achi...
Most people would return Bools as follows: bananas(color) { return (color = "yellow") } and not as literal expressions; that is, not this way: bananas(color) { if (color = "yellow") return true else return false } However, in the discussion at wiki.c2.com Jim Perry said that if a method in...
Currently we are developing an application for service oriented development which is a college signature, the professor created two applications one for backend and other for front. We are using maven, hibernate and JPA. He has proposed a the following package distribution: However I want to simplify the distribution ...
We have legacy app which keeps state of a cart in local storage on a Frontend (this decision was made long time ago by other devs). The cart is cleared from local storage after 2 hours if it is not completed. Now we are moving towards microservices, and one of new microservice is 'Discount Coupons'. Customer can apply ...
I have an API which is licensed under AGPL v3. Let's suppose someone modifies the API code to make it look completely different from the original code and also deletes any history. Then he goes on to release the modified code as a product and makes it closed-source. Will he face any legal implications? P.S: I know this...
Currently, I'm making an Editor with MVVM pattern in WPF. Editor simply take an instance of a specific type as a reference and modifies it. The following code is the expected usage when editor development is completed. MyEditor myEditor = new MyEditor(); myEditor.Show(); myEditor.Edit(myDataInstance1); // Bind myDataIn...
I'm working on a system with a main entity, let's say "Members", these members have relationships to other entities and it's important to keep the history to be able to query and know the relationships at a given time in history. We mainly have two kind of relationships: Company (most exist and can only be on company ...
I am learning about the semantic web. So far what I know is that the whole idea of the semantic web is to add metadata to the data in your website in order to make the data in your website easier to read by a machine. But I don't know if an average web developer can add this metadata to their website, or if this proces...
So I'm currently working on building a restful API. Let's keep it simple and say I have two endpoints, both GET: /products /products/{productId} The first returns a list of all products, the second returns a particular product. The response for the first endpoint would likely look something this: [ { "id": 1...
I have the below default method in an interface and it seems to be pretty complex because of the many if-else conditions. default void validate() { Application application = application().get(); if (StringUtils.isEmpty(application.name()) || application.data() == null) { throw new IllegalArgume...
I understand the concept of cloud computing, but I'm curious why the term has become so exhausted the past several years. Servers have been around for a long time, and I fail to see how this is any different from before the term "cloud computing" was in fashion. There are many more vps services and more systems and com...
I am working on my chess engine in C++ and I went for bitboards to represent the board. It is basically a 64-bit number for which I use the bitset library. I feel the most crucial part in performance comes through the move generation. Earlier I encoded moves as std::string's in a std::vector which would perform moves o...
.Net Standard is specification. There are two popular implementation of the .net standard specification. ie .Net Core & .Net Framework When I create .Net Standard library, I am allowed to refer this in .Net core project as well as .Net Framework project. This makes absolute sense to me. I am allowed to reference a .Ne...
My team is about to build a new user interface. The team has skills in a range of client-side and server-side technologies. Half the team argue for ASP.NET MVC, and half the team argue for a JavaScript SPA. Either technologies works with our business requirements. The main point of contention seems to be how to survive...
Say we have a standalone spring boot application which we are going to distribute by creating an AMI and sharing on the AWS marketplace. Since the jar is available inside the AMI, I want to stop a user from buying the AMI on the marketplace and then redistributing my jar file. This is my current implementation plan for...
I'm working on a classes that are designed to read a defined file format; said format is comprised of 2 separate files (FileA and FileB). For ease of use, the format is referred to as the FileA format, but a valid "file" must have a FileB. The files share the same path prefix, but alter in suffix; therefore my current ...
I'm writing a C++ library which does some computation on vectors of audio data. The library supports both GPU (using Thrust, a C++ STL-like library for GPUs) and CPUs (using the STL). I'm using CUDA Toolkit 10.2, which is limited to GCC 8 (and thus limiting me to C++14). All of this is on an amd64 desktop computer runn...
You must have seen them as applications on mobile devices and I've been using one on mac OS. I was wondering what exactly memory cleaner software do? Do they free up memory in both ROM and RAM? And isn't this something that can be a standard or a must in order to submit apps for public use?
The focus of my question is on design. If I have an argument that can be None and it is passed between several functions until finally being used, which function should treat it as a default argument? For example, suppose the following code block: def foo(a): b = # some code block to assign b return bar(a, b) def ba...
I am building a simple application built in Rails that allows the client to connect to a third party api to sync customer data. The customer inputs their username and password and my application retrieves an OAuth access token which is valid for the current datetime + 24 hours. My current theory is that I run a cron jo...
I've got a DataSource base class and a few different sub-classes. I want to be able to switch which sub-class i'm using at runtime so I'm doing the following : // pointer for our datasource object DataSource *data; if (ds.equals("mqtt")) { data = new Data_mqtt(config,display); // Data_mqtt is a sub-class of DataSou...
I have a Node backend that uploads users' profile pictures to Google Cloud Storage, which returns a Public URL that is stored against the user doc in MongoDB. I want this URL to only be accessible from my React Native app, and nowhere else. In other words, I want it to not be public. I'm shying away from Signed URL's b...
Suppose I have this: ID A_Type B_Type C_Type 1 Y N N 2 N Y Y And I "flip" those columns into this: ID Type Value 1 A Y 1 B N 1 C N 2 A N 2 B Y 2 C Y I know this is fine to do. I know it means I don't have to change the target table in the second design if I have a new type, where I ...
If I am writing in a functional style and want to use the Replace Conditional with Composition refactoring pattern on a switch or a long chain of if/else if/else if/..., how do I approach it? I understand with OOP that applying the Replace Conditional with Polymorphism pattern makes this easy as you can simply call a s...
My application (VSTO/C#) handles excel files editing some cells and inserting some rows. My problem is more generlaized than this though, and is about defensive coding the class that acts as edtior. The design is based on a wrapper object for the worksheet, let's call it SheetTable; it contains the fixed data like the ...
I have a couple of web applications that write to their own databases. They also share a few entities, for example, the customer entity. My business case is such that the same field for the same record can be updated around the same time in both the applications. It brings in dual sources of truth. How can one ensure d...
I'm interested in designing a high level function in Python, (I.E. a function that takes other functions as arguments) but I don't know of any good conventions for documenting such a function. For example let's say I have a function "low_level" that takes an int and returns an int. def low_level(x): """ x: int ...
Following Martin Odersky's course on coursera - Functional Programming with Scala and I'm on Week 4 where we're learning about Types and Pattern Matching. In the video lecture, this is the representation of a Natural Number: abstract class Nat { def isZero: Boolean def predecessor: Nat def successor: Nat = new Su...
I came across reading a blogpost (this one on medium.com) about some principles of writing clean code and referring to a book by Robert C. Martin. Let me cite a particular paragraph from the blogpost: A function shouldn’t have more than 3 arguments. Keep it as low as possible. When a function seems to need more than t...
Imagine a project is assigned to a team, deadline is estimated as 8 months. After 6 months it becomes apparent the project will most certainly not be complete on time(e.g a law changes or a hidden monumental hurdle is discovered, the lead dev gets hit by a bus, etc.). But the project is important (e.g. lose an importan...
This is an architecture question as I've been asked by an existing web store to build a mobile app (they don't have a mobile app) that provides extra functionality to the store, a web admin panel to manage the app's content The mobile app is to provide extra functionality (tracking orders, contests, rewards etc.) to ...
I have the following function: def create_dic(): key_list = ['a','b'] val_list = [1, 2] dic = {} for i in range(2): dic[key_list[i]] = val_list[i] return dic I want to implement a test that makes sure there are no errors raised in the process of creating the dictionary. I thought t...
While it is an undeniable truth that there is no formula for the perfect team mainly because different projects might require different roles and skills, there should be some pretty common elements to it. I think that there are certain roles in a software development team that are crucial independently of the project. ...
I am new to JavaScript, I've done most of my coding in Python, and haven't found a clear answer to this question. If I have an object containing element ids and function parameters, and I want to add event handlers (pointing to the same function) to the ids inside the object - how do I do it? I've been looping over the...