instruction
stringlengths
34
36.1k
I was reading on this blog post about the for-if anti-pattern, and I'm not quite sure I understand why it's an anti-pattern. foreach (string filename in Directory.GetFiles(".")) { if (filename.Equals("desktop.ini", StringComparison.OrdinalIgnoreCase)) { return new StreamReader(filename); } } Quest...
I was reading a article about front-end development on Medium, when I stumbled upon an interesting piece of information, which is as follows: The type of a variable can be determined by using the typeof(var_name) function. One thing to note is that typeof(null) returns object. This is a long-standing bug in JS, bu...
A friend of my family asked me for a bit of help as he learns to program (in the C language). As we were talking, he expressed frustration about having a hard time understanding the error messages his compiler (GCC) is giving him when he makes errors. He does not understand all the terms used, and sometimes it's their ...
I am creating a dashboard. I obviously need to fetch some data. The problem is the data shown is based on user role. For instance: Administrator can see everything and columns that are fetched from database are x, y and z. Manager can see only rows for users that belongs to his region and columns that are fetched are...
My domain space is Java + RxJava but I think this applies to any reactive framework I have a stack that looks like the diagram below. Just for examples sake I'm describing a login flow but any UI --> web request --> UI flow would be the same. +-----------------+ | | ...
Is there any documentation that exhaustively lists the optimizations that the Java JIT can make? I can easily find articles with examples of what the JIT can do, but I want to make sure that it's not going to optimize away a password hash comparison and expose me to a timing attack. My code is loosely: Record record = ...
It's often convenient to hire a remote contractor for front-end development. Frameworks, like Laravel, use PHP to render front-end so it would make sense to give the front-end developer rights to edit PHP views files that render the HTML. I can think of two possible security risks: Can the developer use PHP to copy t...
Let's say a client need to get a list of products from somewhere. He does not care if that list comes from a cache, from a remote database, from a local database, from the resources or from the remote database that only returns item newer than 2 days. So I'd like to interface that behavior. How do I name it? I am missi...
I have been taught that with TDD, the tests "naturally fail first but it is a good habit to run them anyway to see the red light". Well, but I am quite sure a unit test written first for a new feature might actually pass, if such a feature is already implemented (and for example somehow inhibited). I am borrowing the f...
I build quite a bit of projects with a friend of mine, but we always come to the same pitfall over and over again. I know how to write PHP, Javascript and all that of stuff (I also know CSS and HTML) so I can do most of the work when it comes to building the actual functionality. However, he can't, but he can do someth...
I'm looking into system architecture and can't seem to figure out when you should create a subsystem/what deserves its own subsystem. Common examples I have seen include: Input Database Networking and User interface subsystems.
I have some code that looks like this: // Player.hpp class Player { public: enum class State { RUN, WALK, STAND }; }; The enum class State is used by the Player class, as well as by many other external components. This way every other component that needs the Player::State definition has to include the Player.hpp file...
This article states that: Consistency in CAP actually means linearizability, which is a very specific (and very strong) notion of consistency. In particular it has got nothing to do with the C in ACID The article goes on to define linearizability with: If operation B started after operation A successfully comple...
I've been thinking about the most optimal way to implement middleware in my web application and it got me thinking, how is middleware any different from events? Let's say that before a controller gets executed I want to verify that the IP from which the request is coming from is not blacklisted. Do I create a new middl...
I just want to improve this design, share your thoughts. Q1. I have specialized Splitter class based on monetary unit as "MonetarySplitter" and "NonMonetarySplitter". Whether doing so is correct? To check inheritance, I used to do "is a" check. It doesn't sounds good for me that "MonetarySplitter" is a "Splitter". Q2...
I'm in the process of writing a 8 bit cpu emulator and currently have a jump table for different opcodes. I want to move this over to be cycle accurate and was wondering what the best approach would be in implementing a microtable? I was thinking of something akin to the following: //PSEUDO static int (*microtable[][])...
Once in a while I’m stumbling on switch statements during a Code Review session. I would like to find a more elegant way of this code .... $istannceOfClass = $repository->loadFoo(); switch($istannceOfClass) { case $istannceOfClass instanceOf derivedClassAB: $istannceOfClass->callA(); $istann...
Please consider the following example (common in SaaS applications): This is a SaaS that deals with Widgets. You have an Account, that you authenticate via an API key. Each API key authenticates only one Account. You have several Widgets under your Account. A Widget belongs to only one Account and can't be transferred...
As I am only senior developer in team, Others are juniors who not strong to write clean code and architect. Problem is the during sprint planning, It took very hard time for me to lead technical decision during sprint planning because juniors doesn't have ideas to make any decision. Most of decision come from me with m...
I am trying to build an internet service that executes commands on the connected computers. Commands are initiated through a web-based dashboard. I currently have a REST API running with Laravel and the frontend dashboard application built out. I am getting stuck on how to connect the clients to the cloud service. Clie...
Maybe this answer already exists here, but I do not know if there is any technical term for that. I'm starting to develop in C ++ and as the program grows in size, it gets harder to move through the source code. However within the code there are several parts that are already 'solved', that is, I do not need to change ...
I was started programming in 6 months ago in college. I learned Python, C and Java. I want to create a project and using these languages. For example to searching part should use C because it's faster than the others. To design java etc ... How do you use different languages in same project? Is there any special method...
I am writing an application in python. The part I am little confused about is providing a little structure to my code. This is the basic requirement of my web application. I have these different end points: GET /reports/daywise. GET /reports/bulk_report_between_date_range. GET /reports/breakdown_by_age. For each of ...
I am currently in charge of designing the API of a new service. It started simple enough, 10 different URIs or so were allowed. I knew I was not doing the best code, but frankly I did not see a better way, since I lack experience, and since we are using AWS and API Gateway, I figured having less objects as is recommend...
I'm currently working on an application which uses compiler directives to vary settings between environments. Would it be worth refactoring these to use settings in the web.config which will be modified with the config transforms?
In order to better understand proofs, I am wondering if the following example will help clarify. Given the following JavaScript function: function log(a) { console.log(a) } My questions are: If it is possible to create a specification around this, and prove "correctness" to the specification. All the ways we can wr...
I am looking for the most efficient way to find the appropriate position of a geographical coordinate in a list of other (geographical) coordinates forming a route. That may sound a little cryptical, but consider this: Conditions I have the following data to work with: A list of (cartesian) coordinates describing a ge...
Can CQRS pattern exist and/or work without mediator pattern? I mean there are always commands and these commands have to be dispatched somehow to the handlers that perform some logic on them. Does it mean that CQRS pattern depend on mediator pattern in order to work? Every example I see with CQRS uses mediator pattern...
I am working on a RESTful, resource-based, API and I have a large entity (an account) with a lot of properties (30, we'll say). The account has a couple of properties that can be changed... Name: This actually submits a request (e-mail) for a person to confirm the identity and they use a separate system to update the ...
I've been struggling to grasp my head around the SRP pattern, because I dont know if it refers to a actor o to the use case. In the following case: To don't violate the SRP, would you need to create a class for every action (Maintain user, game, log on....) or a single Parent Teacher class?
I'm trying to build an application by creating an RESTful API(Koa.js) to communicate with clients(Web with React and Mobile with Ionic). But I'm facing issues when dealing with authentication. So my question is: How should I implement authentication in this scenario? It is ok to use just stateless token based auth or s...
We have Customer transactional table with multiple lookup tables with foreign keys. We want to create dropdown menus using these lookup tables, when CustomerService creates a Customer order transaction. If a person views the transactions later, they would see the 4 tables joined together. Would I create (a) 4 interfa...
I have been learning a lot of inheritance in C#. But am wondering if there are other ways that can be cleaner for component based setups. I have objects that are all pretty much the same but they have a unique behaviour tied to them, which i currently just override a virtual method. So every new component i'm making a ...
In an in-house solution I've been working on, I've been unable to understand the benefit of how interfaces are frequently implemented throughout the project. Which is as follows: Want to do CRUD operations on a database for a specific model/table? Make a view service. Made a view service? Make an interface for it. Vie...
In an Agile/Scrum development environment, where the "products" of a team are only consumed internally (think infrastructure, CI/CD tooling, automated testing), should POs exist even though the team's output is only directly consumed by other corporate dev teams? The client in question is a large enterprise, with an in...
I currently work for a company who builds web applications for businesses and entrepreneurs, typically 4-6 projects per year. We currently use Laravel/PHP which allows us to build apps relatively quickly with reasonable scalability, maintainability, security, etc. I dislike PHP as a language and since I have a strong i...
I understand you can generate an O(N^2) algorithm by using loops: eg: for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { //do something N^2 times. } } Is it possible to generate an O(N^2) without using loops (for, foreach, while, goto)? How would you do it?
In the SOA architecture, with many services that implements data persistence as well as basic logic - is there even a place for connection strings in client Desktop applications? Or should everything goes through the service? Does it change for Microservices?
Can someone please explain the last sentence of this paragraph about Distributed Version Control Systems: "Furthermore, many of these systems deal pretty well with having several remote repositories they can work with, so you can collaborate with different groups of people in different ways simultaneously within the sa...
This might sound as a weird question, but in my department we are having trouble with following situation: We are working here on a server application, which is growing larger and larger, even at the point that we are considering to split it into different parts (DLL files), dynamically loading when needed and unloadin...
I'm getting used to DDD so don't assume I'm a DDD pro yet. I'm trying to implement a hexagonal architecture using the CakePHP framework in a completely custom made application that just utilizes the framework but doesn't built something based on the app skeleton it has. CakePHP is using the data mapper pattern, not act...
Imagine a client-server architecture. The client calls some method on the server and that method fails. We want to retry. Which option is better design: The server tries calling this method again before returning a response The server returns the response immediately and the client decides if and how it wants to retry...
In some organisations, apparently, part of the software release process is to use unit testing, but at any point in time all unit tests must pass. Eg there might be some screen which shows all unit tests passing in green - which is supposed to be good. Personally, I think this is not how it should be for the following ...
I have a Python script which is responsible for updating SVN repository (in a nutshell) and checking it. Now I'd like to write some functional tests for the script. To check whether SVN update has been performed correctly, I have an idea for manual test scenario, to check at first revision number of a particular path, ...
I have been creating a POC for a part of our system but I'm finding some trouble communicating some of the ideas behind it. This takes ideas from Event Sourcing and Event Driven Architecture but trying to learn step by step. I thought I had my reasons and motivations clear, but to be honest, I don't find good arguments...
I have a FtpServerDataSeriesProvider that is used to provide data series from Ftp server files: public interface class FtpServerDataSeriesProvider { IEnumerable<DataSeries> GetDataSeries(); } It has several concrete implementations that are specific to the company that owns the Ftp Server, like: public class Comp...
Say I have the following 2 JavaScript functions for demonstration purposes: function colorize(integer) { if (integer === 1) return 'red' if (integer === 2) return 'blue' if (integer === 3) return 'yellow' // ... return 'green' } function max(a, b) { return Math.max(a, b) } The specifications are as follow...
I have a single page app (Vue JS) that is built and released as docker image. The docker image is based on the official Nginx Docker image and serves the SPA as static content. Until now, there was only a single non-development deployment of that SPA, so the URL of the back-end API was hard-coded in the production buil...
I've just finished reading Scott Wlaschin's excellent book "Domain Modeling Made Functional: Tackle Software Complexity with Domain-Driven Design and F#" in which he uses the F# SQL type provider for the database access. Anticipating the obvious question, he says (p260) not to use an ORM because you can't ensure the in...
Just read my first book on DDD ("Domain Modeling Made Functional: Tackle Software Complexity with Domain-Driven Design and F#" by Scott Wlaschin in case it makes any difference), and came away with the distinct impression that DDD is great for batch processing, but not necessarily so good for other things. His example ...
I have several apps witch build from one code base (using common modules). And my question: how to write composition root in this case? Let's imagine simple dependency graph: ClassBase --> ClassBase1 --> ClassA | --> ClassBase2 --> ClassB 1) First guess is to have one big composition root with all dependencie...
A couple of readonly variables will be used. Almost all of the classes will be using those variables. Either I place all of the variables in a separate internal static class or I pass them on repeatedly in all the classes' constructor parameters. What would be the better of the 2? Performance-wise only please.
Do all non-functional requirements need a specific metric and measurement? Would a NF maintainability requirement such as: "Upgrade to a new software version shall leave all database and personal settings unchanged" be correct? Would a metric and measurement need to be added? How would a metric and measurement be add...
I am experiencing a dilemma. Let me explain it with two functions: # Takes vector.magnitude(), vector.x, vector.y and uses it somewhere def func1(vector, {other parameters 1}): pass # Takes vector.magnitude(), vector.x, vector.y and uses it somewhere def func2(vector, {other parameters 2}): It is not uncommon tha...
There's a design pattern of sorts that I've thought about but haven't seen implemented where every function / method passes around a permissions object. I'm wondering whether using it in a project is a good idea or not. The key ideas here are that 1) capabilities are only ever taken away, not added (unless you're in so...
I'm new to Git and SourceTree tool. I don't understand why this happens? My steps: 1. Create new brand, named develop/john/LinksMiddleware/new 2. Stages changed files, for more details there're three files. 3. Commit => Expected: In new brand only contains three staged files in step 2th above => Real result: In n...
We are planning to build a SPA in Angular 2+, which will use ASP.NET as a back-end. Since Angular doesn't really have a good integration to ASP.NET, we decided to create the SPA as a standalone application, which will be communicating with the WebAPI. The first popped up question although is, how to keep the HTML templ...
Say I have a method A which calls a method B and does one additional thing. The B method behaves differently in 10 different cases and I have a broad unit test describing it. And now I want to test my method A. What is the best practice to do that? Should I run the same test with all 10 cases for method A to make sure ...
In teams, when should one get the latest versions of the files in source control in an optimal workflow? For example, should it be right before you commit? Or every morning? Should it be automated? In my current team we have no guidelines about this, occasionally leading to situations of e.g. people not being able to b...
A question came to the team and I'm asking you guys. Our application uses MVC with service layer. But sometimes our service layer just call the repository, without doing nothing Our questions is: in this cases is it ok to call the repository directly from controller? For example: let's say a controller that call servi...
So, let's say I have a standard set up for application, that is: - split into micro services - and is running in a cluster (kubernetes or docker swarm, I guess specific implementation does not matter, just the main idea), - there's a API gateway, that faces internet and authenticates all the incoming external requests....
I am trying to design the DB schema of my new project and I need some suggestions. I am thinking to have one extra column for some tables which is a UUID. I wanted mainly for tables which contain data which are accessible through REST, so I don't want to expose the primary key. My concern is that when I want to update...
I am trying to design the DB schema of my new project and I need some suggestions. I decided to create a lookup table in order to save the enumeration values. So I have a table Status with these columns idstatus, statusName, statusCode. My question is, do you think that is a good practice to follow this way? Imagine ...
I've been trying to figure out what this certain UML symbol means. It is only used in design diagrams (as far as I know). I've got UML distilled (3rd edition), but that too doesn't explain what this is. Searching around the web gave me some meager results as well. Does anyone know what this particular associatio...
I need to collect user data every few seconds where each user is unique. I've done some research and concluded that I should consider my data as time series data because I'm looking at how user behaviour changes over time. I want to use DynamoDB and in its best practices for time series doc, it describes creating a new...
I have several but independent computer vision pipelines which were original planned to run by a user via a cmd (task1 -> script_1.py, task2 -> script_2.py and so on). All pipelines share some code (e.g. resize an image) but otherwise the entire procedure inside the pipeline is different, for instance some problems are...
Here's one example: My web application contains draggable elements. When dragging an element, the browser produces a "ghost image". I want to remove the "ghost image" when dragging and I write a test for this behaviour. My problem is that I initially have no idea how to fix this bug and the only way I can write a test...
You can create a data structure such as a Parsing Expression Grammar (PEG) that will be used to parse: string -> object You can then write a function that iterates through the object's properties and serializes back into a string, or will stringify it: object -> string I haven't seen any data structures for defining ...
I’ve been interacting with a very early stage startup founder (no funding, just a simple site w/some visitors) and have offered to build out a microservice that helps automate some currently-manual tasks as a sort of proof of usefulness and general competence. This is completed and working as promised (I control the d...
I have developed a program to read through text in files and capture information, and write it into a CSV. Each "field" is identified by an index, a label, and a value, like so: .0 index .0.label unicode "Area" .0.value unicode "6WAY DB" .1 index .1.label unicode "SubStation" .1.value unicode "E782DB257" ....
It is my impression that in software engineering, a connection can mean many things depending on context and the level of abstraction at which some system is considered. I'm surprised no one has asked this before, as I feel that a connection is such a fundamental concept, but also very easy to misunderstand. I want to...
I have a piece of code that can be represented as: public class ItemService { public void DeleteItems(IEnumerable<Item> items) { // Save us from possible NullReferenceException below. if(items == null) return; foreach(var item in items) { // For the purp...
Eg: Assume a task has been estimated to take 8 hours working time, for 1 person to complete. Supposing that person takes a break of 15 mins every 2 hours. Obviously the task will take 1 hour extra and, assuming an 8-hour working day, will now be completed only the next day. Therefore, 1. Should breaks also be entered i...
In the following scenario: A factory returns an object of a logic class: ILogicClass object = factory.GetByRequirements(reqs); I then want to invoke a method and get some results which are in the same shape for all concrete logic classes: output = object.GetResults(...) and then use the result. Imagine the concrete i...
This is a simplified version of a problem I'm facing in my current project. Let's say we want to display shapes: rectangles, circles, etc. I'll have a Shape class which is subclassed by Rectangle, Circle and so on. I'll then have a World class which represents a 2d plane containing shapes at various coordinates. I'll a...
What naming convention should use when I have a method with an out parameter. I want to do this using clean code principles. So is it a good practice to include the name of the out parameter in the method name? I want to write a couple of methods like this in which I use one of them in another method. And I want to be...
I faced the problem bellow when I designed our new app. We are thinking to have one extra column for some tables which is a UUID for security purposes. So, there are two different solutions. First is to have an extra column (UUID) on top of primary key which is a serial. In that case you need some more calls just to...
Languages with coercions (i.e. implicit type conversions) allows expressing things like that (irrespective of any syntax): f : int32 → int32 = λx.x+x a : int16 = 42 b : int64 = f(a) Where type conversions are not explicitly indicated in the code. Type checking relies on: int16 <: int32 <: int64. Is there a programming...
Most examples of auto use the = operator. #include <iostream> int main() { auto a = 1; std::cout << a << '\n'; } Why don't they use the uniform initializer like this? #include <iostream> int main() { auto a {1}; std::cout << a << '\n'; } Is there any advantage or disadvantage of using one syntax ove...
I'm working on a web application with constantly changing requirements. The relationships between entities in the database have mostly remained the same but the attributes of each entity type changes a lot. I'm using Java, JPA, and Postgres. Postgres has a JSON type. Is it a good design to remove all non-key and foreig...
lets say I have several objects Object A,Object B,Object C in different parts of my project. I have defined a Object X that is only used to store some specific values from the objects mentioned above plus some other context data, only getters and setters functions, and pass it on to another layer or service. What would...
Knowing that BDD somehow avoids using the term "test", I am trying to understand the process as described in a book called The Journey to Enterprise Agility: Systems Thinking and Organizational Legacy. They describe the BDD process like that: Select a scenario from a feature Write a failing scenario step Write a faili...
I am an Electrical Engineer now training and working as an embedded software developer, so I have little formal computer science and software design training. I have until a few months ago only worked in C and functional programming, but started recently working with C++ and OOP for Embedded Linux with a team whose dev...
In university, at our algorithms courses, we learn how to precisely compute the complexity of various simple algorithms that are used in practice, such as hash tables or quick sort. But now in a big software project, when we want to make it faster, all we do is look at individual pieces -a a few nested loops there that...
I'm hesitating between algorithm and implementation as most of the questions here on how to prevent coupling between implementation and tests are about using spies/stubs or mocks. The typical problem is that the tests are merely mirroring the SUT because tests are focusing validating behaviour instead of state. The cou...
I have a Product entity with a Category value object (contrived example). There's an API endpoint /products?category=Keyboards,Mice The classes at play here are the: ListProductsController (interfaces layer) ProductsRetriever (application layer) ProductRepository (domain / infrastructure layer) Product (entity / aggre...
In our organization, we have several databases. Each of them has lots of schemas with tons of packages, procedure, functions and so on. Now, I wonder what approach is best in terms of organizing those objects in a git repository. Should I have repositories based on schemas or application they're used by? There are lots...
I have a class that contains an object (set in this case). The set is modified by the standard function operators __add__ and __sub__, but I also want to explicitly expose a method of getting this set. Should the @property decorator be used instead of a simple get() method, even if there is no intent to allow setting ...
[Node.js / CommonJS] I'm creating a single GitHub repo for my tool which has a Core, Control, Server, and Client library. It's unlikely that all of them will be used at the same time. I'd like my fellow coworkers to require one entry point for all four libraries. So I made this questionable implementation: exporting th...
I'm developing an application with Python. I want to have a Boolean variable that represent whether something is buy or sell but I'm not sure how I should name it. Here are my current ideas: isBuy isSell buy_sell sell_buy buy1_sell0 actually I like the last one the most although it's somehow the ugliest because it te...
In Typescript/Angular 6 (2+), is it considered a good practice to have a base abstract http service from which derives all the application services? for example: //import the angular Http ...etc export abstract class MyBaseService{ ... protected get<T>(url: string): Observable<T> { return this.http.get(...) ...
What is preferred and why? void PrepMyInstantiatedObject(SomeComplexDTO someComplexDto){ someComplexDto.Name = SomeOtherClassHelper.DerivedName(someComplexDto.Name); someComplexDto.Ids = SomeOtherClassHelper.Resolve(someComplexDto.RelatedIds); someComplexDto.SingleId = SomeOtherClassHelper.FindId(som...
Have read about "Repository pattern", before it, I have used pattern DAO (data-acess-object). How should I implement table relations with this pattern? Should I create entity for links between tables? Thank you!
Given the need to log only in debug mode the easiest way would be to use if conditions: def test(x, debug=False): if debug: print(x) # ...Some more code if debug: print("Something else") # ...More conditional logging return x * 2 This leads to the cluttering of the actual functi...
This morning I had a presentation on PHPSPec which the official website describes as follows: A php toolset to drive emergent design by specification. As defined within an adjective context the word "emergent" is defined as follow: the process of coming into being On the other hand PHPUnit is said to focus on quick...
I had been learning python and i know Java. if i were to write a simple program, can i write both programming language in one document or compiler? I got into this problem because if i cannot merge both the programming language , what is the meaning there to learn them. Another reason for this is that; I found some co...
Do logging impact application performance? First thing to know is , whether logs are written serially as processing takes place or are logged into file i a separate process? In java world how should I improve performance of my application where I need to log a lot in that case? Micro optimization is a side effect but...
When testing RESTful JSON APIs with ATDD/BDD practices in mind is it good practice to test the structure of the response? I'm thinking that it could too easily change, thus making for a brittle test. If this is true, then how should one approach testing REST API endpoints? Perhaps only test the status codes?
As always I came here to ask for some light in a design issue I am facing. I have a system that issues some notifications : PackageReceivedNotification PackageSentNotification DisccountAvailableNotification More in the future I want to store the text of them in the DB in multiple languages (imagine english and spani...
Currently, we've been working on the architecture team on defining the database models. What has been troubling me is my superior's advice when it comes to working with audit fields. He advocates for the updated_at and updated_by fields to be Nullable, reasoning that these should be initialized as NULL because the data...