instruction
stringlengths
34
36.1k
Let's say I have a project that needs to do the following: Multiple calls to read from the database where each call is a different query and returns back a value object (just has getters/setters). Let's say we end receiving 20 value objects Perform some logic with the data from these value objects I'm trying to brai...
I'm not sure if this is the right forum, but I'm really looking for an advice on this. We've a procedural decision engine, which is fairly rudimentary, to decide application routing. It's basically multiple if-else statements (about 30 of them) in series. For example: if (application.isBlue && (!configs.isBlueAllowed)...
I'm looking for the "Holy Grail" (best practise) of how to update an entity with REST? There are three main approaches I've found so far: Always send full entity, regardless what has been changed and just overwrite the previously stored data. (This is the one I'm using right now, but it's ugly because of hidden fields...
I'm prototyping some single machine, single user software with a client-server model; the first client for which will be a CLI, but I expect a (local) webapp/GUI to come later. For the CLI, I'd like to be able to either connect to an existing server instance to run whatever commands, or start one up for the duration of...
Problem overview: I'm creating a spring application just for learning purposes. I would like to create a microservice just for files, which: at the beginning would have only two basic endpoints upload/download a file (used by other microservices, not by a user directly) create db only for that microservice with thefil...
I am considering a CQRS refactoring process. It is more of a learning exercise in my spare time. The use case is similar to a price comparison website where a user enters their details for a mortgage and they are presented with mortgage options from service providers. For example, a user enters the minimum deposit; ...
There's a sort of pattern that I've sort of stumbled myself into "discovering" that seems extremely useful, but I've never seen it described before. It's sort of a way of achieving inheritance through an interface. It's really wierd where the class "becomes" the thing that it accepts. (Written here in C# but it doesn't...
Let's say I have the following function (in JavaScript, for sake of example): function foo() { var bar = function () {return 'lol';} return bar; } This function returns other functions. I had the misconception that this was called a generator, but on reading around, that's something different entirely. Googling th...
Here's an example taken from http://json.org/ Is there a name for this kind of diagram?
Often I want Arduino board to control several peripherals. Writing program for all of them in one document using #define SOME_PIN 4 constructions seems pretty inconvenient to me. Especially in such a case when you have to modify old code which was written a long time ago. I chose to use the following approach to organ...
I am designing and prototyping an ncurses C++ wrapper. It's a hobby project, nothing too serious. I will omit include guards and stdlib includes etc. Consider the following files: application.hpp #include "ncurses_forward_decl.hpp" #include "window/window.hpp" #define PPCURSES_VERSION_MAJOR 0 #define PPCURSES_VERSION_...
Assume we are in the world of car rental application :) Let's say that I have 3 types of cars with 2 categories of price: Car type Price category ------------------------------ Sport High Luxury High Economy Low Values of High and Low can change over time, so they should be a sepa...
My application backend consists of a bunch of standalone tasks linked together by messaging queues. They all need to access the same SQL database in order to run and store their results. Right now, all the tasks are accessing the SQL database directly, but by not having a centralized entity to manage access to that dat...
Haskell is one of the few non-strict languages out there. In his paper Why Functional Programming Matters, John Hughes uses (memoized) lazy evaluation (as well as higher-order functions) to implement a couple of nice algorithms where he is able to separate: how data is generated. how this data might be manipulated. ho...
I've been doing some research on RESTful architectures and JSON responses. I'm trying to understand which method of laying out JSON responses is "correct" or if they are both acceptable. For instance, using the swapi, I've seen JSON responses that reference URIs for embedded objects: { "name": "Luke Skywalker", "h...
I am building travel blog using React as frontend Javascript framework along with GraphQL. I am doing this project by myself as a pilot test and I am currently in a phase of translating photoshop design in HTML/CSS/JSX. What bothers me is what will be the best way to store blog posts in database, fetching them and show...
I am developing a project using Laravel. My workflow is: route directs to controller Controller calls eloquent models Eloquent models perform queries (tipically CRUD and find) Controller returns either a view or a JSON string Lately I realise my queries are getting too complex. Complex enough that I find myself writi...
In my system I frequently operate with airport codes ("YYZ", "LAX", "SFO", etc.), they are always in the exact same format (3 letter, represented as uppercase). The system typically deals with 25-50 of these (different) codes per API request, with over a thousand allocations total, they are passed around through many ...
I was studying Lamport's mutual exclusion algorithm from the original paper, and noticed a difference in the release phase to the one given in Wikipedia. In the original paper, author states that : To release the resource, process Pi removes any Tm:Pi requests resource message from its request queue and sends a (tim...
To simplify deployment and project management tasks I maintain a monorepo containing several packages that each have a semver version. To be clear, I don't mean several repositories managed from one place, I mean a single Git repository that tracks several packages with a common toolchain. Note that this does NOT imply...
To avoid magic numbers, we often hear that we should give a literal a meaningful name. Such as: //THIS CODE COMES FROM THE CLEAN CODE BOOK for (int j = 0; j < 34; j++) { s += (t[j] * 4) / 5; } -------------------- Change to -------------------- int realDaysPerIdealDay = 4; const int WORK_DAYS_PER_WEEK = 5; int su...
Is it possible to use semantic tags in UML associations (among classes) to express the wider semantic nature of the relationship? For example, consider the relation that Doctor TREATS Patient. Beyond the TREATS relation, we also want to express that it's a medical and humanitarian relation. Is it possible to somehow ta...
I'm working on a small python project and have a general_code.py file where I have functions that I use throughout the project. Some examples: def to_boolean(var): return var in ['True', 'true', '1', 'y', 'Y' 'yes', 'Yes'] e.g 2 def get_last_line(in_file, block_size=128, ignore_ending_newline=False): e.g 3 def s...
At my work every line of code must be reviewed and this review is formalized in a merge request. Now we are a facing a situation were one developer developed a prototype for a new product which is now going in production. There are a few hundred commits and lots of line changed all in one branch. I'm wondering what wou...
I am researching before starting to work on an API for a web-service I am building. The goal is to be very quick and easy to adapt and use for other developers but fairly hidden for clients using a collection of Webapps to make calls to the service behind the API. It is the first time making an API for more than intern...
Background I'm currently working for a relatively small ticketing company with many clients and customers. We have developed an 'open' (as in it can be used by anyone) Serverless GraphQL API in Node.JS. The API is made up of fine grained services that implement their own security, exposed using GraphQL through AWS API ...
I have been looking into object detection and tracking for a project that I am working on but I can't yet seem to find any techniques that I can make use of to utilise the information from object tracking to determine the direction of travel. Ideally I'd want to find out whether the object is moving towards or away fro...
(Note that, below, I am frequently using term "daemon or worker" just to indicate that I dont know which word to use as I dont know the exact difference between them in the context explained below.) Consider following scenarios: I need to write a server listening on some port, which accepts a request on that port and...
I have a API call that returns a list of Payments, each Payment contains a User. I need to call it, save the results in the database, fetch all the payments and users and return them all to the presenter. On the UI each payment row will also contain info about the user. So the Payment and User entities are highly coupl...
At my new work, a few people want to share modules between systems/apps, and I'm a bit skeptical about it. Context: we have a lot of little apps living in different servers, some of them are scrappers, some just web apps etc... they are different languages too (java, javascript, php, python) maybe the only thing that t...
I built an app where the app owner can build custom forms for each of his clients. The forms have default fields like "name" and "message" as well as custom fields for each client requirement, like "whatsapp", which must trigger a switch in the app to send the message via Whatsapp instead of a Mailer. So custom form fi...
I feel like this is a dumb question but here it goes: If i'm consuming rest (getting data and transforming in POJO), does it sit in the DAO or Service layer? As for what i've researched I believe that it should be in Service Layer but i couldn't find a definitive answer or explanation. Thanks!
I am trying to look for the right design pattern for the below scenario. I am trying to create an object/binary with different modules, a module is a functionality that I want to provide to that object. Examples of a module are like reading a file, writing a file, sending some requests to the server, etc... Let say I ...
We started a project recently, and during the design process, we have some arguments among team members. We have to deal with enumerations so we ended up with three choices. Have the enumerations as Normal Enums in Database Have the enumerations inside the Application and isolated from the Database. Keep them only in ...
I'd like to add translations without waiting for a full new release. In other words, I'd prefer that the Resource Bundles not be part of my Git repository; and that they be easily editable and immediately reflected in my webapp. What are the standard solutions for this?
I understand inlining as the following: A separate function which is marked as "inline" (assuming the compiler really does inline) will be "merged" into the function it is called. i.e. (pseudo code) void main () { printf(b(2,3)) // will be printf(2*3*3); } inline function b(int x, int y) { return x*y*y; } Howeve...
Imagine we have a simple rule: A member must be at least 18 years old to join. Imagine we have a C# class for Member and it is our domain model. The rule is enforced in this class. Now we create a web app with a view to create a new member. This view has a datepicker for entering a date for date of birth. It makes n...
I'm working on my first android app. It's a companion app for a video game, and it should come with preloaded data. I'm not entirely sure how to best go about this. I apologize if this has been asked before but I tried searching for a few different keywords and nothing is jumping out at me. So I've got a basic data mod...
I am building an API using Laravel and am looking at using Laravel/Passport for authentication - but I am struggling with a design decision. The API will be consumed by multiple other applications / sites - initially an Angular web app that administers the data stored in the API, and another than will display certain d...
At a job that I recently started, I inherited some of the projects from the guy who previously held this position. One of the projects was a program that used a Website Platform's public API to get certain data from their site. The program itself is pretty simple, and is written correctly from what I can tell. It's not...
My team is migrating from a monolithic ASP.NET application to .NET Core and Kubernetes. The code changes seem to be going as well as can be expected but where my team is encountering a lot of discord is around the database. We currently have rather large SQL Server database that houses all of the data for our entire b...
If I have a service that consumes events of type A and emits events of type B, how can I make sure that event B is only emitted once for every event A? Should the service also subscribe to events of type B to see that an event B with a same correlation ID/with a reference to the A event wasn't written yet? Seems like a...
A user story calls for an extension to a current feature. This is reviewed and discussed in planning and given a small/medium point value. Internally within the team the effort is estimated at 2 to 3 days. As work progresses it becomes clear that it is not possible to extend the feature in the desired way without signi...
There are points of failure: ATM gives money then send a deduction request to it's bank. What happens, if the request will fail? the user got the money but his account hasn't been deducted - fail. ATM send a deduction request to it's bank, bank deduct the value, send a request back to ATM, the request fail (disappear)...
I'm working on API design for a mobile app where the user can send one or more photos that will be stored in the database. Currently I have three routes, post photo/create which will send one photo every call and returns json object when successful, post photo/delete which will delete the photo by id and return empty o...
Given a system of services and a reverse proxy, such that requests may either be conclusively processed by the proxy or ultimately handled by any of the services behind the proxy. Consideration has be given to the X-Forwarded-For, Forwarded, X-Forwarded-Host fields. Though they appear naturally fitting for the request ...
As far as I've learned, the IRepository should contain CRUD. Then we inherit this IRepository in our other Interfaces like IProductand implement IProductconcrete class ProductRepository, with methods like GetAllProducts(), Top5Products(). We could also do the same with n-tier architecture. like, Creating DAL Class Libr...
I am developing the back-end of an e-commerce system, which has customer and administrator type accounts. These two roles do not overlap, administrators are there to do the back office work, while customers do the shopping. I would like to make the admin panel completely inaccessible to the public. If I were the only d...
I've been reading up on API versioning for REST APIs. Most of the articles I've come across (here's an example) seem to focus on two options: URI based versioning, e.g. v1/my_resource/ Media Type Versioning, i.e. adding additional information to the ACCEPT header. I have also seen proposals of adding a custom versio...
In our team, we currently all develop on our local environment, with a local database, that regularly fetches data from the production database. However, as our production database grows, it's becoming impossible to fetch data from it and store it on our work laptops. What are the best solutions for development databas...
Has anyone worked in an environment where multiple in-house applications are all under one database with each application given its own schema within that single database? I don't just mean a few small, related applications in one DB, but like full on standalone applications being put into one DB with other standalone ...
I am pretty new to software architecture, and I am trying to understand the basic concepts of n-layer architecture and MVP (specifically Passive View). My current understanding of n-layer architecture: The point of n-layer architecture (or n-tier architecture if we have a physical separation between the layers) is to s...
I am developing a small application as a hobbyist. This application will track costs (eg. purchases and sales, ...) for a single person company. Only string, date, double, integer, and decimal types are stored. References to files will be path. I want to store this data somewhere structured and my SQL knowledge is belo...
I may have gotten myself confused, when reading CRUD vs REST and how they are similar, so I wanted to explicitly ask: can I turn my CRUD application into a REST application, when I have a specific scenario, and will doing so be of any benefit? My existing CRUD application uses data in a MySQL table that is mostly pass...
I write code for an Engineering application where engineers keep giving me various specs in a form of tabular data - for example, a table with product model names and many various parameters for each model. Engineering is my "customer", since they use the code I create. I usually encode the data they give me in a data...
The antipattern-plagued game I'm creating is using ASP.NET Core, which, in many cases, requires the use of dependency injection. This is new and counter-intuitive to me. Up to now, I managed to limit the use of dependency injection to where it is strictly required by the framework, while writing the mechanics of the ga...
Lets say I have multiple file types: .json, .csv ... etc These file types come in different formats: Second json structure Extra column added to csv etc. I need to extract fields from these files; however, sometimes one format doesn't have all of the same fields. JSON format 2 has a new element than JSON1 didn't h...
I've noticed that some methods like the String's substring(int beginIndex, int endIndex) and StringBuilder's delete(int beginIndex, int endIndex), use the second parameter to signify that the substring or deletion should go to endIndex-1 and not endIndex. Is there a reason for this? It doesn't seem, at least to me, to ...
For example, suppose I have a shopping app, which has a user info page to show user info: class UserInfoController{ toPurchaseRecord(){ } } and a purchase record page to show purchase record, which can be reached from user info: class PurchaseRecordController{ } but the problem is, I need to get data from int...
I'm sure there's some programming paradigm to cover this case, but I can't find the correct wording for it, and therefore my Google-fu is worthless. I have a class called SimpleWorld that has methods, and inside those methods, the class likes to instantiate objects. Now all of these instantiated objects subclass a part...
Is it fair to say that it is good practice to default everything to private up when defining a class? For example, for my public interface I would set my class something like this: class foo { private var x private var y //even get and set are private, //public only if necessary private get/set me...
I have a git repository that is built with one library and during compiling the library is switched for another to get 2 versions of compiled code for 2 different libraries. (different versions of the same software) This method has been working until now. Now I have received a new 3rd library that differs significantly...
Assume you need to define a completely new REST API for a given service. These rest APIs are distinguished by something like "v1" and "v2" in the path. If you develop these services in Java, would you: Add the new access points to the given project and deploy a new version that supports both the v1 and the v2 paths? R...
I have a list of items. Each item have various properties. Each item can be tagged, like tagging a post here. Right now, tags are represented using a Tags property, that is a string and it looks like tag1:tag2:...:tagN. A user can search for an item based on its tags (i.e. get me items that has tag2 and tagN). To do th...
PHP is written in C, but is considered a language. What makes it different from something like jQuery which is considered to be a library of Javascript? Why is PHP not a library of C or jQuery a language in its own right? This is not a dupe of this question because it does not address languages which is the primary po...
Background In much of the literature I've read online with respect to multi-layered architectures, many people describe how to create the simple application where: UI presents static model objects to the screen. Users can make one-off requests (e.g. send e-mail, commit payment). A database transaction is typically mad...
Problem: I have a complex system with many layers of abstractions. I need a different behaviour low in the abstractions, but to be configured high in the abstraction. Solution 1: Having a parameter to define the chosen behaviour and pass this parameter down in the abstraction until the method that uses it. Solution 2: ...
We have an MVC application that has very granular and configurable authorization. We currently have been using the authorize attribute against our controllers and controller functions. The next project that we will be working on will require us to support a 3 state control. The 3 states are NoAccess, ReadAccess and Fu...
I am designing a class that has a state. I wonder if I should expose that state in the interface in view of allowing a decorator to enrich the state transition logic. Shall my design expose access to the state? Let's take an example and suppose that I have this interface: public interface ILoginService { void Logi...
I've written a bit of code that looks like this: async function fetchData() { const json = await fetch(ENDPOINT + key.key).then(data => data.json()); //Do something with the data } It's pretty clear and straight forward what I'm doing here. I'm just wondering if it's normal to combine both the older Promise ...
It seems like ES6 imports for Node have been a bugbear for a while. There is the --experimental-modules flag, or options like using Babel - but AFAIK ES6 modules still aren't supported in vanilla Node.js. Meanwhile, ES6 modules are supported by all the major browsers. Why is that the browsers have been able to implem...
I have method a the returns something like this: List<Customer> customers = repository.GetCustomers.Where(x => x.IsActive); return customers; Visual Studio tooling is suggesting an inline temporary variable: return repository.GetCustomers.Where(x => x.IsActive); Years ago I heard a tip on a .Net podcast (the guest I...
This question addresses building a Chess engine. I've done just that, and in my humble opinion quite elegantly. But I'm missing my ending conditions. Here are some pseudopython functions that I use. # Move from position old to new def move(old, new): if is_legal(old, new): # Eat and move if is_legal...
I know that an int for example has a max value of 2,147,483,647 and is stored in 4 memory slots (each 8 bits and a total of 32 bits or simply a word). Int can be loaded into a 32 bit Register just fine. If we are using smaller Register counts like an 8 bit Microcontrollers, the int will be divided into 4 registers. N...
#include <stdio.h> int main() { size_t a = 2; size_t *p = &a; printf("%p\n", p); } The above code will print the memory address of a. I understand that within an OS, this address is referring to a virtual address and not the actual memory. However, compiling a similar code (osdev.org) and running it as an...
Going through osDev.org, I managed to write a small kernel that outputs a memory address, similar to this: #include <stdio.h> int main() { size_t a = 2; size_t *p = &a; printf("%p\n", p); } of course printf is replaced with another function but the principle remains. There was an output on the monitor (an...
I am working on an open source web application that I will be hosting on my own server and I estimate most users will use that but I also want to easily allow users to run the application themself. The problem seems to be that the more I attempt to make my system performant and scaleable the harder I make it to host fo...
UML specification says: If multiple tokens are offered at the same time, then the tokens are offered in the same order as if they had been offered one at a time from the source I want to know "what situation is tried to be described"? one source to one target? one source to multiple targets? multiple source to multi...
This is in the context of my bismon program (GPLv3+, on github, still unreleased, alpha-stage), which is mostly a single-page web application (with a garbage collected DSL in it) which uses the libonion HTTP server library (so bismon is a specialized web server). Most of the HTML + Javascript + C code of bismon is (or ...
I have written a C++ code that calls a solver called CPLEX to solve an integer linear optimization problem (under Ubuntu 18.04). I have three sets of data and I use make command to create 3 excecutables for each one of them. I then run these three executables at the same time. My question is, does the fact that CPLEX l...
I am working on a data integration project, where I need to extract data from oracle source and load it to XML file. The requirement is to get the list of customers and foreach customer create an xml file with customer data and its associated products and the product related data.The way I have designed it as follows. ...
I understand that it's referring to the Register size of the CPU. If register size is 32 bits it makes sense to have a 32 bit data bus to transfer the data. My question is, is the bus actually deigned to handle only 32 bits at a time? isn't just a wire? can't it technically handle more bits at once?
Lets say you were designing a Twitter client for people with people could see tweets and post tweets? How would you design the twitter api abstraction? Many of the api wrappers I've seen feature an client object that takes as input, the credentials of a user. Something similar to the code below: twitter = TwitterClient...
I am developing an app and I need to tackle a problem here. The app is kind of an e-commerce app where each user will be shown a list of items daily. The problem is, I need to keep a track of all the items seen by a user so that those items are not shown again. How can I do this? Approach I Maintain the ids of all the...
What's the reason behind making methods for database queries instead of allowing raw queries? for example get(...)->where(...). Guess1_ We're repeating ourselves otherwise(DRY) ---> I don't think this is a good reason because this way, it will still be repeated inevitably. Guess2_ By using methods we have the benefit ...
So I was recently given a coding assignment from a large financial firm, and I thought of two ways to solve the problem. One of the ways involved 1 outer for loop and 1 inner for loop. In this case, the code would be relatively easy to understand, and I saw this method as a more "obvious" solution. However, I thought o...
Javascript has the behavior where an error is not thrown on missing property access on objects, which is the cause of many pernicious bugs: console.log("iPhone".missingProperty) // undefined I'm wondering if this behavior is particularly abnormal for programming languages. Like the following will blow up in Ruby: puts...
If i'm writing my own kernel I will have access the the physical memory (instead of a virtual memory). Now assume I want to make a loop starting from the first memory location until the last one and set every byte to 0xFF. My pointer will start like this: unsigned char *firstMemoryAddress = N; What would N be? in embe...
I've read Defensive Programming vs Exception Handling? and if/else statements or exceptions, but none contain something relevant to what I'm searching for. Taking into account that exception handling is more computational expensive than just carefully designing your code and avoiding certain scenarios, I recently came ...
I've got the following state diagram that can be seen in Webgraphviz: digraph reload_states { rankdir=LR; size="8,5" node [shape = doublecircle]; Requested; node [shape = circle]; Requested -> Requested [ label = "Reschedule" ]; Requested -> Approved [ label = "Approve...
Let's say I want to have several types of output messages in my code. One of them is DEBUG, which is printed only, when the code is compiled in Debug mode. Usually I'd have to write something like #ifdef DEBUG std::cout << "Debug message" << std::endl; #endif which is pretty cumbersome and annoying to use in many ...
I have an object that wraps an Either<T,T[]>. It can only be either a single instance of T or an array of T[] but I don't know at compile time. What do I name the class, and what do I name an instance for example Either<string,string[]>? I want to describe it as short as possible. //class name SingularOrArray //too lon...
I have come up with a problem in my development and I have searched for correct solutions but have not found any. I am developing an application which lets users login with username and password. After making a login, the username is saved in SharedPreferences to retrieve it later if the user does any operation, such a...
GOAL: naming a class which has the responsibility to save data in Android database. The class structure is like this ClassName { public void saveSync(...){ /* implementation*/ } public void auxiliaryMethod(...){ /* implementation */ } } QUESTION: which is the proper manner to name this kind of class? S...
We have a REST API with an endpoint accepting JSON data from the client. One of the JSON fields is a URL that will be rendrered to other users as a hyperlink to a website page associated to the resource. Somewhere in the pipeline we needed to ensure the URL is valid (starts with http(s)://, contains a domain from a whi...
Goal: Prevent unauthorized 'clone' apps from using REST API-based solutions where the customers manage their own servers and services instead of the vendor doing so (database, resource, and identity). In other words: on-premise servers instead of a cloud-based solution. My company wants to be able to authorize only so...
Do N-Tier/Layered architecture really helpful with MVC? I have some projects here that use N-Tier architecture with MVC. The available layers are Entity Layer Data Layer Business Layer Presentation Layer Service Layer It does have some other layers like Common, Helper etc. but the above layers provides major function...
I've been working on an architecture, trying to learn more about DDD, layered architecture, etc. Here's what I have: Domain Here I have my entities, the classes that directly map to a database table. I have an Infra where I declared enums used by the entities, my UserManager and ClaimManager, and a few claims, such as ...
Recently I've been assigned to a new project to start with designing and visualizing business processes. Unfortunately I just can't wrap my head around this one, I understand what the client wants but I don't understand how to translate it to a proper design what technically spoken makes sense. The planning I came up w...
Let's say I have a TextBox in my View (in a Passive-View approach). Should it expose the TextBox object itself to the Presenter, or should it expose only the Text property of this object? Furthermore, what about a case when the presenter needs not only the Text property but also some other properties? For me, it seems ...