instruction
stringlengths
34
36.1k
A common way to implement "PIMPL" in C is to do this: typedef struct _Opaque Opaque; Opaque* createOpaque(); void doSomething(Opaque *opaque); Or: typedef struct _Opaque* Opaque; Opaque createOpaque(); void doSomething(Opaque opaque); The first requires that the caller treates Opaque as a pointer, the second requir...
I am new to unit testing. Started working on unit test using PHPUnit. But it seems to be taking too much time. If consider I take 3 hours to write a Class, its taking my 7 hours to write test case for it. There are a few factors behind it. As I told, I am new to this stuff, so have to do lot of R&D. Sometimes I get co...
I'm currently working on a .xml to .uml diagram converter, but you may also add relations/attributes/operations and change pretty much everything. but drawing multiple arrows between 2 classes would cause one to override the other one pretty much, i guess that's not the intention Is that allowed by UML? Because i can n...
I am learning Redux (a JavaScript state container tool). I am finding numerous references to something called a "selector" (e.g. here, here, here, and here). However, I don't seem to be finding a simple definition of what a selector is (as opposed to, say, examples of selectors or details about some aspect of selector ...
I've been working on a UTF-8 iterator adapter. By which, I mean an adapter that turns an iterator to a char or unsigned char sequence into an iterator to a char32_t sequence. My work here was inspired by this iterator I found online. However, as I looked through the standard when I was beginning my own implementation, ...
I've recently become incredibly confused about the notion of "strengthening/weakening a precondition/postcondition". I think my confusion lies in my interpretation of the words "precondition" and "postcondition". Here is why I'm confused: In the rules of Hoare Logic, one can "strengthen the precondition and/or weaken t...
For context, I am running a REST API built with Node.js. Because of callbacks and some complex DB calls, I have a chain of functions that are async but also unique, so it's tough to reduce redundancy. I came up with the idea to call my own endpoints (different endpoints) from within the code itself so I can reduce redu...
I have a parent object, with multiple child objects. Every child object is of the same type and has a "ChildMethod" that contains some child specific logic. If the ChildMethod is called on any child, i want to serialize the state of all children. I put that logic into the parent object. Also I implemented it with the o...
I am writing a tool that will give users the ability to summarize text content on a webpage, by highlighting the text that they wish to get summarized. So far, I've received results that I can work with in order to further optimize the algorithm, but only when applied to single paragraphs. When multiple paragraphs are ...
This is sort of like the chicken and egg problem. In order to ensure that my arbitrary precision code works correctly, I need to rely on other, existing bignum implementations. This is relatively easy in Java. We already have the java.math package to help in this situation. So far, I've used it to test my basic arithme...
I have an API which is basically comprised of two parts: 1. A TensorFlow neural net that provides predictions based on input image (mainly GPU computations) and 2. Post processing on those predictions (mainly CPU) This is kind of a best practices/recommendation question. What I am wondering is if these two sections of ...
I am trying to build an extended CRM, using OpenSource PHP-Software. What I have for now are 3 separated systems, that all work well independent from one another. I would like to combine them. The System will have a public and a Private (Internal use only) parts. The Public part is not included in this diagram, but wil...
The way I created my rest api is the following: /api/users/{id} /api/users/{id}/items/{itemId} But I also have URIs like this one: /api/items/{itemId} It's a bit confusing to me how to handle the item authorization in this case. I don't want to send every request for a resource to the /api/users/{id}/items/{itemId} U...
I understand that there is a thread discussing a similar issue here: How to efficiently search a set of vectors for a vector which is the closest match But my problem is slightly different - and hopefully easier. Given a set of vectors of the same dimension, e.g., [2, 3, 5, 9] [12, 9, 2, 8] [45, 1, 0, 1] And a query ve...
Let's say we have a full-text database. The reasonable thing to do, for scalability, is to store only an index but not the content of documents. The issue I'm facing is: I would like to deliver highlighted preview of the content when listing search results for a given query (just like Google does), but I find hard to c...
I am a C++ newbie, and I'd basically like to know how to set things up to run unit tests as fast as possible, which I think is pretty equivalent in my case to compiling as fast as possible, without regard for anything else. So if there's practices to avoid, frameworks that are faster or slower, or compiler flags I want...
We have an API server, which serves both of our web app and mobile app (both Android, IOS). We have to shut down database servers sometimes for up-gradation or maintenance, so the site shows Maintenance in Progress kind of page. It works for the web app, but what to do about the mobile app? We can't show any kind of ma...
I am currently running a team of 5 VB.Net developers and have decided to make a switch to C#. The team builds and maintains around 20 different applications that run our whole platform, so the code-base is fairly moderately sized. There are several factors for making the switch, but the biggest is to overcome recruitme...
I know the purpose of it and everything. I see myself as a solo developer for a couple more years. I always see answers that it is contract. Yes I get it. But here's something on my mind: If a class did not provide what an Interface wants, it'll throw an error. Well, if a class really needs that method, it'll throw an ...
If one needs different JVMs for different architectures I can't figure out what is the logic behind introducing this concept. In other languages we need different compilers for different machines, but in Java we require different JVMs so what is the logic behind introducing the concept of a JVM or this extra step??
Say, a repository licensed under BSD-2 license has been forked on GitHub. A major refactoring is happening and new features are going to be added. No interactions with the original repository is expected in the future. What should/could happen with the original author's name present in the source code? Should the fork ...
A common pattern I use on my nontrivial programs is to have a class that parses out a config file (usually YAML), and makes the items in the values in the config available as properties on the class. I then import this class elsewhere in my program anytime I need to refer to the user-provided configuration #config.yml ...
Context: I am using C# I designed a class, and in order to isolate it, and make unit testing easier, I am passing in all its dependencies; it does no object instantiation internally. However, instead of referencing interfaces to get the data it needs, I have it referencing general purpose Funcs returning the data/behav...
If I were to write a security application and sell it or "opensource" it, how would I avoid writing the same code coincidentally if I cannot review source code of other programs out there? (and replace matching code) I understand citing source can prevent plagiarism, but even then, how would a company know without acce...
There's a pattern for RPC or distributed computation I've seen a couple times and I'd like to know if there is a standard name for it so that I can communicate it more effectively. I'm describing it using Java terminology, but I don't think it's Java-specific. To submit a job or RPC call, the calling code creates an i...
I want a non-primary key column to be unique. This is enforced with a unique constraint. In a service endpoint I want to return a nice error message structured into a {field, messsage} object when unique constraints are violated. Currently I check if the column is unique in the service layer and throw a UniqueFieldExce...
Just wondering if there is a good way to do this? Currently i'm performing the method calls as if they were happening prior to the conditional block, then comparing what would be the result in "[isDoable == true]" with isDoable being the result of the long chained method call. An example of the method call contained wi...
I need to store two 32-bit numbers in a way that is quickly accessible and as storage space efficient as possible. My keys are a combination of the following two values: port: 0 - 29 vlan: 1 - 4095 struct Dat_s{ int id; int val; } Dat_t; Also I need to pre-allocate all the storage that could be taken up in a ...
I have a matrix of values that is anywhere from a few dozen to a few hundred rows and columns (always square). I have a series of tasks that need to be performed on the matrix. (I'm using the Hungarian Algorithm.) Because they may take a long time, I'm doing the work on different threads to keep the UI from getting loc...
I'm currently working on a project where i am the only developer, but it should be delivered soon to "customers". Since this is actually an application consisting of multiple libraries for physicists laboratories, the boundaries between developers and customers blur or disappear - my colleagues in the labs are familiar...
I have an application service which returns entity by its registration number public Entity FindByRegNumber(string number) { if (!RegNumber.IsValid(number)) { return null; } var regNumber = new RegNumber(regNumber); return repository.FindBy(regNumber); } Here RegNumber is a value object an...
It got my by surprise yesterday than ordinal indicators are considered letters. I thought letters were only [a-zA-Z]. Why are they considered letters and not symbols? char.IsLetter('º'); // true char.IsLetter('ª'); // true char.IsLetter('°'); // false char.IsLetter('ᵗ'); // true Is there any flag I ca...
I know the differences between these associations (as described here). However I'm wondering: Composition, why not simply use an association with multiplicity of 1..* (and thus implicit saying that the target class has to exist). Aggregation, actually using multiplicity here too Or am I wrong here and do these associ...
Over on StackOverflow I found myself recommending the following pattern. I see it used fairly often in production but I don't remember having seen any articles or blog posts discussing its use. The gist is that you provide an overridable implementation method which does not form part of the public API. The public-faci...
In the Ruby on Rails communication, it is often said that RoR is "convention over configuration". Can you say for React / Redux / Flux and AngularJS, Angular2, they are also "convention over configuration"? Some details: the reason is, engineers probably do things in quite standard, or convention ways, such as // in i...
I used Angular 1 and React / Redux, and one thing I like about React / Redux is that there is a definite app state, and a middleware that can convert a promise into real data. In Angular 1, we often said, either have some sort of data in the top most controller, or in a parent controller, or by a service object, and pe...
I'm in a situation where a part of my application depends on a website which I have no control over. The website might change unexpectedly and without warning, and the changes may or may not break a part in my application. When that happens, I always have to figure out what changed and how I need to change my applicati...
I am often in the following situation: I have a config file, specifying the path to a resource file This config file gets parsed and the values (e.g., file path) are stored in a ConfigStore object A business logic object needs to content of the resource file. Now who should actually read the resource file? Config...
One of the last projects I worked on had a lot of deprecated methods. Are there any good strategies for making sure that the use of these methods actually decreases over time? The example below is Python-specific, but this question really applies to all languages. I've read a little bit in the past about adopting infor...
First Software Engineering question, so I hope I'm on topic. I'm an academic scientist working on on Python GUI applications for educational (and eventually research) use. The GUI uses PyQt and pyqtgraph to plot the results of calculations derived from user inputs. I've put a prototype for the first app on GitHub. In a...
Just except that Chain of Responsibility might go one straight line, but in the HTML event handling, it is first the "capture phase" (capturing), then the "at phase", and then the "bubble phase" (bubbling), so it is Chain of Responsibility by going from the first item to the end and back to the first item. And any item...
In the early time, maybe just few line code, But I have see too many repeated and messy codes involve serialize/deserialize interference the main logic. So I try to persuade the team members to wrap a function for operations like read/write/update data ,example as: void updateCopyTimes(int times) { player->getE...
We are trying to move (slowly) into Microservices architecture from our current monolithic based architecture. I've done my research on microservices architecture and would like to get some feedback on the architecture I've described below from the community. Information about the application It's a web application us...
The relatively large size of std::mutex on different platforms (e.g. 40 or even 80 bytes) is often explained as ensuring the mutexes don't occupy the same cache-lines and so don't incur logically unnecessary fetches and synchronization activity. However a std::mutex is commonly embedded in a larger object and its very ...
Do you name a dictionary by the key or the value? I have a dictionary that will hold gradient data and the component: dictionary[gradient] = component; Do I name it gradientDictionary or componentDictionary?
I have a question on writing clean code. I’m trying to refactor the following method: private static Map<String, String> createMapOfAttributes( final String Id, final String attributes, final Map<String, String> invalidLines ) { final String[] arrayOfAttributes = attributes.split...
we have a hierarchical structure where every node is derived from a node base class public Node(INodeFactory nodeFactory). The factory is injected so the node can create its child nodes using Get(int id) At a later moment some nodes need a reference to another node in the structure. The information necessary to get the...
I am dealing with a pretty big codebase and I was given a few months to refactor existing code. The refactor process is needed because soon we will need to add many new features to our product and as for now we are no longer able to add any feature without breaking something else. In short: messy, huge, buggy code, tha...
My app has a large dependency on external endpoints. As time passes some of them are changing and evolving. Some of these changes are breaking changes... So far i have about 10 dependencies for a single project (i have other side-projects too) and keeping it up-to-date is not the easiest task of all... Integration te...
We have a legacy system which will eventually be deprecated, at which point we will switch to using a new system. What are the pros and cons of maintaining separate databases for the old and new system, versus incrementally adapting the original database?
Today I saw that React (React JS) has lifecycle methods, such as componentWillMount() and so when the component or container is instantiated for the first time, this method will be called if it exists. (if it is defined). One example of it is, when the component is instantiated for the first time, if the above method ...
I am strucuring our rest API resources and came accross an interesting dilemma. Here is the scenario and I am going to use a car analogy /cars/1/ { "id": 1, "make": "Toyota", "year_build": 2015 ... } /cars/models/1/insurances { "id": 1, insurances: [ { "policy_number": 101, "company": "Insurance C...
I am building a new simple web application using dotnet core (.NET Core) and Angular SPA. Does it make sense to split API and Web App into different projects? This would complicate things (especially with authentication) whereas I could simply use 1 single MVC controller that would render my only view that spits out m...
So I have a singleton in Objective-C, there's one static method exposed to access the one and only instance: + (id)sharedMyClass { static MyClass* sharedMyClass = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedMyClass = [[self alloc] init]; sharedMyClass.myString...
I am having trouble calculating the complexity of this problem: REVERSE3(A): // Reverse the order of elements in an array // P is an array; assume generating next permutation takes 1 step. for every possible permutation P of A: for index i = 1 to N: if P[i] is not equal to A[N-i+1]: contin...
Generally speaking in canonical OOP situations, the rule of thumb is to write your classes with the least access as necessary. i.e. only make public only what is necessary, make protected only what is necessary, etc etc. (There are exceptions and what I describe does not always apply. FWIW, I find the idea of "least ac...
I have a binary file that I want to parse. The file is broken up into records that are 1024 bytes each. The high level steps needed are: Read 1024 bytes at a time from the file. Parse each 1024-byte "record" (chunk) and place the parsed data into a map or struct. Return the parsed data to the user and any error(s). D...
We have our own proprietary software that we are developing for commercial business. We want to sell the software and we do not have any problem in distributing the source code to our customers. Due to the lack of good build infrastructure and complexity of the software, it has become difficult to manage and has lost i...
I have code along the following lines: public void processInput() { List<String> input = readInput(); final Object[] returnObj = createInternalStructureFrom(input); final Dictionary dictionary = (Dictionary) returnObj[0]; final List<Order> orderList = (List<Order>) returnObj[1]; final List<String> i...
UPDATE 2017/04/19 Another view is using wrappers for late binding. Introduction I believe that objects should be immutable, so I only set properties via the constructor. In that case, the object state never change. Problem There are cases the required parameters for the constructor aren't known at that moment. So I nee...
Introduction Let's say that you have such design in your application: - application (laravel) - web scraper (used by application) - query builder (used by web scraper) The application is what actually uses the Web Scraper to fetch the data from the web, however since we use the Web Scraper as a search engine as...
A user has to perform a somewhat complex task on my website (submitting a rating). For the sake of example, let's consider it's a rating for a movie, done through a controller. There are several possible "paths" the logic could follow The user wants to cancel his rating submission (eg he didn't go to the movie) He ...
Take this example public static boolean uniqueNumbers(int[] x){ for(int i = 0; i <x.length; i++){ for(int j = 0; j <x.length; j++){ if(i != j && x[i] == x[j]) return false; } } return true; } The loop body will execute x.length times for loop wit...
I need to design code for a complex multi-table update, ideally using a repository pattern to fit in with existing code structures. Some of the tables which will be updated are specific to this flow, whereas others will be updated in future from other flows. e.g. Specific Tables A, B, C, D Address (common) Customer (c...
In the case of unit testing, I'm testing as many cases as I can that when I do X, Y happens. I'm also concerned in some cases that when I do X, Z does not happen. But for the sake of protection, I could also test that A, B, C ... do not happen either. And going that direction I could basically test a billion things tha...
I have posted this question on Stack Overflow and there few people suggested to post it here. I understand the both factory and factory method pattern. In factory pattern we create instance of my classed by another class function dynamically where I pass some parameter to another class function and based on that parame...
I'm developing both a REST API and a frontend web app. What's the best way to go about plugging the API into the web app while I'm developing locally on my machine? I could spin up a local copy of the API and point my web app to localhost:api-port, but that seems like unnecessary administrative work to have a local co...
During work, i only make commit and push my work to our shared repository at Github, when i consider that I have done my task up to necessary changes which I may realize later. So that means that I don't commit and push my work on a daily basis, but often once in several days. Generally, is daily commit and push neces...
On a REST api I have these endpoints: GET: /tracks.json GET: /tracks.xml GET: /tracks.csv It receives a tracks resourse and the format gets defined by .^string^ that is after the resourse. eg the tracks.csv sends the tracks resourse to the client as csv format (with the appropriate mime extention to Content-Type http ...
I am trying to have a lean database size, so I thought that if an input, which will always be a string, should be checked for its value type and therefore saved in a specific table that is appropriate with its type. Meaning if an input represents a string, then it should go to a table that saves string, or if an input ...
Update: Without fluent interface, builder pattern can still be done, see my implementation. Edit for possible duplication issues: When should the builder design pattern be used?: My question is about the actual advantages of Builder Pattern(of GoF). And the chosen answer in the link is about Bloch Builder, which may(S...
We are developing a.NET web application that uses WebApi. We have separate layers: UI (HTML, CSS, js etc.) ApiController - receives input DTOs from the UI and calls the appropriate endpoint in the Business Layer (for instance, StudentBLL.Add or StudentReportBLL.GetFollowReport) Business Layer - contains all business...
I'm trying to build a Java application that connects to a remote database that stores and retrieves video files that can be over 200MB. I could store/retrieve these files in MySQL directly as LONGBLOBs, yet I read again and again how that's bad practice for various reasons. One solution commonly offered is to store the...
I am using JWT for authentication in a micro service architecture. There is 1 UI web app and multiple REST API exposed services in the backend. I am considering a IAM service which will give a JWT to UI with permission information. The UI can use this to contact another Micro service X. But in this case should X contac...
var list = ['a','b','c','d','e','f','g','h']; Each time I make an API call and get that list, showing it here as a JavaScript array, I would like to know if any of the items have moved quickly (defined as, say, more than x positions) in either direction over the past n requests. Each request I get an array with the sa...
I came across this programming technique while doing pair programming in an interview and couldn't find the name of it on google. The idea is that you first write the expression which uses the variables and then you write the code that computes the variables later on. To use some example code here: private bool Valid...
Background I saw this figure describing the different crowfoot notations used in ERD: I'm not able to find the difference between the "many" notation and the "zero or many. However I was able to find an example (see bottom left for the "many" notation): (source) Question When to use the "many" notation and what is ...
I'm building an Android app where different "types" of users can log in - lets say User and Admin are the two roles (there could be more than two). User can access some views in the app, by pressing buttons that are presented to it. Admin can access those same views but more, via buttons exposed only to the admin. Furt...
My question is actually two questions about GNU GPL and monthly fees: If I build a server and use GNU GPL as a license, can I run it and charge the users a monthly fee without the need to distribute the source code? My understanding is that since the users buy the service and not the server, I can charge whatever I wa...
I have a question about a geofence triggered action. Does anyone know if you can trigger a credit card transaction by location? An app I'm having a guy work on requires this function and the guy says it can't be done. Thanks in advance
I'm planning to implement a system with a super class named User and 2 subclasses of the class User, named Seller and Buyer. They are specific types of Users. So, I have 3 files with 3 classes: - User.php (class User) - Seller.php (class Seller extends User) - Buyer.php (class Buyer extends User) When there is a sess...
I'm refactoring a legacy codebase. I have 4 very similar objects that I decided would be a good target for becoming polymorphic, so I moved all the common code to a base class and added an interface. The real problem arises when trying to create those objects. Every class has 3 different constructors with 5-10 paramete...
I'm writing java library(jar file) to log Web service request and responses in a Database for in-house application. This library will have two methods registerReuqest and registerResponse. I'm wondering is it good idea to pass database connection to these library methods? Passing connection to library will have some p...
I am currently designing a web application where the data needs to be stored encrypted. Planned technologies used: ASP.NET Core API ASP.NET Core Entity Framework MS SQL Server 2016 any Web Frontend Because of the specification we need to store all data encrypted in the database. Which would be a good approach to achi...
I am reading a book "Black-Box Testing by Boris Beizer". In this book, there is a sentence as follows, Object-oriented programming and improved operating systems promise to eliminate many currently common inter-component interaction bugs. While I understand Object-Oriented design concept (such as in Java Programming ...
The add operator of the set class returns a boolean which is true if the element (which is to be added) wasn't already there, and false otherwise. Is writing if (set.add(entry)) { //do some more stuff } considered good style in terms of writing clean code? I am wondering since you do two things at once. 1) adding ...
I am trying to understand SaaS (software as a service). What are the different ways of delivering it? We all know using ssh -X $host we can run software on a remote computer. Can this be considered SaaS?
I have been reading about distributed databases and the like providing weak and strong consistency guarantees, but perhaps I am short on imagination - when would you want to use a weakly consistent system? Most examples of real use-cases - services that share state across a distributed system, or read-write services a...
My team is preparing to add new capabilities to an OpenAPI contract and our implementation of it. There are pre-existing clients. We are planning to take our API from v1.1 to v1.2 while fully respecting semantic versioning. Our team is debating whether we must go to v2.0 instead of v1.2 if we add new possible values ...
Say you have a UI that reflects some sort of server-side data and the UI can manipulate that data via HTTP requests. For a more concrete example, consider a user database with a web interface that can add, edit, and delete users through HTTP. The client itself stays in sync with the server through periodic polling and ...
According to Effective Java's Item 15: Minimize Mutability, it is always better to make classes Immutable. According to that, how would I handle classes that are by nature given to change? Some examples would be: A Customer class, where an address or phone number can (and probably will) change. A ShippingRule class,...
Something I've noticed recently is when I am doing the following types of projects: When beginning a project Working on an MVP/prototype Adding features which aren't entirely defined Working on a smaller scale project For reference, I am working on a Python project now which currently has ~1k lines of code, including...
I am using Java for creating an application for Android (so I can use many of Java 7 options, but cannot use all of them). I have two classes: class A{ static String getScript(String input){ return "result of functionality_1 on input"; } ... } class B{ static String getScript(String input){ ...
I structured my "service" layers (or, what I thought to be service-like functionality) as static classes where each class is a grouping of complementary functions that together provide a cohesive set of operations for supporting the consuming layers' needs. public static class ElementService { public static Element...
Is it possible to optimize a .NET application running on a server version of Windows for near-zero latency TCP communication? Or will there always be unpredictable/unavoidable delays? For example, while searching for low-latency open source apps I found this OpenPDC application on Github which seems to be the de-facto ...
Currently I am working on a health related application which was being developed for 5 years and lot of developers have contributed in it. The application is quite complex and highly used by lot of users. During code review, I have found that lots of its code and implementation patterns have been deprecated and they c...
I'm fairly new to software engineering, and so as a learning exercise I wrote a chess game. My friend had a look at it and pointed out that my code looked like for (int i = 0; i < 8; i++){ for (int j = 0; j < 8; j++){ while he insisted that it should instead be for (int i = 0; i < CHESS_CONST; i++){ for (int j...
I'm familiar with HTML/CSS, and some non-UI programming using C#/node.js/Java and looking at options for building a simple mobile app. I will definitely use Xamarin, and have to choose between Xamarin native and Xamarin Forms. How much of an overlap is there between a UI coded in XAML and an Android UI coded in XML? I'...
I had a discussion about standardizing return structures in an API and the best way to enforce it across our services. The quickest way we went with was just to have our controllers in .NET Web Api return the same templated class so we came up with something like this class ResponseObject<T> { public T Data {get;...
I have an application written in C. I have to develop a GUI for it. This application will be connected to the internet and will send and receive requests and responses through the network. One way is to write the code in PHP to send and receive requests and responses by POST or something, and compile the C code into an...