instruction
stringlengths
34
36.1k
(Assuming a single-threaded environment) A function that fulfills this criterion is: bool MyClass::is_initialized = false; void MyClass::lazy_initialize() { if (!is_initialized) { initialize(); //Should not be called multiple times is_initialized = true; } } In essence, I can call this fun...
I want to make a social game for Android. I am using NoSQL Based Database (MongoDB) and I am using NodeJs. I am using Android-Volley library to make POST and GET requests. But I am stucked on something, I need to see friends of friends or send some game requests or friend requests from one user to another. However, I a...
As defined in the documentation of the gamma parameter for Tree Booster: Minimum loss reduction required to make a further partition on a leaf node of the tree. The larger gamma is, the more conservative the algorithm will be.
I'm writing a reader for the custom binary file format used in one game. The format has multiple versions for example: struct FileHeader { ushort version; uint fieldX; // version 1 uint fieldXX; // added in version 3 uint fieldY; // version 2 uint fieldZ; // version 4 } The problem is, different versio...
When I was a beginner it took a while to learn the language syntax and the idea that languages couldn't improve after they were invented. But now we're seeing new language features added every year with ES5, ES6 the so on. If I don't write software for a few weeks or months when I come back to it I have often found f...
So the scenario is that I'm asked to redesign and refactor a REST API by combining multiple endpoints that do similar tasks. For example, now I have 10 different endpoints that are all used to upload different resources e.g.upload_job, upload_script, upload_action, upload_sound ... The main idea is to reduce the number...
Context: I recently found out about Semantic Versioning, and am trying to determine how to best use it practically for my own projects. Given that semver takes major changes, minor changes, and patches into account for versioning, when should a commit not be tagged with an updated version? It seems to me that every cha...
I am dealing with C++ code that I want to model it as component diagram (UML2.0). So, a main step is to realize which parameters are input & output signals. One problem with that is: Not every parameter has to be an input/output signal, because it can be passed from or read by an external function in other module. An e...
I found a great project on github with a useful central feature but which is rough in the "polishing" of error handling, logging, config, and setup. The project is 5 years untouched, and only a couple hundred lines of code. Still it's useful enough to have brought itself attention for a decent number of watchers and a ...
The codebase I'm working on frequently uses instance variables to share data between various trivial methods. The original developer is adamant that this adheres to the best practices stated in the Clean Code book by Uncle Bob/Robert Martin: "The first rule of functions is that they should be small." and "The ideal num...
I am trying to refactor a huge chunk of our software, and it requires to set up a factory. However, I am not sure where lies its responsibility. (PS: The code below is shown simply as an illustration and may not be perfectly designed, please do not unleash hell on it :() Should the factory only return the correct inst...
I am writing a gui that is supposed to replace a fairly large shellscript in order to make the usage easier for not-so-technical people. The script calls a certain program (saga_cmd) multiple times with different parameters, i.e. saga_cmd grid_calculus 8 -GRIDS "TriGridResult.sgrd;TpiGridResult.sgrd;SlopeResultGrid.sgr...
In UML sequence diagrams, given two objects A and B, if Object A sends a message to Object B. Does this mean the message is a method in Object B which is invoked from Object A?
A colleague, and frankly better software engineer that me, is telling me that this pattern let variable = someDefaultVariable(); if (some_boolean) { variable = someOtherValue(); } is better than this pattern let variable if (some_boolean) { variable = someOtherValue(); } else { variable = someDefaultVariab...
A SW-Component "SWC-A" is integrated with a SW-Component "SWC-B". The SWC-A has an output interface which provides "Distance in meters". The SWC-B receives this value and does some calculation. If in SWC-B interprets the received value is interpreted as "Distance in Feet" and not in meters. How can this scenario be te...
Let's assume, that frameworks I use, provide some kind of dependency injection automatically available in testing environment. Let's also assume, that I have a lot of micro services in my application. Testing each of them separately in ideal unit tests scenarios doesn't bring too much value to me. It is usually because...
I was just studying the interdependence of state and behavior exhibited by the state of an object and its behavior.was wondering if an object can have behavior without having state. Because i am very sure that the other way around is very much possible
This came up when a developer brought in these planning poker cards, one of which is Yak Shaving. There are various articles on google/wikitionary which basically say: Yak shaving is programming lingo for the seemingly endless series of small tasks that have to be completed before the next step in a project can move f...
I am trying to understand UML class diagrams. Imagine two classes that are related with each other by association. What is the difference between {ordered} and {sequence} for the association?
Do you think its a good OO practice to use parts of an object to build itself? Here is an example. var car = new Car { Make = BuildMake(), Model = BuildModel(), Vin = BuildVin(), }; car.Wheel = BuildWheel(Car.Vin); In the case above, I had to move the wheel out of the initialize ...
First of all, C# solutions are needed. So in my team I am responsible for creating a program that will receive a "task" in json format from an API, from this json it needs to figure out what website to create an account for, for example: wordpress.com weebly.com whatever.com Now, each of these sites will have separat...
I am in the process of building an heavily data-driven web application written in Node.js / Typescript with Mariadb for the database engine. I am trying to put an emphasis on extensibility and DRY principles. One thing that I've come across that is repetitive and time consuming to write code for is data validation. So...
I understand OCP in SOLID can be applied when we have same set of interfaces defined via abstract type, so that we can have varying implementations of those interfaces via concrete types. For example, I have my business logic working with IRepository with defined set of operations: interface IRepository<T>{ void save(T...
I understand that in OOP languages like C#, it is generally viewed as bad practice to create utility classes, and it's preferable to put methods in the classes in which they will be used. To that end, I wanted to create a transpose() extension method for double[,] types; however, it told me that extension methods must...
I have Facade class which requires an Endpoint instance to function (it uses it in most of the functions). Endpoint is attached to Platform that is passed in Endpoint's constructor and has to be started (Platform.Start()). Both Platform and Endpoint come from external library and use Start/Stop pattern. Before Facade i...
Let's say I have a react component like this: const MyComponent = ({data}) => (<div>{JSON.stringify(data)}</div>); const myReduxSelector = (state, id) => state.someData[id]; export default connect( (state, ownProps) => ({ data: myReduxSelector(state, ownProps.someId) }) )(MyComponent); Now this work...
Default docstring from PyCharm automatically creates template with Args: and Returns: sections. However I have observed that this prompts people to say obvious things, frequently just stating the variable name without underscores (if name was chosen well). My first external source was the source code of mypy, a project...
Just like the title says, I want to use the pipeline design pattern for chaining related API calls. The context will store the data that will be used to create a payload. For example, I have the context object, a map of some sort, contain a "raw" data. First in the line is a formatter handler that formats the data i...
Is it typical that a Product Owner (or even a BA) creates a high-level prototype/wireframe of a system based on the requirements document to ensure that the requirements are clear enough to start working on user stories for the UX & development teams? I am currently being 'promoted' from a developer to UX designer and ...
I'm designing an API for a stream-processing library. The library will process a stream provided by the user and will transition between states based on the data in the stream. The state transitions are indicated via a callback. But I want to be able to have the user force a state transition as well. In this case, shou...
My younger brother has made a small rock, scissor and paper python game running in console. I want to host it on my own domain, running on a digitalOcean droplet. I have no more experience with python, than knowing some syntax and use-cases. I guess it is almost impossible to run python code in the browser, so my gues...
While coding I stumbled upon something like this (extremely simplified example): public bool Func() { Object[] array = new Object[] {false, false}; return array[0] != array[1]; } I was fooled thinking it would return false, but it instead returned true. It did that because of C# comparing two Object references...
I am currently trying to create a web application, that saves inbound emails. I have figured out how to save the incoming emails into my database, and I have all the email information available (headers, body etc.) I want to be able to allow my users to set custom conditions for each of the email inboxes they have. So ...
"The ideal number of arguments for a function is zero" is plain wrong. The ideal number of arguments is exactly the number needed to enable your function to be side-effect free. Less than that and you needlessly cause your functions to be impure thus forcing you to steer away from the pit of success and climb the grad...
Context: Suppose the current way to update a person is to use HTTP PATCH, where you can set the firstname and lastname: { "firstname": "john", "lastname": "doe" } And you want to add an extra optional field birthdate to the person. There is no problem for the GET or PUT (as it's optional). But can it be added to ...
I'm looking for advice on what a good branching strategy looks like when using mostly open source code. Most of my dev experience is with writing and working with custom made code and only using open source libraries so I'm a bit out of my dept here. The aim is to use an open source application and make mostly minor an...
Say I have a customer class class Customer(name, age) somewhere in my code, I have a list of customers List[Customers] at some point, I need to transform this list of customers into a Map with Key = age, and value = List[Customer] like below Map 15 -> List[Customer] 21 -> List[Customer] 33 -> List[Customer] Though ...
Trying to better understand how to write specifications for automated theorem proving and testing, etc. One seemingly simple example is generating a random number. I would like to know how to specify this behavior, that a function rand() returns a "random" number. It is straightforward to say it returns a "number", as ...
According to Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?, I should split long functions into smaller functions even if they are used once only, but my question is , how should I call the extracted functions? Style 1: centralize them callFunctions(){...
coalesce definition in Cambridge Dictionary: If two or more things coalesce, they come or grow together to form one thing or system. to combine into a single group or thing But in MySQL, coalesce means: COALESCE(): Return the first non-NULL argument As an ESL(English as Second Language), That confused me a lot....
I'm building a paid feature for my application & the clients who haven't enabled it won't have access to it While building all the API's around it, I see that I'm doing a lot of permission checks in every API (whether the feature is enabled for that client) My question is, should I really bother? The reason why I say s...
A1 |__A2 |__A3 |__A4 |__A5 B1 |__B2 |__B3 |__B4 |__B5 C1 |__C2 |__C3 |__C4 |__C5 Given a list of A and a list of B, we want to "join" the two and put the results into C. The join should include everything from A and B, and indicate with a derived field ...
I have been trying to learn more about MicroServices architecture and I am using Microsoft's eShopOnContainers as a reference because I am familiar with .NET. I am getting into the part about testing, but I noticed that all the tests in the service API folders are referencing the WebMVC project and not the Service.API ...
It used to be fairly common for people to call a getter, do some calculation on it, then call a setter with the result. This is a clear sign your calculation actually belongs to the class you called the getter on. "Tell, don't ask" was coined to remind people to be on the lookout for that anti-pattern, and it worked s...
Our small team writes desktop apps using WPF + Prism. Most of the team members are not so familiar with professional software developing process. I'm trying to adopt some agile techniques to make the existing process more professional and bring more quality to our products. The one of basic conception of the agile proc...
I know some languages (C comes to mind) its best to declare as few variables as possible. In a language with memory management like C# is it better practice to continue with this philosophy or should I be declaring unnecessary variables if it improvese readability? Ex: Declaring unnecessary database and server varia...
I am not sure if this is the right place to post this question, but I think this might be better suited than Stack Overflow. I have got an online application, a Java EJB application. Requirement is to have an external configuration file which will contain property using which the application is going to decide whether...
A function that is repeatedly called should do multiple tasks: request a vector from a server. calculate a new vector. send this latter to a server. append the new vector summed to the downloaded one to a FIFO buffer. Currently, the code that I have implemented starts two new threads inside that function, and wait fo...
Let's say I have two domains: Customers and Jobs. Customers is responsible for knowing what customers a user has access to. Jobs is responsible for knowing what jobs a user has access to (by referencing which customers it has access to). This means that Jobs technically needs the User:Customer association data from Cu...
Say we have the following image (which is about Linux): Can we call the file systems boxes that are shown in the image (ext2, msdos, and minix) "file systems drivers", for example can we say that the ext2 box is an "ext2 driver"? The reason I am asking this question is because the ext2 "driver" is not itself accessing...
We have a .Net 3 tiered app that wasn't designed to scale horizontally. I've heard we can use docker to containerize our app and then put it on kubernetes. Is that enough for kubernetes to make it scale horizontally, or do we have to re-engineer our app?
For example, sometimes I need a float variable to be used inside a for loop, e.g.: float sum=0; for(int i = 0; i < students.length; i++) { sum += Math.random(); students[i].result = sum; } I feel uncomfortable that sum is accessible outside the for loop even it is used inside the for loop only, and my using la...
I'll ask this question this way - what are the software engineering concerns for not implementing my REST API the "right" way? What do you mean the "right" way? Well, allow me to explain my perception of the right way, then I'll tell you how I am doing it (also, assume I am talking about a JSON REST API). The right wa...
Shown in the image below is an example of an actor that can perform an action and this action branches into several options (none of them HAVE to be performed). My question is whether the arrows coming from "Manage my events" should be "include" or "extend". In other words, is "include" or "extend" more appropriate if ...
Let's say we will not use distributed caching because we want that our microservices are independent and they do not have many single point of failures. Either we will have in-memory cache (simple hashmap in every microservice instance) or we will have one REDIS per service kind. If the service A needs some data from t...
I have several handlers classes that implements same interface and factories to create handlers. Handlers: public class Handler1 : IHandler { private readonly IService1 _service1; private readonly IService2 _service2; private readonly Handler1Data _data; public Handler1(IService1 service1, IService2 ser...
I am busy with a score keeping app. And would appreciate suggestions/ help. I will try to be brief and hopefully have explained the main gist of the app below The app basically maintains some scores. The way they are set-up is using scoresheets. Basically a scoresheet contain the name , the count (no of occurences), an...
I am still learning Design Patterns and I have a situation in my hand. I am developing a simple employee management Python program. An employee can be a Developer, Senior Developer, Lead Developer, Manager. Now during the tenure employee may get promoted and thus a responsibility change happens with same employee. I t...
Some time ago when there were no ASP.NET-Core hosted-services the choice for a service-type application was pretty clear, it was a Windows Service. However, recently I've noticed that at least some people misuse hosted-service for this purpose. I've seen applications that had absolutely no REST API whatsoever and were ...
My company works with different developers from different studios, always sharing the code to everyone aboard. At the moment, we need to protect a part of the code, not from theft but from some random developer in the studio maybe changing something important by mistake. Is there a way to protect a critical part of t...
Note: I wrote this question in a way that made it seem I'm mainly concerned with the memory usage and ways to optimise this. Rather, my original intention (and my current intention, upon revisiting this question) is to ask for solutions to the maintainability problem: the fact that one has to make sure that a correspo...
I'm learning about Binary Trees in school and I'm trying to apply the SOLID principles to it. My problem is in my BinaryTree::insert() method I'm creating a new BinaryNode, and from what I've understood that's bad dependency direction because higher level abstractions (a tree) should not depend on lower level details (...
I have a few models which need to be linked together during a workflow on my webapp and I'm having trouble thinking of a nice abstraction for the api. They are represented as individual constructs on the backend with their own CRUD methods that can be hit individually, however when the front-end saves a model it has to...
Apologies for the title, perhaps someone can suggest a better way to summarize my question. Let's say I have a task/checklist application. On the front-end, I create a task. The eventual result is that the task exists in both the front-end and the database. I have these 2 approaches: I create a task in the front end b...
I've been trying to decide if I should include getters/setters in business entities. A few reason I have been through to include getters/setters but those are accompanied by an anti-reason as well. Find them below: Insurance policy for type change: First it is extremely rare. Secondly, we can always add a new method ...
I come from OOP pradigm and I also know a bit about functional programming and its advantages. Over time I came to like the separation of data and transformations that are applied to it using pure functions. While I like the OOP idea of encapsulating data and the operations you can perform on it using classes I also st...
I am making a program using Java todo colo quantization using mean shift clustering algorithm and the image is RGB with resolution of 512x512. I want to reduce the image file size by reducing the total color in the input image. I have a problem with defining the bandwidth for calculating the euclidian squared distance ...
I am unsure, if I understand the principles of REST completely. The idea behind it is (according to e.g. Wiki and other sources) that data is transferred via HTTP(S) and addressed via URIs. Depending on the HTTP method used different operations on the underlying database are performed (CRUD operations). The glory detai...
I am looking to build an web-application which would allow user to upload csv file - see preview of few rows in the file and then apply different cleansing and standardisation rules. For example the user can choose a telephone column and click a standardise button to format the phone numbers in a particular way. He ca...
There is a scenario, where we have two commercial applications that are so called REST based(java) but not HATEOAS compliant. Development activity is out-sourced to vendor Development phase of project is done and planning for functional testing. We preferred in-house technicians for testing phase to perform functiona...
I have a few questions regarding the three architecture patterns mentioned in the title. I'm having a little trouble trying to understand the advantages any one of them has over the others, especially the first two. So I'll start each one off with a description of what I understand so far and then I'll ask questions be...
I am writing a simple chat using Node.js, Websockets and Vue.js. Specifically, I have a Vue instance and a Websockets Client. When a user presses a "Submit" button, Vue asks the Client to send a message to a Server. When the Client receives a message from the Server, it asks the Vue to render it to the page. My first t...
I am working on creating iterators, for strings, lists, trees, graphs, and potentially other things. First a side note. I have a string data type in my engine. The string is implemented as a bunch of small chunks separated physically in memory, let's say 256-byte chunks. So a single string might look like this in memo...
Here's my dilemma... I need to provide a rough order of magnitude estimate for development time of a system that we know the requirements (story map created) however we don't yet have a technical team in place to do the work. The issue is this, before hiring the team, management wants to know how long it will take to b...
By that I mean, forming a Hash Array Mapped Trie with 2 or more indexed fields, such as a User model by email and location name, or email + username + last logged in + isActive. Basically any arbitrary number of columns of any type of field (boolean, int, string, pretty much). I am just learning about HAMTs, but don't ...
Objects.requireNonNull is a helpful method to spot NullPointerExceptions effectively while developing. But in fact it's throwing a RuntimeException which could crash the application (the worst thing ever in production). Which brings up the question - is it safe to use this method on production or just in development?
I have multiple web services that need to be integrated into one solution. One frontend would provide access to features from all services. Each of the services has its own native authentication, and keeps its own users' data. Services don't support OAuth or SAML. What I need to achieve is that when a user gets logged...
I am working on trying to understand HAMT and now am uncertain generally what to do when you run into a conflict in a hash. All I understand so far is you create a list to append the keys to, but I don't understand any deeper. I would like to know (ideally for the HAMT case, but any hash would do) how you resolve confl...
I am trying to understand how functions -- which could have dozens of parameters that could themselves be functions or complex objects (I'm thinking JavaScript) -- get passed the arguments when compiled. I have seen before simple examples like this in C, which shows: foo(1, 2, 3); getting compiled down to: push $3 pus...
In JavaScript I want to create a log function: function log(string) { console.log(string) } Obviously this causes side effects; it prints to the screen. And I have no control over its implementation. Basically, I just trust that it works. But I wonder what I can do to incorporate something like this into a formal ve...
Suppose I am doing an if-else clause inside a for loop. I like to structure it as for (...) if (...) // (part A) continue; //(part B) rather than for (...) if (...) // (part A) else (part B) but I can imagine that coders might have strong opinions on this. Is there a ...
I have one website and the website are now in HTML, that actually is structured: domain.com = English domain.com/es = Spanish domain.com/de = Germany I copied the HTML of English page to Spanish and Germany and I edit the Text, sometimes when I want add some extra code on English, I need open the Spanish, Germany and...
We have a Git Flow type workflow (in rails) where our 'testing' (aka develop) branch has feature branches merged into it for UAT. So: master has the current running production system. feature branches have a single feature (against a pull request) testing has a number of features that are in the development cycle Cu...
For example, I remember most examples of dependency injection I see is something like this: public interface Fruit{ } public class FruitBox{ public Fruit fruit; public FruitBox(Fruit fruit){ this.fruit=fruit; } } which can supply different types under Fruit from outside. But my question is, if one...
We have an ecommerce application which sends out transactional emails to customers for events like order placed, order shipped, order delivered etc. We used to send one bcc of every email to a gmail address to keep record. But due to large volume of emails, we are facing two problems: We need to buy storage from gmail...
From what I understand from the 'Clean Architecture', the controller determines which usecase to execute dependent on the input of the user. If the input from the CLI for example is invalid, the controller already knows that something is wrong, so that the controller could directly talk to the presenter in order to sho...
I've made a simple login form. It's made very generic to be used for any project. Now I wonder if the security is good enough and if my approach is safe. On success When successfully logged in I do two things. I set a cookie with username and hash (sha256). I also write a temp file to the server with the username and h...
I know this can be very use-case specific, but I find myself wondering this far too often. Is there a generally preferred syntax. I'm not asking what is the best approach when in a function, I am asking should I exit early or should I just not call the function. Wrap if around function call if (shouldThisRun) { runF...
I'm trying to find the longest word in a given text, but it has to be done "old school": without using split, enumerate, etc. (I'm using Python but what I'm looking for is more of a pseudocode or a general algorithm). I'm struggling with the last word (or the last character). As a precondition, there are no leading or ...
Lets say someone has written code for multiple companies that have then copyrighted you work. Another company gives them a similar project to one they have worked on previously. Would it be legal for them to copy their own previous work and submit it their current company? Is Coping ones own work and using it for a dif...
With regards to object-oriented Java constructor syntax and design, specifically parameterized or specific constructors, it is the accepted process, as describe in books, to build a parameterized constructor in this form: public Car (int x, int y, int g) { xdistance = x; ydistance = y; gas = g; } For shorthan...
Colleague and I have begun a long (and hopefully fruitful) project. I've been building and have come to my first crux, and now I ask the experts of the Stack Exchange for their guidance. I'll keep this simple. Our front end has functionality to search for stocks and get back real-time intraday data on it. It's a searc...
I'm using BDD and I'm writing Gherkin feature files. Is it good practice to add a step in a Scenario to wait for a while? Something like: Waits for 2 seconds after all the operations complete or should this be implemented in the code without having an explicit step? A stakeholder would not know about the necessity to ...
I'm currently learning object-oriented programming and we have moved on to UML. We are learning about use cases and actors currently and we need to create a list of actors and use cases initiated by each actor for a given problem. I understand what each of the individual components are but we haven't been given any exa...
I am looking to create a digital Rolodex to keep track of contacts in Qt 5.9 and am uncertain how to efficiently create custom widgets. Examples online like the classic clock example show to completely override paint, but I want only to create a widget in design that is a collection of labels and buttons to display a ...
I am facing the following situation: I have to develop a system that has to calculate the price of a car so i need to calculate the prices of all the Pieces that make up the car and then total them. We have two main entities: public class Car { public int Id{get;} public List<PieceOfCar> Pieces{get;} } pu...
The TIOBE Programming Community Index shows Java and C dramatically falling in popularity between late 2016 and mid 2017 before rebounding by mid 2018. What is the cause of the volatility? Source: www.tiobe.com
According to the accepted answer on "Rationale to prefer local variables over instance variables?", variables should live in the smallest scope possible. Simplify the problem into my interpretation, it means we should refactor this kind of code: public class Main { private A a; private B b; public ABResult...
See https://www.scrumguides.org/scrum-guide.html I've read through this several times and can't find anything about how often to do QA/Test builds during a sprint. There is a section called increment. This seems to refer to the fully built product at the end of the sprint, but it doesn't offer any guidance on whether o...
From here it was advised: Formal verification needs to have a goal: what precisely do you want to prove? This is a good question. I am very intrigued by the idea of doing formal proofs in web applications after reading about TLA+. But all of the proof stuff is very low-level and doesn't deal directly with web applica...