instruction
stringlengths
34
36.1k
So I'm trying to write a interpreter with a lexer. Currently, it adds a token line by line and does some more processing later on. But when I look at sources online, they all seem to go word by word or symbol by symbol. Is there a "correct way" to make a lexer or is tokenizing each line fine? EDIT: I realized I didn't ...
I have to create a reporting system based on hundreds of different tables in a database (which means a huge volume) and I'd like to know the best practices and/or your wild ideas about it. Here are the details: I have to generate many different reports, (around 50 report types are defined at this moment, but this numb...
Scenario: A very simple android app needed to be developed. It has just one screen with a list of items. Each item has a label and an icon. We fetch the item list from the server, and the server response contains labels and URLs of icons. ViewModel asks Repository for the list, the View observers the list reference in ...
I am new to DDD and I am trying model/design the aggregates of the following domain. The domain consists of several concepts: Assessment Models (AM) which contain Enabling Elements (EEs) and Focus Areas (FAs). EEs also contain Generic Processes (GPs). Assessments (As) which contain EE Sub-Assessments (EESAs), FA Sub-A...
We're starting to record history in an about 5 y/o internet system built with ASP.NET Core and SQL Server. Our current requirement is to save all records from a specific table, plus two fields from two other tables. We've tried using Temporal Tables, but since in some scenarios the user can change history records - tha...
I have a collection of opaque objects and related functions API. Such objects are typically created on the heap, but that involves a non-trivial amount of overhead. And when aggregate together, that adds layers upon layers of extra pointers and indirection. I would like to be able to compose multiples of those opaque t...
Have question on priority scheduling both in preemptive and nonpreemptive and wanted to make sure understand it correctly. (Higher the number highest priority) Process Arrival Time Burst Time Priority P1 0 5 5 P2 0 12 7 Since these processes come in ...
A time ago I participated in an interview process where I was tasked with a simple requirement. I created the best solution I could, using some lock-free implementation. I didn't pass the code challenge, and sadly I didn't get any feedback neither, so I never learned how the ideal solution would look like. I didn't get...
I am developing an app in which I have to fetch data through company provided APIs. All the authentication is done on their end, so I don't have to build my own APIs. However, There are some situations where they have some information, for eg: a new data entry notification, for us, for which they will hit an API provid...
At the end of this discussion about coupling and cohesion https://www.youtube.com/watch?v=hd0v72pD1MI some renowned programmers agreed in the general thought that to achieve high cohesion you have to join things, and to achieve low coupling you have to split them. This seems to be a common thought but I think is totall...
I've been developing .NET projects for the past 3 years, and on my recent web .NET projects, I've been using Partial Views for all the screens that contain Forms for Add/Update/Delete or other information (e.g. User Info). Here's a sample (not the exact code) of how I designed it. For example on editing a user: HTML - ...
I would like to create a dynamic appointment system between teacher and student to easily allow them to make an appointment. In this system, teachers select their 30 minutes time slot availabilities during the following 10 days. They can be available from 9am to 22pm. Then, students can see their teacher's time slot av...
When looking and Behavior-Driven development, "Behavior-driven development is an extension of test-driven development" (From Wikipedia). Researching around various articles, behavior-driven development is a form of TDD which is writing unit tests. At the same time, BDD focuses on business value, but not all modules pro...
FYI: I was asked to post this on softwareengineering - this question was originally posted on stack overflow, but they are a bit funny about broad questions over there, hence I was told to post here instead... I have searched stackoverflow for relevant questions and was surprised to find that I couldn't find any questi...
I have an Abstract Base Class AbstractModel class AbstractModel { public: struct predictionStructure{}; virtual predictionStructure predict(CompanyLib::Matrix<double> data) = 0; std::string modelType; public: //constants const uint32_t IMPORTER_VERSION = 1; protected: Preprocessor dataProcessor;//object ...
I am rewriting an old asp.net 4.0 web forms website that exposes an application's data and logic to the web. I am moving this to a .net core mvc or razor page project. The website has minimal formatting logic and some take-input-and-return-data logic. I am not using his logic because he essentially wrote a procedural, ...
As a Java developer, I just have scratched the surface of Javascript libraries like React, Angular, Vue etc. It seems that theoretically any web applications with server side rendering, like Spring-mvc with JSF, can be replaced by the aforementioned JS libraries those kinda totally decoupled views from the models and c...
I have a website-sideproject (Application Server: Django, Database: sqlite) with "search" functionality and I've recently stumbled over this problem. When you have a full-text-search-functionality, typically you have some kind of data-duplication going on. Typically this is by storing your original data in some kind of...
I have a simple setup where I've decided to reduce my overall OOP design and opt for lots of small individual components that I can add and remove from a particular object. The whole point of this was so components could be added and removed with out depending on other components - essentially they are decoupled. But t...
I maintain a CSS framework that is versioning with semantic versioning. What changes to a CSS framework are considered major, minor, and patches? Specifically, what is the "API" of a CSS framework? Is it simply the CSS classes available to you and how you use and combine them, or is it something more subjective like th...
I need some help with better kubernetes resource deployment. Essentially, I've 2 components. C1 and C2. My task is to not deploy C2 pods or any resources until the tasks which are running in C1 are finished. C1 will install some dars into server machine. --> this will take almost an hour to finish C2 is dependent on a ...
I am using C++ , but as far as I understand most OO principles are cross language. In most of the articles that I have read and liked about inheritance the advice are about : not to use it for the purpose of code reuse. inherit interface not implementations. use "interfaces" (pure abstract class ) as base class. pr...
I was doing a code review today and came across a change that, while it works, "smells" to me. Original code: if(itemStatus.equals(ItemStatus.Preparing)){ orderStatus = OrderStatus.NotReady; } and the modified code looks like this: switch (itemStatus) { case ItemStatus.Preparing: case ItemStatus.Ordered: ...
I have two interfaces: Camera and Computer. So far, each interfaces have multiple implementations in my codebase and they are loosely coupled (no implementations of Camera depends on any implementations of Computer and vice versa). Now I am interested to create a new class called DigitalCamera. DigitalCamera optionally...
I'm trying to get a grasp of the Clean Architecture. In the examples I found the typical solution structure consists of three projects: Core, Infrastructure, and Presentation/UI. The Core project must not have any dependencies. It contains the domain objects and business rules. The Infrastructure contains all external ...
Apologies for the title, I'm sure there is some well-known phrase for it but I don't know it. I have a solution for a problem, but I'm not satisfied with and am seeking inputs to help me improve it. Problem domain I'm working with an SDK for a third party database. To use the SDK I need to instantiate a "Loader" and pa...
Suppose I were to make two classes: class Databank { ... } class Dababase { ... } Based upon the chosen terminology, could one infer how one class would behave different compared to the other? And what are the origins of these two terms? Are there any historically significant examples of a "Databank"?
There is a bunch of books that state principles about good code (SOLID, DRY, Design patterns etc.) Those principles are solutions to some problems. An application of those principles could go like that: Approach 1: I know the principles ⇒ I will write code that respect those principles. The problem with this approach i...
I have an Angular + Django web application in which Django functions as my backend. In this web application, I have 12 different tables about articles, each table representing a different kind of article, which means they contain vastly different columns at times. They all have the fields creation_datetime and update_d...
History's first webpage is still online and functional. I was looking at its source out of interest and noticed that anchors consistently have a name attribute containing a stringified number, for example: <p> Everything there is online about W3 is linked directly or indirectly to this document, including an <a nam...
I am writing a timer-based scheduler to accomplish the task of informing a certain process of what to do and when. The Idea: Inform an X process of certain requests to perform at timed-intervals. So if the X process needs to perform an action every Y seconds, the scheduler should send the desired request to the X proce...
I'm thinking about this scenario: I can receive customer inquiries by Email. Those inquiries can be sent from existing customers or unknown "customers" - I'll call latter "Leads". When receiving an inquiry by Email from a Lead, a Sales Representative will need to register a new Lead in the Customer Relations Bounded C...
I would like to use a generic interface that has been implemented. I have two classes as such: class App { MainWindow<State> mainWindow; protected: virtual MainWindow<State> provideMainWindow() = 0; public: void exec(){ // Do something with MainWindow<State> } }; template<class StateType> cl...
I've been tasked with re-designing a system that is, for lack of a better term, complete spaghetti. For various reasons I feel that the system is well-suited for microservices. At a high level I feel that every service should... Function standalone Not have direct dependencies on other services Have a defined API to...
I'm converting an app to run on AWS Fargate and was going to use the Parameter Store to hold configuration values. Most of the information I've seen about it revolves around injecting Parameter Store values into the container as environment variables. Seems simple enough, but got me wondering about why you wouldn't ins...
In the context of a web application where we handle only one command per request in a stateless fashion, do we always have to load/save aggregates as one atomic unit? Why is it recommended not to partially load/save aggregates? What are the fundamental reasons behind this rule of thumb? Some references where I found th...
In the code sample below. Would UserId, Email, and UserType be considered "dependencies" with respect to the ChangeEmail method? would they be considered "collaborators"? Is it a condition for a member to be of a complex type for it to be considered either? public class User { public int UserId { get; private set; ...
I was invited to review some code. I've never done that before and barely know the project. Thus I'm following the README step by step. I log everything. The README says in its "Quickstart" section: docker-compose up -d This line raised "..denied..access forbidden.." which lead me to invest some reasonable time into r...
When it comes to exception handling, there are many guidelines and best practices on the web. On of them is to throw early, catch late, or even Don't Catch. So when facing an exception, the current use case would be abandoned by letting the exception bubble up, until some global exception handler catches it, logs it an...
I'm working on a chess game and have created a base class for game entities and chess pieces, along with an enum for the state of a square, when returned in a collection of possible movements: public enum MovementValidationResult { None = 0, Safe = 1, Attackable = 2 } public abstract class GameEntity { public bool ...
We have a handful of AWS EC2s set up for testing ongoing feature developments. I'm wondering if anyone knows an easy, automated way to keep track of which git branch we're testing on each EC2. Maybe with github hooks? For example, we might be testing with various internal departments: a new navigation menu on test1....
It is said that visitor pattern is applicable to problems where objects rarely change but we add actions on those objects more frequently. What if the objects are changing too though? For example we might have a NotificationSource class where it can have many children such as EmailNotificationSource or SmsNotificationS...
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...