instruction
stringlengths
34
36.1k
I have an integration test that needs to tweak some values on the database. This sort of tweak is not needed for the real application, only to setup the test scenario. The dilemma: Should I manipulate the DB directly from within the test project (by running a custom SQL query or by adding EF to the test project), or s...
I am learning about Primitive Obsession. Please see the value object below: public class UserName {     private readonly string value;     public UserName(string value)     {         if (value == null)             throw new ArgumentNullException("value");         if (!UserName.IsValid(value))             throw new Ar...
Java and .NET have wonderful garbage collectors that manage memory for you, and convenient patterns for quickly releasing external objects (Closeable, IDisposable), but only if they are owned by a single object. In some systems a resource might need to be consumed independently by two components, and only be released ...
Let's say I have a C++ function that looks like this: bool Foo(Bar* b) { if(b == nullptr) { return false; } // Do stuff return true; } Let's further say that, because of limitations with some of the tools I have that don't support any standards newer than C++03, I have this code in a header: #...
Is it bad design to expect the client to cast between interfaces? I understand it can be done, but is it clean? I'm comparing retirement profiles in a simulation. I have 2 different types of TSPs (think 401k). I have a TSP class, which holds employee contributions (no government match). MatchingTSP is a TSP, but it als...
I'm working on a problem that reduces to something like toll plaza placement on a set of highways. Given a large undirected graph and a list of node pairs with a toll value between them, I need to find the minimal set of toll plaza nodes that can levy the tolls (each plaza node can levy an arbitrary set of tolls). Each...
I'm currently looking at microservice architecture example and am struggling to make my services truly autonomous. I have the following services... CustomerAPI CustomerService OrderAPI OrderService ProductAPI ProductService As part of the OrderAPI I'm looking to create an order by sending back a Customer ID and Produ...
Assuming I have the following objects (pseudocode for Ruby): StringToXML with call method which accepts a String and returns an ExternalLibrary::XML::Document object (a data structure from a third-party library) XMLToArray with call method which accepts ExternalLibrary::XML::Document and returns an array following som...
Let's say I have a class Dot with a builder: public class Dot { private final Double x; private final Double y; private final Color color; private Dot(Double x, Double y, Color color) { this.x = x; this.y = y; this.color = color; } public static Builder createBuilder() ...
I'm familiar with the process of setting up Postgresql. And I'm also thinking of using SQLite for some of my websites for I don't need that much functionality that Postgresql offers. And I also want to avoid having a database demond working all the time in the background even when there's no need -- no requests to my d...
I'm maintaining an already built system. The current system operates as following: Current situation: Client (UI) submits a request. Web layer round-robins to one of backends. Backend takes request and handles. Backend can spend millis / seconds / minutes on request depending on which job it was asked to do. so let'...
Assume I have some data a csv-Files like ObjectName, PropertyA, PropertyB, PropertyC "Name1", 3, 1, 4 "Name2", 1, 5, 9 "Name3", 2, 6, 5 ... and a typical question I want to answer would be For which Object is PropertyX maximal? I have two approaches for this and would be thankful for some Input. Approach 1 I define...
Can anyone please help me understand the internal process of how C# class fields work? And how class properties (with getters and setters) work? While comparing performance I found properties are a lot slower to access than fields. So what is the reason behind this?
A class LinkedList exists with functions such as add_first(), add_last(), add_after(), remove_first(), remove_last() and remove() Now there is a class Stack that provides functionalities such as push(), pop(), peek() or top(), and to implement these methods it extends the LinkedList class methods. Is this a violation o...
When I review the changes in a pull request, I sometimes stumble upon a comment with a "TODO" note which may be there for different reasons, in our case mostly because of: the solution used to solve a problem can be improved but would require significantly more time investment. An author chose a quicker solution but p...
Most modern programming languages do not allow multiple return types (excluding scenarios like C#'s out parameters or the newest use of Tuples). This is because all languages implement the concept of mathematical functions, which for a given number of input parameters, produce only one result (by one I don't necessaril...
Let's take an example of class with 3 dependencies and one method. class Example { private readonly IDependency1 _d1; private readonly IDependency2 _d2; private readonly IDependency3 _d3; public Example(IDependency1 d1, IDependency2 d2, IDependency3 d3) { _d1 = d1 ?? throw new ArgumentNull...
Let say I've abstracted away a data structure such as a list; should this new object perform all the calculations or just provide minimal calculation functions and then allow a new object such as ReportGenerator to perform more large-scale calculations? Example below: THIS? class WrappedCollection { public double Ca...
I would like to vectorize some operations in arrays that are not actually available in ndarray or pandas dataframes/series, such as comparing element-wise two arrays/series/frame of similar shape, one of these containing a value and the other one a list. Can I write my own data structure in python which use vectorizati...
I'm rearchitecting a system in Python, using SQLAlchemy for the data mapping layer, and the Zope Component Architecture for dependency injection and interface declaration. I am in the process of figuring how to combine (or draw on) DDD, DCI, and the Clean/Onion/Hexagonal architecture. In SQLAlchemy, we have a unit of w...
I have read, both on this site and elsewhere, that the recommended programming style for C++ is to avoid using C-style casts, and prefer the C++-style static_cast, dynamic_cast, reinterpret_cast, and const_cast. The reasons for this recommendation generally boil down to (1) the C++ casts are safer because they are more...
The highest rated answer to this question about the Liskov Substitution Principle takes pains to distinguish between the terms subtype and subclass. It also makes the point that some languages conflate the two, whereas others do not. For the object-oriented languages that I am most familiar with (Python, C++), "type" a...
I have a simple question about best practices in unit test verifications. Given this example: @Test public void methodUnderTest() { when(mockedDependency.someMethod()).thenReturn(someValue); int actual = classUnderTest.methodUnderTest(); assertEquals(5, actual); verify(mockedDependency).someMethod(...
I'm stuck in a concurrency problem. Is a typical problem where the user sends 2 o 3 transactions to persists some data that SHOULD NOT BE duplicated in the DB, in case of a duplicate record you should return an error. This problem is easy when you can just add an index (unique) to a column where you store a hash. But ...
Imagine a LineSegment class that represents a line segment using two arbitrary endpoints. Should the constructor throw if it is passed two approximately equal endpoints? Obviously this would require some arbitrary floating point comparison. For example, test the Euclidean distance between the endpoints is less than ε. ...
To restate the question: Which is better, one central detailed comment, or several smaller "sprinkles"? Bear with me while I set up the scene: I've got this function for popping a value from a queue implementation: int queue_pop(queue *list, void **pValue); If you're familiar with C, you understand that calling this f...
I think a lot of new comers get confused because these two terms look and sound similar: Authentication Authorization I think "Authentication" is well known, I will use this term. But for some docs I currently write I would like to use an alternative word for "Authorization". What's the best synonym for "Authorizatio...
I know this has been asked many times before, but I still don't quite understand what the difference is between the following: var Foo = function (){ //1 this.a = ""; this.b = ""; var c = ""; //private member } var instantiatedFoo = new Foo(); // and the same with closure var FooSelfEncapsulated =...
One of the most annoying boneheaded bugs I run into is trying to create a new file in a directory that does not exist. (At least on Windows/NTFS, not sure about other OS/FS combinations.) Here's how it usually happens in C#: const string directoryName = @"logDir\"; // This would prevent the exceptions. //Directory.Cr...
I'm using some AWS modules to develop a role which will create users, groups, roles and manage managed policies on AWS. I would like to have some TDD practice while developing this role. For example, I have the following task: - name: Create or delete an user iam: iam_type: user name: "{{ item.name }}" ...
I am designing a resource request system where an user can request resource of different types. There can be many resource types such as: VM DB File System etc Above types can have sub-types and i.e. there can be mysql, postgresql etc for resource type of DB. The user can have different roles like: Director Manager ...
I'm trying to refactor some legacy code that's quite a mess. We're talking a class with 7000 lines and a handfull of methods that are violating the Single Responsibilty Principle so much it hurts to look at. I've managed to break it up a little, but I find I'm mainly just shuffling the code around into separate classes...
In 8.3. collections — Container datatypes — Python 3.6.4rc1 documentation, it specify 5 methods of namedtuple. namedtuple_methods = {'_fields', '_make', '_replace', '_asdict', '_source'} Nevertheless, the methods cannot be acquired by dir method from collections import namedtuple set(dir(namedtuple)) & namedtuple_met...
Please see the code below: public IEnumerable<DenominationNumberRequired> CalculateDenominationsFor(int cost) { var target = cost; foreach (var denomination in currency.AvailableDenominations.OrderByDescending(a => a)) { var numberRequired = target / denomination; if (...
Please see the code below: public class EnglishCurrency : Currency { private static readonly decimal[] _denominations= { 0.01M, 0.02M, 0.05M, 0.10M, 0.20M, 0.50M, 1.00M, 2.00M, 5.00M, 10.00M, 20.00M, 50.00M, }; public override IEnumerable<decimal> GetDenominat...
I am creating a brand new Housing application which lets user rate or favourite the houses. The following are users of the application: Owner Agent Guest (not logged in) Visitor (logged in) Tenant Now, the Owner can do CRUD operations but only for the house he owns and can't rate the House he owns. The Tenant for exa...
I'm having trouble coming up with a name for this problem, but I feel like its been solved before. I think my naiveté is preventing me from typing the right words into Google to get the results I need. So I apologize in advance if this question has been asked before. Anyway... I'm designing a multi-tenant web app where...
I am working on a system that needs to keep the data safe and not accessible to people without authorized access. The client is a web app that communicates with the servers via APIs. This is what I have so far: __________ _____________ __________ | Server | | Server | | ...
Example: in the database I have a record such as this: { id: 53, part_number: 'MOTOR-OIL', description: 'Motor Oil' } I wish to use a link that displays this record. I could refer to the record like so, using the surrogate key: http://localhost/show_record/53 or I could use an domain-specific identifier...
I have a project where I will be creating certain data models, and managing them. I also want to provide functionality to external clients to access and modify this database. So the question is around how to structure various components to achieve this. I have so far considered two options: Option 1 Create a list of AP...
Let's say we have a struct Vector2i { int x = 0, int y = 0 }; And create a Pointer to it via Vector2i* pointer = new Vector2i; Where would int x and int y be stored? Heap or stack? Are all members of an instance a Pointer is pointing to automatically on the heap because the vessel is? Are members of stack created vesse...
When does an object truly belong to a class? I'm familiar with the "has-a" relationship, but in the case of an Employee object, it "has-a" 401k, but it's not really composed of a 401k object. As an employee, my 401k does not make me who I am. What I'm getting at is, I don't feel that I should need to reach into the E...
So I'm working on this game where I have a nested class which has to get access to the member functions and variables of the outer class in order to perform it's functionalities. In particular the outer class contains member functions and data related to game objects whereas the nested class extends an AnimationTimer w...
I have an array of integers representing connectivity of nodes.Consider the following states of the array after each time it's changed: 0|1|2|3|4|5|6|7|8|9 => Root of each node is itself 0|1|2|3|3|5|6|7|8|9 => The root of 4 is 3 0|1|2|8|3|5|6|7|8|9 => The root of 3 is 8, so now 8 is root for 3 as well as 4. And so on.....
In every website I have ever made I usually make the back-end API using NodeJS and run it on a certain port and make the front-end using React and run it on a different port and make requests to my NodeJS API. Is this the optimal approach to making a web app where I don't want anyone but my front end to access my API? ...
I am currently thinking about how I would implement a software I did write some years ago with a Clean-/Hexagonal-/Onion-Architecture. This shall not be a "Grand Redesign from Heaven", since I'm not involved in the project anymore, but rather I'd like to learn what I could have done better. One thing that I have probl...
I'm implementing a registration system where I would care of having a clean DB with only unique email addresses. uniquenes could be simply obtained by comparing email addresses strings. But considering what various email providers policies, allowing you to use same address e.g. inserting dots or plus signs... Resource:...
In a MVVM application (Xamarin.Forms, FWIW) I have a viewmodel that stores settings explicitly public class SettingsPageViewMode : INavigatedAware { ISettingsRepository settingsRepository; // injected public void OnNavigatedTo(NavigationParameters navigationParameters) { var settings = settingsRepo...
I have a custom TextBox that validates its input. Whenever the validity of the input changes, a ValidityChanged event is raised and the user is informed about the validation results. My question is what to do when the user changes the input, but the input still has the same errors. For example, let's say the input shou...
I our team we use a gitflow approach to maintain our codebase. But there is one case in which we struggle. We are in the following case, we have two feature branches (feat/A, feat/B) that were create from develop. feat/A is now finished, so we merge it into develop, well this feature now lives in develop, it is waitin...
With the inability to go into to much detail, imagine the following situation: You are developing a library that needs to run on various embedded platforms (AVR, ARM, etc..). Some functionality of said library needs some sort of time keeping (not an actual time but along the lines of "it is now x (mili)seconds later th...
We have a build server that will transpile the JS source into the bundle file. I now need to inject values that are dependent on the environment the application is executed. The problem is, since the app is already bundled, I don't see a way of injecting it in a clean way. Alternatives I've seen on other teams are cre...
We are developing a new REST Api for our Spring MVC legacy enterprise web application (before this it was communicationg with Adobe Flex frontends). As a general rule we stated that we were creating a @RestController for every model we have in our application. We have also a BaseController for handling the CRUD operati...
What are efficient algorithms for immutable dictionaries/sets? By efficient I mean they either have better or comparable time and/or memory performance compared to their mutable versions. I don't necessarily mean this in the context of functional programming, where I've seen immutability equated to persistent data stru...
I was trying to create an integration test for my service where 100 clients would connect, login, send request, and log all responses for some configurable amount of time. I was build a class for the client using async sockets and it works fine. I started them all up using Task and Task.Factory, sent the login, and po...
I'm designing a programming language for a game, to be used as the main way of interacting with the game, as opposed to using other methods of control, such as the arrow keys or mouse. My plan is to have the user control game objects through objects in the language. if unit1.health > 20 { unit1.attack(Enemies.ene...
The reasons may vary from breaking principle/guidelines of OO to considering protected as part of public API. Then, what should we do if some derived classes have same members? Should we declare them in base class and inherit them? Or should we declare them in derived classes multiple times? For example, class Warrior ...
For example: While performing functional testing of a form in a web application, we will test the fields by entering different kind of random input values. In general, we as users of the web application do not actually enter random values into fields. So what is the use of incorporating all those testcases which may/ma...
I come from a python background. I typically write long unit test descriptions that link the test to a user story. The test is as much about justifying why the code exists and how it fits into the larger system as it is about testing for correctness. As such my tests often have about as much docstring text as test code...
I'm developing a software system, which provides HTTP REST API, and I want to achieve a very modular and flexible design. So, there is a core functionality and feature modules, which handle only the logic related to each specific feature. The goal is to be able to add/remove modules in a flexible manner without the nee...
When requiring to use dependency injection, I always use IoC containers such as Ninject, Unity, or the built-in one in ASP.Net Core MVC. However, I've just come across the idea of "why not creating an object factory" and then instead of intercepting calls to parameterized constructors (via IoC containers), retrieve tho...
I have a concept that I am struggling to design in a DDD CQRS manner, and I hope to find some insight. In the old days (before I knew DDD) I would have used simple inheritance, and that's how my mind is wrapping around the following... I have a domain concept: Property There is a SingleValueProperty which has a Proper...
We are building a notification service whose work is to send push notification to end user. There are two types of notifications Group notification where we send same text notification to all user's in a group. This is easily achievable as everyone subscribe to a group and we send a notification to a group. Personali...
How to declare static function with array and pass next into other class? class A { //static public static $data = ['Los Angeles', 'New York', 'Washington']; //const const DATA = ['Los Angeles', 'New York', 'Washington']; } Which approach is better and why? Maybe for string or int better is other appro...
I've come across a method resembling the below snippet. public void process(Data row) { Value value1 = row.getValue1(); Value value2 = row.getValue2(); boolean saved = false; if (value1 != null) { if (relevantValues.contains(value1)) { addRow(value1, row, only1collection); ...
I have multiple data sources that I need to search across and return back to the client (web app). For example the sources are: an elastic search index a sql database Is there an efficient way to perform paging across two sources? At the moment I am searching on one, and then reducing the searchable items on the sec...
I have a created a Java project. My project is a collection of classes that allow a programmer to manage local networks (create network, delete network-access to device, get information of SSID) and other functions in the local network. The architecture of program is based on CMD commands. All classes are reusable by p...
I am working on a ruby on rails learner project that uses multi-tenancy. This project has states(tenant) and cities(sub-tenants). User can only belong to one city. For first level i.e for states I have decided to go with separate schema approach using the Apartment Gem. Now my question is can I use table level multi-te...
I have had a discussion with a coworker about breaking a return statement and the statement that calculates the return value in two lines. For example private string GetFormattedValue() { var formattedString = format != null ? string.Format(format, value) : value.ToString(); return formattedString; } instead o...
I have developed a windows service with Message Broker (RabbitMQ) The purpose of the service is to receive data over TCP/UDP connection. Parse the incoming data which is in HEX format and convert them to objects and save the object to the database. Also the service performs some calculations and checks to send out aler...
What's a good way to design a RESTful URL pattern to get one and many results by ID ? One (Response: single item) /invoices?id=a/b Many (Response: array of items) /invoices?id=a/b&id=bar The above approach looks nice in theory but raises a couple of concerns What (JSON) should be returned if id is omitted, {}, or [...
I'm trying to figure out a win/lose algorithm where we have to have (around) X winners per day spread across the day without knowing the number of participations. A user sends a request to an application that immediately decides at random whether the user has won or not. We don't know the number of requests when we sta...
I have a class that internally uses an interface that is defined externally. Testing this class becomes difficult since I need to mock out this interface but I am required to reference the external library (which may be quite big) since the test is in a separate test project. Are there any ways to decouple this interfa...
I was writing an app(learning) and I found this problem. I have 3 table Orders, Customers and Suppliers. An order can only refer to a customer or a supplier and there is no conceptual difference between a customer or supplier order. What is the best / most performant way to store it? Create 2 separate tables: Customer...
Sometimes i have code along the lines of this: public abstract class A { protected abstract void DoSomething(); }   public abstract class B : A { /// <inheritdoc /> protected sealed override void DoSomething() { SpecialFunctionalityOfClassB(); ...
In our codebase we have a lot of controllers with a very similar structure: @my_model.update_owner(something) if @my_model.update_attributes(params) return render_object(@my_model) else return render_validation_error(@my_model) end Although the structure is not exactly the same everywhere, it seems feasible t...
I've reported to a third party what I consider a very serious performance bug in a widely used product. Older versions worked fine. Newer versions are practically unusable except for what I consider trivial situations. I have provided test cases showing older version performance versus newer version performance. After ...
Does visitor pattern lead to violation of SRP? Take this for example: class 401k { public void MakeContribution(Contribution contribution) { contributions.Add(contribution); } // using double-dispatch here (violation)? public Money CalculateBalance(I401kBalanceCalculator balanceCalculator) { retur...
Here is a weird problem in Angular: <input #pin1 type="password"> <p>You entered: {{pin1.value}}</p> If you type something in <input>, the <p>'s content will not change which means pin1.value does not have value, does it mean the variable reference #pin1 does not work? On the other hand, if we add a function to pass t...
This question might be a bit vague and answers might come up quite opinionated but I don't know how to rephrase it so here it goes. How can a developer build a solid vocabulary when working in a specific domain? As we all know, naming things is one of the hardest feats in this craft. Furthermore, it is highly likely ...
I have an interface with only a single method that could be replaced by java.util.function.Function from the JDK: interface DataModel { boolean apply(Map<String, Integer> input); } The replacement would be Function<Map<String, Integer>, Boolean> However, I wonder whether I should keep this interface since at least ...
I'd like to implement a multicast function. Currently, I'm in the design phase of this. The basic idea is to have a class, to which std::function can be added, an interface like this: template <typename ...PARAMETERS> class MultiFunction { private: // some container to store functions public: //...
I'm currently doing up class diagrams for a project I'm working on. I feel there's something that should be represented in my class diagram but I'm not quite sure. I have a .csv file which the whole system essentially works on, which is created by a java class on a once off basis (i.e it will never be done again). I...
Say we have a class "Felidae", and a class that extends it, "Felis". Felis is an extension of Felidae, but what is Felidae? Is it the inheritor (or inheriter) for Felis, in common terminology? Given I'm not sure that inheritor is the accepted term, I want to ask, if there is any formal, or at least, very common term fo...
Supposed I have a common block of code between two controllers where the only difference is the concrete class that the block uses. Both clases implemenet a common interface so I am using an interface to interact with the object. The block of code is a series of steps that interact with functions of the concrete class....
If I've got a script that uses a config file (or defaults to a generic config file) that calls another module which needs the config file passed to it as a parameter should I always File 1 (the script): /bin/runner include doer.py ... initializing backup conf file backup_conf_file = "/etc/thing.conf" ... processin...
I have a script which returns the ID's of the warehouses (4,1,2,10,9) in order how close they are to the customer. $warehouse_rank = array('0'=>4,'1'=>1, '2'=>2, '3'=>10, '4'=>9); When I lookup a product from the database, I return a breakdown of which warehouses have it in stock and the quantity. Like so: $product_bre...
PHP, C#, Python and likely a few other languages have a yield keyword that is used to create generator functions. In PHP: http://php.net/manual/en/language.generators.syntax.php In Python: https://www.pythoncentral.io/python-generators-and-yield-keyword/ In C#: https://docs.microsoft.com/en-us/dotnet/csharp/language-re...
I have searched and found a few questions talking about testing in relation to feature branching. My question is a little different. We are a scrum* team of 4 to 5 developers with a dedicated on-team QC. We do active development on a family of applications with large amounts of legacy code. The application family incl...
I'm integrating a messaging feature into an application written in Javascript and would like to know which is the preferred data structure of storing messages. The two structures I can think of so far are these: const thread = [ { id: 1, user: 'joanne', message: 'Hello, How are you?', }, { id: 2,...
I am building a service which acts as a proxy to third party data providers for the end-user. My service uses tokens for authorization and if the user does not have a valid token it responds with 401 Unauthorized. If the token is valid but access to the resource is denied my service responds with 403 Forbidden. The ser...
Is it a good practice to use #ifdef during development to switch between different types of behavior? For example, I want to change the behavior of existing code, I have several ideas how to change the behavior and it's necessary to switch between different implementations to test and compare different approaches. Usua...
My application uses a relational database but there is a feature requirement to display a survey form to users at the end of each quarter/year etc. I understand that this data maybe used to do some analysis in near future but the issue is the form would have many key value pairs and I am sure that it will keep on chang...
I have a Java app which acts like a command server for other devices and communicated with them via MQTT. I want to add a new functionality and don't let my sender class (implemented as a thread) send another message if the receiver class (also implemented as a thread) doesn't allow him to, let's say when a message con...
I recently had my final exam for a software engineering course for my masters program and one of the questions on the exam was the following: Unit Testing is considered: a. White-box Testing b. Black-box Testing c. Either In my 7 years of software development experience, unit testing has always taken a white box appro...
I have a system ("an engine", which is a piece of code) that takes in several parameters returns some output. The input parameters are several distinct and constrained sets. I can enumerate all of them (currently 1064 sets of inputs) and run them through the engine to produce the same number of outputs. The engine co...
I have two stories (I know they are missing the benefit part) As a Credit Management User, I can view the current and previous payroll differences for Offices. As a Credit Management User, I can receive an email containing a PDF of the current and previous payroll differences for Offices. The two are related in tha...
I've been reading about how memory-mapped I/O actually works and I cannot understand how the system assigns an address or address space to a specific device. Let's say I had two devices that I wanted to use in a memory-mapped scheme, and they were identical devices (hard drives maybe?). If they both monitored the addre...
Kinda new here and also learning new db concepts. I got little bit confused about terms: Roll-back and Roll-forward. I read definitions and thought I understand it. I found some little tasks about transactions and it got me confused. Example: Question_1: Which transactions (when system is recovering) will do roll back...
I'm developing a desktop JavaFX application that connects to a local WildFly app server via the REST protocol. WildFly describes itself as an application runtime that helps you build amazing applications. and the way I view WildFly is for development use only, so when I eventually want to deploy my app to the public...