instruction
stringlengths
34
36.1k
From my book "Data Structures & Algorithms in Java: Sixth Edition" the definition of Big Oh is the following: Let f(n) and g(n) be functions mapping positive integers to positive real numbers. We say that f(n) is O(g(n)) if there is a real constant c > 0 and an integer constant n0 >= 1 such that f(n) <= c * g(n) f...
I am reading this article about CQRS, and when it comes to decide where to use it, the following didn’t really get to my mind: Collaborative domains where multiple operations are performed in parallel on the same data. CQRS allows you to define commands with enough granularity to minimize merge conflicts at the do...
I'm writing a NuGet package mainly for data access and utility functions that is going to be consumed by multiple web applications, but there will be one main web application that is going to drive the development of the NuGet package. As such I'm going to want to be developing that web application alongside the NuGet...
Recently I had to refactor some legacy code. As in most cases, I had to split big parts of code into smaller, cleaner and readable functions. I ended with many functions, that had multiple, weird parameters. Let me show an example: public void SendOrder(Order order, XmlOrder xmlOrder, Insider insider) { string cust...
I'm writing a library in C++ which needs to be as fast as reasonably possible. However, I'd also like to be able to provide logging in case a user (or me) needs to debug possible problems. This library needs to be built, but also contains some header-only templated classes. As I understand, usually logging in libraries...
I have several questions about UML diagrams as I am not finding them very clear (they are new to me). 1) When making a diagram with generalizations/specialization: if I do not have all of the possible child classes on my diagram and only have the main children relevant to me, do I still use a blank triangle for the co...
Say I have a Domain Object, which represents a Customer with a list of Offers. Say I want to add a collection of Offers. I believe I have two options: Option 1 Have the Domain Object calculate the offers and then add them: public IEnumerable<IProduct> GetEligibleOffers(IOfferCalculator offerCalculator, IList<IProduct...
I would separate the BLL from DAL as a best practice. I interact between BLL and DAL via interface. Example: public interface IProductRepository { void Add(Product myProduct); Product Get(string name); Product GetById(int id); } where business object Product is: public class Product { public int Id { ...
Given 2 objects / classes: A class for a cargo ship. It has a small set of attributes, say current location, size, number of crew and some other things. Most important, it has an attribute for the id which is unique and the class is hashable. A class for a harbor. Again a small list of attributes like location and t...
I am trying to use a dispatch table to select a data type to cast something as and cannot figure out the syntax for this. g_cast_table[] = { {'h', short int} or {'h', "short int"} } outcome: (short int)q Right now my table is set to have a char name and char* type. This is causing a large number of ...
I'm trying to read about DDD, and i'm struggling a bit trying to to identify aggregate roots. I wrote a really simple app to divide players into different teams inside a game. So my entities are something like this: Game Entity: public class Game : DomainEntityBase, IDomainEntity { private List<Team> teams = new Li...
I have a Unit Test, which looks like this: [Test] public void Should_create_person() { Assert.DoesNotThrow(() => new Person(Guid.NewGuid(), new DateTime(1972, 01, 01)); } I am asserting that a Person object is created here i.e. that validation does not fail. For example, if the Guid is null or the date of birth ...
I have an external dependency that provides a client library that is subject to change frequently. I'm writing a wrapper class on top of the client library so that all changes with respect to that library are contained there. This library provides some enums that are needed to send requests to the client. I dont want ...
I was reading this article here: http://enterprisecraftsmanship.com/2014/11/08/domain-object-base-class/. The article talks about creating a base Entity class, which handles four of the nine ways to do comparison in C# i.e. it handles: == != object.Equals IEquatable<T>.Equals<T> Then I read this article here: https:...
Trying to practice LSP, the following is not really clear to me: Liskov requirements (some) -There must be contravariance of the method arguments in the subtype. – There must be covariance of the return types in the subtype. Also the method in a subclass could be declared with a parameter type that is more...
I've written a function that tests two floating point numbers for approximate equality (see this Code Review question). I'd like to unit test my function, but I'm not positive of the best way to do this. Obviously I could pick some arbitrary numbers that should be equal within the threshold, but it seems a lot more use...
We are in the process of modernizing an existing legacy application and as part of that we are replacing a proprietary off-the-shelf product that is deeply integrated with the application - with a new off-the-shelf product. There are two approaches we are looking for co-existence. Update the Original application (say...
I am currently building a piece of code that creates side-effects based on input parameters. It has around ten input parameters and about six available side-effects. Based on the input parameters, the chosen side-effects - one or multiple - differ. I have started developing this code test first with a context/specifica...
In system design using use case diagrams are all use cases initiated/done by the external user: e.g. add line item, print receipt Or can use cases be entirely internal/automatic: e.g. calculate running total, or even present running total In regards to the second example would a cashier system have a use case of presen...
I want to enable versioning in my REST service via urls. Need some suggestions/feedback on which is better mechanism? <myapp_context>/v1/<sub_context> or v1/<myapp_context>/<sub_context> where v1 is the version. I am asking this because a lot of articles mention it like v1/<myapp_context>/<sub_context> but according...
I need to measure a web application average bit rate consumption to see what is the recommended bandwidth needed for the end-user to connect and use the web application with no performance issues from the server. My thinking is to use an end-user machine and make a stress test to the web application and load it with he...
I was talking to a Business Analyst about our Domain Model a few weeks ago. I used a class diagram to facilitate communication. She understands UML at a high level and this worked out quite well. She only asked two questions: what is an Entity and what is a Value Object? I explained. I have two base classes i.e. Ent...
As we know, some processes will complete. void func (var a) { Console.WriteLine(a) }; And some will not, void func (var a) { while (true) { Console.WriteLine(a) } }; What do we call the function that completes? What do we call the function that never completes?
My apologies if this is the wrong stack exchange site for this question. Please, let me know if I should ask this in a different place. I have recently went to a interview. The interview was for the position of senior full stack engineer. At that interview, I was asked the question: How would you design a scalable web...
I am modeling an aggregate root, which has several actions that perform operations against other entities, as you'd expect. The aggregate, however, has a state, and several of these operations can only be performed when the aggregate is in a particular state. I created an implementation of the state pattern, so that t...
This question extends from these questions: Should we avoid object creation in Java? Is object pooling a deprecated technique? Well, a JVM running on a server is well optimised, I know. Programs like Minecraft server runs pretty smoothly with a little pause time every few seconds(it's still well over 2-5ms, so that's...
A common pattern for locating a bug follows this script: Observe weirdness, for example, no output or a hanging program. Locate relevant message in log or program output, for example, "Could not find Foo". (The following is only relevant if this is the path taken to locate the bug. If a stack trace or other debugging ...
I'm quite a noob in the world of testing. I've read all the materials related to Android testing: Unit test Instrumentation test JUnit Robolectric Espresso etc. The thing is that, all the examples provided only cover very simple use cases, such as verifying whether a text is on the screen or verifying whether the cal...
I'm writing a postcode validation library, so that I can call a helper method var result = Postcode.IsValid(postcode, country) To that end I need to have 'classes' that represent supported countries and know how to validate each. At present I have an interface thus: public interface IPostcode { bool IsValid(string...
I'm maintaining a couple of software repositories (C, C++ essentially) which I want to also run - or let's start with at least build - seamlessly on Windows. Now, my desktop machine does not have Windows installed, nor does my laptop; and I don't have a spare computer right now, nor do I want to have my desktop or lapt...
I have read a few questions on the SO and elsewhere and still do not understand well where this "widening" of a parameter type can be helpful, i.e. compliying to Liskov substitution principle. The following code I took from an answer on the SO, explaining contravariance: //Contravariance of parameter types: OK class Fo...
Last week our teacher gave us a question about Huffman Encoding Algorithm described as below. HUFFMAN ENCODING ALGORITHM: Consider all pairs: . Choose the two lowest frequencies, and make them brothers, with the root having the combined frequency. Iterate. The question was to find the Final Binary Tree and Variable L...
I am working on a software assignment where the design is component based. The components have ports which provide interfaces. My professor argues that the Port class which is exposed by each component should be a Singleton, as the port must be the only way to interact with the component. As I see it, multiple instan...
so I am thinking of using the actor model to solve a problem I currently have. For brevity, I have made up a scenario so we don't get too technical. Lets say I have 3 benches but each bench supports a different amount of people: Park Bench 1 supports 3 people simultaneously Park Bench 2 supports 5 people simultaneousl...
I have a base class with a method called Update: Start Update Code block 1 (An If statement) Code block 2 (Setting a variable based on the If result) Code block 3 (A switch which is setting something) End Update The order in which the code is executed is important so they can't be shifted around. I als...
I am building a small web API using .NET Core. I want to practice TDD and this is my first attempt at TDD. These are a few use cases of the API: Users in administrator role can create/edit/delete common(shared) lesson records. Users in teacher role can create lesson record. Users in teacher role can edit or delete l...
I've developed an application that reads a file, maps it and stores info on the database. For some columns we need the primary key of an object in the database, and if the record does not exist we need to create it, for that purpose we got a class called ReferenceSolver which is abstract and has many implementations th...
This is a very conceptual question and looking for advice or examples you may know about. I'm just getting back into development after a very long hiatus in a sales career, so please excuse me if my thoughts or questions seem simplistic or outdated. The data for a very large number of implementations is moving off-site...
This is not a problem I am having in my problem domain. It is just a thought exercise. Say I have a simple calculator like this: public class Calculator { public IEnumerable<KeyValuePair<int, int>> CalculateDenominationsFor(int cost) { var target = cost; foreach (var d...
I am trying to design an app that is based on microservice architecture. Backend is written in JavaEE (micro profile, not Spring Boot), while for front-end I would use Angular5. Now I am wondering how I could implement an authentication which would require user to present a valid X.509 certificate (.p12 file) signed wi...
Trying to work out where certain responsibilities lie with the following example. We have a Project object and a Project can have Time entries booked against it. Each Time entry will have a no. of Hours and a Rate. We then want to create a report that shows a list of projects, the amount of hours booked and the value o...
For example class A { public int data1 {get; set;} public int data2 {get; set;} } class B { public A objectA; } class C { public B objectB; } class D { public C objectC } class E { public D objectD; } class Caller { public void foo(E input) { var bar = input.objectD.objectC.ob...
I am writing a utility in C++ with Qt which communicates with an embedded device. The program was originally going to be used to just plot data from the device, but a new requirement has been added (not by me; no control over it). So now it has two modes, and thus two classes: DevicePlotWindow DeviceDebugWindow Both ...
I am hoping you may be able to give me some advice on class design and what would be best for the program I'm currently writing. This is being done in Java and the goal is to generate letter data fields for the mainframe to read and run through a program for further action. Imagine there are 50 different letters, 40 of...
I am developing an app which uses Entity Framework for data access. The architecture of the app somewhat like below: As depicted in the drawing, the business service can be consumed from either web app, cli app or windows service. What I'm trying to design is, each service request should be performed in a single trans...
Let's say I have written a library containing many classes in C++. Obviously, I can call this library from C++ client programs. But, now let's say I want to use another language for my client programs. Since my C++ library contains many classes, I don't want to redevelop them in the client language. So, I would like to...
Is there a best practice for naming class selectors for identification alone? For example, for defining a single amount field with action button, we end up creating several div containers and div items among other elements. <div class="form-group debit-amount"> <label class="control-label">Debit amount/label> <div ...
For example, I want to show a list of buttons from 0,0.5,... 5, which jumps for each 0.5. I use a for loop to do that, and have different color at button STANDARD_LINE: var MAX=5.0; var DIFF=0.5 var STANDARD_LINE=1.5; for(var i=0;i<=MAX;i=i+DIFF){ button.text=i+''; if(i==STANDARD_LINE){ button.color='red...
A common bug in JavaScript is to forget the await keyword when calling an async function. Of course you don't always want to await, sometimes you really want to get a promise. And of course you can't statically determine all target functions. But there's still a vast majority of trivial cases that we'd like to check in...
I have read plenty of articles recently that describe primitive obsession as a code smell. There are two benefits of avoiding primitive obsession: It makes the domain model more explicit. For example, I can talk to a business analyst about a Post Code instead of a string that contains a post code. All the validation i...
Currently I have a design problem, which I am not sure how exactly to solve and what would be the best approach. So what I have is a ASP.NET Core WebApi project which is actually clustered solution. It has several layers, of course representation (RESTful API), services, validation, repositories and data. Solution is ...
A pure function is assumed to produce the same outputs given the same inputs. Suppose an (otherwise) side-effects free function computes with floating-point numbers. Due to numerical error, these outputs may differ (dependent on the system, parallelism, compiler optimisations ...) For instance https://stackoverflow.com...
I am retrieving GeoPoints from a database and organize them for usage in frontend. The GeoPoints are aggregated in segments, the segments in layers, the layers are mapped to drive ids and that map is maped to car ids. The frontend displays all of that nicely, with Tooltips and such. My REST GetMapping method looks lik...
Imagine this use case: I have a class with 50 attributes of which 10 are relationships plus 100 methods which perform calculations and return a value. I need to save that data (including relationships and method's return values) into a database for later retrieval. The idea is to have an snapshot of the current state o...
I am building a fleet unit gps system and currently and i need to figure out how to link my objects. Here is the scenario: Each fleet unit may have attached one or more gps devices. Each fleet unit may have one or more engines. Each fleet unit's engine may have one or two fuel flow meters connected to one or two gps d...
I have producer / worker queue (1 producer, many workers). Currently using Redis, but I dont mind switching to RabbitMQ or anything else. Worker takes a task from queue, runs long running job and confirms that it finished. Now I have a new type of worker which allows cheaper queue processing, but it may not always be a...
I'm currently in the process of architecting a small RPG-style dungeon crawl (in Unity), and am a little stuck on how to update various objects when things change, while not updating unrelated objects. For this question, I will be using my current project as an example, but the question itself can be applied to any sit...
In switching from a procedural background to "FP in the small, OO in the large" I'm grappling with the following problem. Suppose there're modules, each only containing numerical math functions without side-effects. Some functions need the results from functions in another module. Here's a toy example in pseudo-Scala:...
I've been tasked with refactoring a console application, which is constantly running on a server and receiving messages from a service bus. Right now, it just parses the incoming message, and based on a property, will use a switch statement to call one of many different functions (about 70 at the moment, always growing...
In my company I proposed NodeJS for developing a microservice that acts as a bridge between the front-end and a third party chat API, that Microservice will receive large amounts of messages (about 1000 or more) at once, that will have to be able to queue using Amazon Simple Queue Service. I have already developed a pr...
this is my first post on here. I am wondering if there is any disadvantage to using websockets as a communication method for a non-web-based client application to connect to a server? I am looking at designing a turn-based game, using a client-server approach. I would like to design the game server so that different ty...
Currently implemented the model and working on the UI for a scheduling application. This is just an in-house application for work between ~5 people that may occasionally have the application running at the same time. It will be run from the network and use a SQLite database (I understand the concurrency issues and fee...
I'm creating a database schema for a internet store and I wonder how to better create the tables "images" and "products". A simpler way will be to have it as one_to_many, that is: images(....., product_id references products(id)) The more flexible way is to create it as many_to_many. However, I can't think of any s...
I would like to ask what is a prefered way when you have such a code, (this is distributed transaction since I cannot delete the item and publishToKafka atomically), and I don't want to have event sourcing right now: if(exists(Item)) DeleteItem(Item) PublishEventKafka(ItemDeleted) Now obviously if a crash is bet...
I am reading about SOLID principles and have just read that Dependency Inversion (DI, to be distinguished here from Dependency injection, which is one way of achieving the inversion) is an extension to the Open-Closed Principle (OCP). How is that exactly meant, if OCP is about making class extensible without touching t...
I'm working on a Scala project and Wartremover shows an error about Option#get usage in my code: Option#get is disabled - use Option#fold instead While I do understand how get should often be avoided, I think there are cases where it's reasonable to use it, like my current one: First, I create an answer item (in the d...
While trying to solve an issue, explained on the StackOverflow forum, somebody advised me to use dependency injection. For personal reasons, the moment a person mentions to me the usage of a design pattern, I always start thinking of very difficult constructions. After some thinking and investigating, I've invented fol...
Please see the code here and specifically using System.Collections.Generic; namespace DddInPractice.Logic.Common { public abstract class AggregateRoot { private readonly List<IDomainEvent> _domainEvents = new List<IDomainEvent>(); public virtual IReadOnlyList<IDomainEvent> DomainEven...
I'm currently working on a rest service writen in c++/qt and i'm also thinking about the future web ui who will use this service. I admit i'm not super expert in html/js since i've always worked on the back-end side, and i'm not sure how the modern ui patterns are today. As first question i aks: is a html/js only ui (a...
First of all please excuse my english mistakes; it's not my native language. Second, I couldn't find a better title to summarize my inquiry, so let me explain it below: Let's say we have a software that invoices some products. The invoicing process highly depends on the current legislation. For example, the current law...
I have a small question. Which approach is correct in the context of SOLID principles? 1 or 2 ? In the first case, the "CreateTask" method does not return the Task object, but places it on the list that it accepts as the method argument. In the second case, the "CreateTask" method does not accept arguments, but returns...
So an Instanced API is one that behaves like an object. So for example: foo* GetInstancedAPI(); void MemFuncSetter(foo* fooThis, const int arg); int MemFuncGetter(const foo* fooThis) const; This is as opposed to a non-instanced API which would depend upon look-ups: int GetInstancedAPI(); void MemFuncSetter(const int i...
Is there some reliable way to detect device/browser/OS of web page visitors except using the user agent string? This is not for rendering/functionality of the web page/application, but only for statistics (how many percentage of visitors use ipad, iphone, pc, mac, chrome, edge, firefox etc). This can be done either by ...
I have read that using "new" in a constructor (for any other objects than simple value ones) is bad practice as it makes unit testing impossible (as then those collaborators needs to be created too and cannot be mocked). As I am not really experienced in unit testing, I am trying to gather some rules that I will learn ...
Problem I have a Python library which sends XML requests to an external API. If an issue occurs, the API responds with an error containing an error code and description with error details. These errors can be caused by anything from malformed XML data, an invalid username/password, editing a read-only attribute, or try...
With a list of thousands of words and a small list of letters I am trying to find the least amount of words to make use of all given letters, assuming my dictionary of words covers all letters. The first step is obviously to remove all words with none of the letters. Then I approached this by calculating the relative ...
Let's say I have thousands of pdfs that are each about 30k words written in conversational English. In each of the pdfs there is a name / names of a person/people who snowboard. There are also many other names. I need to extract the name(s) of the snowboarder(s) from any future pdfs. What are some tools / methods you c...
First off, I want to say that I am used to doing Procedural Programming as my hobby - I'm trying to learn OOP in a couple languages, and understand the theory, just not the practice. I have a pet-project I wanted to build, specifically in PHP with a database backend (didn't care what one). My main reason was for the ap...
I'm working on a project where I have two programs which need to invoke methods on some of each other's objects. I do this by sending JSON objects over a TCP connection. These objects have a receiverID, methodName, and then a list of parameters. Each program has a HashMap from receiverIDs to actual object instances, an...
I am working on a java server, which has a bunch of seemingly distinct "services". A lot of which are just effectively classes. From a software architecture point of view I wonder what the opinion is on such a setup. Is there any advantage to be gained by splitting the related services off into their own server? Or is ...
I have an API server, and it's SPA client (node+ react, but it's unrelated). All the API endpoints are under /api namespaces, and the SPA just keep make REST calls to perform operations. We're working on a feature which require our users to link their Foo Service 3rd party account through OAuth 2. OAuth 2 requires the ...
Context I am making a service class that essentially functions as a business datetime calculator. That is, it can perform various calculations such as what date is X business days from a given date, when is the start of the next business date, is a given date in business hours, etc. The catch is this class has to take...
I am trying to make some version control locally on my Android project. It is just to have control about my changes, but I do not want to upload them to any external repository. Neither I want to create infernal folders with dates of updates... I would want to use Git, in which I am a bit familiar. I am also familiar w...
I'm still currently learning OOP. I need a method that takes in a List<JsonNode>. Now there are multiple components that need some resources from the List. Component1 needs all of the keys. Component2 only needs the keys that have a numerical value. As we understand, these two both need keys, thus requiring a function ...
I've been programming professionally for years now at several different companies and I consider myself to be a fairly competent programmer. However, of everywhere I've worked there are usually dozens of different software engineers and programmers with dozens of different coding styles, and patterns. I've read tons of...
I am developing a BSD 3-clause library. In the root of the repository, I have the full license text, and at the top of each file something like /* This file is part of <project name>, developed my <me>. * * All rights reserved. Use of this source code is governed * by a BSD-style license that can be found in the L...
We have a system that generates lots of logs and we have to somehow maintain logging workflow in a project. The 'strict' (let's assume it's strict) requirement is that there should be a document describing format for each message and each message should comply to that format. (By format I mean BNF-like things like 'som...
I’ve been wondering about this for a little bit, but I couldn’t find much info on Google. What do big websites like YouTube do to manage all the traffic they get without their website slowing down? How are their servers different than a home web server? Do their servers run off of one network from an ISP or something e...
I have been looking around for some practices to write testable code and gathered the following: • Public methods virtual if not using interfaces -- makes mocking easier • Dependency injection -- makes mocking easier • Smaller, more targeted, choesive methods -- tests are more focused, easier to write • Avoidan...
I have a node app with a queue for processing jobs in the background. I have a file that exports a function which when run, creates a job in my queue. In that file, I also have the handler for this type of job. It looks like this: const actuallyDoStuff = async (...) => { // code that takes time }; queue.process('d...
I have a quite large private codebase which has evolved for about ten years now. I'm not using phpDocumentor but since using docblock sections has become quite the standard in open source projects I have adopted writing docblocks for all public methods in my repository as well. Most blocks just contain a small descript...
I admit this was asked to me in interview a long time ago, but I never bothered to check it. The question was simple, how does Python make Queue thread-safe? My answer was, because of Interpreter Lock (GIL), any time only 1 thread is making a call to get the element from queue while others are sleeping/waiting. I was/a...
My team is in dilemma, we have an existing maven spring-boot Java8 project with following onion architechture. controller --> service --> dao --> jpa repositories | --> filesystem | --> jdbc template Dao earlier using jdbc template and jpa, so it had more than ...
I've been thinking about this over the past few weeks, and I've come up with no good arguments. My perspective is from Java, but if anyone has any language-specific cases outside of this language, I'd love to hear them. It seems to me that the benefit of using a List over a Deque comes from the fact that one can acces...
I'm building a Sudoku generator. I have a board class with a number of methods: public class Board { public Board() { /* Creates an empty board */ } public bool ValidateRow(int row) { /* Checks for errors in row */ } public bool ValidateColumn(int column) { /* Checks for errors in column */ } ... } I'm...
AFAIU a SAAS software is any software which is runs on a browser and performs a certain service, (aside of giving a way to contact the owner of that software) and is also aimed for reuse, whether if it's gratis or not. Is PHPmyadmin, the Database Management Tool (DMA) SAAS actually?
Usually, getters always return the value of a variable. I learned in my literature that access to fields is controlled by getters and setters. When I had my code rated by programmers, it was suddenly said that getters and setters violate object-oriented thinking. So far, I have always set the output-statements in the m...
I have a set of services that are used to read/write to the database. These get injected into my controllers: ISystemSettingService _systemSettingService = null; IStatusTypeService _statusTypeservice = null; public MyController( ISystemSettingService systemSettingService, IStatusTypeService statusTypeservice) ...
I recently asked this question: https://stackoverflow.com/questions/48582699/equality-for-a-dateofbirth-value-object. I am going to avoid a DateOfBirth value object. Instead I am planning to use a type alias. I have a few options with regards to my constructor: Option 1 using DateOfBirth=System.DateTime; DateOfBirth...
If I write an application and decide to develop only a single graphical interface for it, and never intend to develop multiple GUIs, then by today's standards it is okay not to use the MVC pattern or MVP pattern, or should you generally prefer the MVC pattern for object-oriented software with output? The advantage of t...