instruction stringlengths 34 36.1k |
|---|
I'm trying to learn the best practices for code design and reuse in C++ so I am going through the well known GoF Design Patterns Elements of Reusable Object-Oriented Software.
I noticed that nearly all design patterns use dynamically allocated objects. To prevent memory leaks, I'm leaning towards using shared_ptr for a... |
I am seeing bad practices occurring in our version control where my colleagues are creating their own versioning system with stored procedures so that they can compare results before/after changes and we end up with multiple stored procedures in the database with slightly different names e.g. StoredProcedureV1, StoredP... |
Is it good/bad practice to add more constructors just for test purposes (to mock the DOCs used in my SUT) like this :
public class A {
private B b = new B();
private C c = new C();
public A(){
}
/***
* used for test puproses
* @param a
* @param b
*/
A(A a, B b) {
//... |
I'm working on a service which has a lots of dependencies. The way how I call them is I'm wrapping each service client around an Adapter. Like this (I'm using Java):
public abstract class AdapterBase<Request, Response> {
protected abstract String adapterMetadata();
protected abstract Response makeActualCall(Re... |
So, first let me explain my current setup. I have an unmanaged ethernet switch which is connected to my intel nuc (server A) and an external had drive.
Server A is running:
Ubuntu
Docker
Gitlab container (I push my code to this, it builds an image adds it to docker and then replaces the old version)
My website is ge... |
The language is PHP. I have several functions that relate to each other (and sometimes use each other) that I've decided to couple under the same class.
Here are my reasonings, do keep in mind that I'm limited by what I don't yet know in terms of how my code will be used:
These functions have no clear need for a class... |
Our react web application is broken down to multiple components. Some of these components are part of the same git mono repo and some live in a different repo.
Now, to implement a bug fix we have to update the changes in one repo, release a version of the package, update the tree of dependencies, release other interme... |
I am working on a project on both iOS/Android/macOS/Linux (Windows is optional, and surely no website version). There are a lot of related webpage-like data and the team decided to store the data in a specific markdown format (not the ordinary *.md format) to meet the requirements in the specific domain being dealt wit... |
so I am in a position where I doubt my solution to the following problem:
- we are developing a wpf desktop application with c# and have a decent plugin system. This increases the libraries we have in the system (multiple git repositories, multiple libraries). The libraries are then packaged to our local nuget server.... |
I'm working on a project at the moment and I'm using this project to try and apply DDD. However, there are parts of my implementation that I just can't get my head around or don't feel right. I'll try to describe how I currently have my application setup;
In my domain layer, I have my aggregates, value objects and a se... |
I looked multiple places for some advice on how to solve this before asking this question, but I couldn't find something similar to this.
So I have the following scenario in Java Spring Integration
Let's say I have some super class type
class Foo {
private String error;
public Foo(error) {
this.error = ... |
Context
At my company, we have a major Python package which is written in Python 2. We are now planning to migrate it to Python 3 (we don't care about keeping it Python 2 compatible).
I am a junior developer and my coworkers are senior people, who don't have a strong computer science background.
Issue
During the planni... |
Suppose that:
you invent a new coordinates system and you create a class to represent it
you have two products which need to deal with this coordinates system but which, apart from that, are completely independent
Then, how do you share this class among both products?
I think this question can receive a generic answ... |
Rather than writing a monolithic code, I've been taught to find the parts of code which can be reused (in the same code or in others) and create a function based on them, which should perform "one and only one" task. Is there a term for this programming style? Modularization? It's definitely not functional programming,... |
Within an organization, suppose you have an internal tool used by different teams and for different use cases. This package offers APIs in different languages.
One could say that having multiple APIs enables more people to use the tool, as they don't have to learn a new language and can use their favorite one.
On the ... |
I'm doing code review on a change my co-worker made to our Java application, and I've found something I'm not very familiar with - a nested class.
From reviewing the code, it seems like the nested class is being used as if it were a normal class - and asking my co-worker about it, the reason for putting it in as a ne... |
I have a library, which sends and receives a set of binary messages and parses them.
So far I’ve used inheritance for my design, i.e.
class BaseMsg
{
// init msg from rx'd binary stream
virtual bool fromBinary(std::vector<char> b) = 0;
// write msg content to binary stream to tx
virtual std::vector<cha... |
May I be so bold as to ask (from an amateurish point of view), what is the general strategy for dealing with potentially ever expanding domain models?
By way of example, I have Staff, and in the beginning they could just have have a department (although sadly, in reality, it had to be a List<Department> because it's n... |
In React, when rendering a mapping from elements of a list/array/iterable to React elements, we're required to attach a locally-unique key to each element. Generally this is so that if an element changes or is removed, React only needs to rerender that specific element rather than the whole list. This key is required... |
I need to insert some records into a database at a time when it normally it's not being used, what are some approaches I can take? I have considered using the SQL Server Agent to run some stored procedures, or I could schedule a program to do the insertions too, ideally if the process takes more than 1 hour It should b... |
The project I am working on has a status field which currently only allows YES or NO, and I am about to refactor it to allow the value MAYBE. Unfortunately, it is used over 1,000 times in 200+ files.
Typically the status field is just displayed raw, but occasionally there is some logic that goes along with it. Because... |
Currently when I build applications, I build them as one big monolithic application such that everything resides in a single compiled assembly and the data resides in one single SQL database (with some redis/elasticsearch used as support). This works relatively well for my purposes, but I would like to move towards des... |
I am in the process of writing a web app to track expenses and which will be multiuser.
Everything is fine with a single expense, but I am struggling to find the best way to represent recurring expenses, i.e. expenses of the same amount and category that repeat regularly until cancelled.
I am thinking to model recurrin... |
I found that it is so hard to test classes that depend on other utility classes
as java.nio.file.Files. It is also impossible to mock them using the classic unit testing stack (junit,mockito,..) unless you use other heavy mocking frameworks like powermock which i consider a bad practice in case of building projects fr... |
I want to create a dictionary application.
One of the design guideline is performance in querying and showing up the definitions of words.
I would like some suggestions on two design choices:
Which serialization format should I choose?
I'm thinking of JSON(or YAML)I checked on popular opensource dictionary application... |
In my service class I would like to connect to external API. Where and how should I do it?
1) Inject in constructor ExternalClass and assign to private property. Next in other property in constructor call connect.
public MyClass(ExternalApi externalApi) {
this.externalApi = externalApi;
this.ExternalApiConnect ... |
I'm new to DDD, and I'm confused at the very start of my DDD project. To setup a context, I'm building the user management part of my app, so I'm building my Account entity, which contains an Id, a username and a password.
public class Account: IEntity<string>
{
public string Id { get; }
public string Username ... |
I am trying to understand two sequence diagrams that I have found in the SE course at university of Washington. Can you confirm if my understanding is correct ?
Diagram 1:
According to my understanding , this sequence diagram describes the dispatch process of orders to either of two distributors. First of all, there ... |
I have one method which need to return multiple values whether it was successful or not, what the key used to call the api and if successful the return result. Here is more concrete method,
public xxxResult PublishMessage(){
// dynamically calculate the key
try {
// call the third party api and get the ... |
I am currently working on a C++ project with a source file structure like this (headers excluded):
src/
├── namespace1/
│ ├── namespace1_base.cpp
│ ├── namespace1_derived1.cpp
│ └── namespace1_derived2.cpp
├── namespace2/
│ ├── namespace2_base.cpp
│ ├── namespace2_derived3.cpp
│ └── namespace2_derived4.cpp
... |
I've been reading on instagram's approach to generate unique identifiers.
Besides remaining content I'd like to understand on of the points their making as a con of client-generated (by client I mean here an app-server, not untrusted userland), specifically:
Generally requires more storage space (96 bits or higher) to... |
I'm developing a ICalendar service. If i add the URL in outlook everything looks correct, but if i import the URL in Google calendar it does not show the description of event.
As google calendar takes up to 24 hours to sync with external calendars it makes it very difficult to test/debug what might be the cause.
Any id... |
I have been stuck on this question for some time. Could you guys direct me or point me to the right direction for solving this problem ?
We would like to encourage passengers to experience the joy of travel using our transit system, therefore we would like to determine the longest path available to advertise the public... |
I was going through the ThreadPool pattern and it resembles the Object Pool pattern. The only difference that I can think of is that most explanations about the ThreadPool explicitly mentioned the use of task queue while the Object Pool pattern is not explicitly stated. Can someone please explain to me the difference b... |
I am working on configuring the build environment for a C++ project that uses multiple libraries. These libraries are independent of each other, but they all depend on the same 3rd party library (GTest) for testing. I am having some trouble determining where I should put this 3rd party library so I will have the most f... |
I've read https://bugs.python.org/issue33098, which is about the following behavior of Python 3
a = {'1': 42, '2': 84} # keys are str on purpose, c.f. the issue
import random
random.choice(a.keys())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/nix/store/.../lib/python3.7/random.py... |
Disclaimer: There are some similar questions, but I didn't find any which touch specifically the problems you face while reviewing a large pull request.
Problem
I feel my code reviews could be done in a better way. I'm particularly talking about big code reviews with many changes across 20+ files.
It's pretty simple to... |
I want to understand the consequences of allowing handlers to be direct or indirect source of new domain events.
In all examples I see in the literature Domain Events are usually published by Aggregate Roots. Actually, events may be just returned and then later be published before or/and after transaction is committed.... |
I do not know the "correct" name of that pattern, so I'd like to describe it with a simple example.
In C#, System.Windows.Window contains a ShowDialog method. I can define an interface containing this method (plus some other functionality). When I create a new Window class, it will inherit from Window, and I can add my... |
It can sometimes ease readability to "draw" lines in a logfile. For example:
noise
noise
----------------------------- Starting Operation ABC
blabla
blabla
----------------------------- End of Operation ABC
noise
noise
Obviously, this should be used sparingly (otherwise the lines don't stand out or sections could over... |
The underlying problem is one I seem to run into a lot. You have a collection of objects with some things in common, but other information about the objects may apply to some of them but not to others. Furthermore, as the application grows, the amount of such information is certain to grow over time. The challenge is t... |
Generally I would always answer "yes" to this question, because at this point, your DI container has become a service locator, and you're losing the benefits of DI.
However, I wonder if it is acceptable in the following specific scenario.
I have an application with a DI container.
The DI container is responsible for c... |
So ran into an issue with circular dependency that looked like this:
public class A
{
public List<B> Bs { get; private set;}
public void AddB(B b)
{
Bs.Add(b);
}
public void RemoveB(B b)
{
Bs.Remove(b);
}
public int DoWork()
{
// Need details of B
/... |
I am writing an IMU device driver in C using test-driven development methodology. As part of the driver, I pass a struct with user selected configuration settings to an initialization function which configures the device by writing into its individual registers.
Using my interpretation of approach described in James Gr... |
The title says it all really. If asked to produce an estimate for a project when is still very unclear what the system is, what do you do? Would you refuse to provide an estimate? Or inflate it massively? On this occasion it doesn't appear I'll have the opportunity to obtain clarity around the system.
|
RFC6530 defines the necessary steps for "international e-mail" (i.e., especially for UTF-8 e-mail addresses). Apparently Google adopted the RFC back in 2014 (source). Still, most validators I find on the web are having trouble with international e-mail addresses to say the least. One very popular contender is HTML5's i... |
Imagine we have a website happy-cooking-together.com. (I made it up so if becomes available all of a sudden don't take it for real.) It's getting quite a lot traffic and multiple teams are working on it. The codebase has become huge and mostly unmaintainable so each of the teams struggles in its own way. Some lack mod... |
Where/how do you draw the line for unit-testing classes at different levels of a hierarchy? For example, let's say you have a structure like this:
public class Account
{
public Money CurrentBalance { get; } => ComputeBalance(_transactions);
public Money BalanceByDate(DateTime date)
{
// ComputeBala... |
I'm struggling to understand how a ReactiveX operator can be considered functional.
Operators are implemented as functions, but but with the exception of simple operators like map and reduce many of the operators do not appear to me to be implementable as pure functions.
A simple Buffer operator that buffers 2 items a... |
I am having a hard time looking for resources on why I should use dependency injection. Most of the resources that I see explains that it just passes an instance of an object to another instance of an object, but why? Is this just for cleaner architecture/code or does this affect performance as a whole?
Why should I do... |
I have a project which has a service-oriented architecture. for example, anything relates to payment is inside payment module.
-dao
-config
-constatnts
-middlewares
-modules
-payment
-user
-bankTransaction
-...
-routes
and expect of mongoose models, all codes are inside the module.
now I want to use mongoDb se... |
I've recently started learning about microservice architecture. API gateway is a pattern usually proposed for aggregating data from different microservices which own their data stores. However I wasn't able to find anything about being able to do that in a configurable way.
Scenario:
Customers should be able to define... |
We have a legacy site that was written a while back using MVC. It's a valid MVC for the most part except for the Data Access Layer. The site has Models, Views, and Controllers. However, instead of using Entity Framework, they use web services that use ADO to execute stored procedures.
For example: say we have a page to... |
From what I've observed, methods that start with the word "On" fall into two categories:
A base class that defines an event will expose a protected method whose name starts with "On" followed by the event name in order for derived classes to be able to raise the event.
A base class exposes a protected virtual or prot... |
I have a question about MVVM design, and where I should put some code that I would like to add.
My application queries active directory for computers and displays the list to the user. Selecting a computer displays some general Active Directory and WMI information about that specific computer.
Currently, I have a “Main... |
To me, equals() between objects of inconvertible types is one of the most useful IntelliJ inspection.
It's almost never intended to have objects with different types equal to each other.
I understand equals method was introduced prior to Java 5 so there is no generics to leverage. But even the new null safe Objects.e... |
I have the implemented a calculator that is very similar to the following UML diagram. The only new thing is a new class, a Recognizer class, that says if the expression is written correctly or not.
I have applied a factory design pattern for the operations Add,Sub,Extract,Division but I'm also interested in applying... |
My api is exposing information centering around an entity Company. Companies are complex, and can contain Vendors directly, or can contain sub-companies which contain vendors themselves.
A consumer of our API has asked for the addition of several new endpoints from which they can request information about a company and... |
I am building an application that aims to process ~10M data items per second.
Each item is exactly 42 bytes small (including a sorting key) which means the total data rate will not be big 420 MB/s.
The data structure entries are supposed to be sorted (either descending or ascending). Duplicate keys will be possible (mu... |
Actually what i'm doing in my code base is duplicating already existing java checked exceptions like MalformedURLException.class by keeping the same exception name while inheriting from RuntimeException.class . Sincerly,i did not find a better way.
I found that really bad,because i've now nearly 8 exceptions duplicate... |
I'm an amateur programmer. I have a lot of interest in the inner workings of operating systems, a subject that I've been reading a lot about.
What I've understood about kernels is that on most operating systems, a process is not able to access the hard disk (or other storage media) directly, but rather through system c... |
I'm working on a project with huge files that contain only the set {[0-9],.}.
Encoding in UTF-8 or ASCII make huge files.
I wonder if I could find a way to encode in only 4 bits (make those file 16 times smaller). I would have enough of 16 characters!
How could I proceed? I'm working on python and I have tried the foll... |
I love the Material-UI library, but some things that I've found annoying:
I find Typography too long to write out, especially when I'm having to specify things like gutterBottom, align, etc. Whereas <H1> is much shorter, and I can always do manual overrides.
With Typography - I end up having to add a class to it any... |
I've been trying to design a database to go with a project concept and ran into what seems like a hotly debated issue. I've read a few articles and some Stack Overflow answers that state it's never (or almost never) okay to store a list of IDs or the like in a field -- all data should be relational, etc.
The problem I'... |
I am busy developing code that processes a bunch of objects that represent monthly reports for regions (e.g. one instance per region per month). Let's call them RegionMonthlyReport objects. At the end of the month, a new set of RegionMonthlyReports need to be created for the next month that are populated with values fr... |
I am not as technically skilled as most people asking here. I use git to backup my own work to an online repository, but I rarely use it in collaboration, and don't know much more than the basic functions.
I have some code (think more like a gaggle of scripts, really) that I use to do some data processing. Frequently, ... |
In the company I am working in we have a management software, written by an external programmer. Let's call the software PK.
PK was initially written in the 90s using C++. Since then it was regularely updated and maintained but in its core it always remained a software based on 90s technology.
We are currently in the p... |
Suppose a large-scale project is being developed in Python 3.7. Some layered architecture is chosen: "clean architecture", "onion" or "hexagonal". The Dependency rule in it only allows inward-looking dependencies; http://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html.
In some languages this ru... |
I design a new Rest API for a personal project and I am trying to implement the authentication and authorization mechanism as a separate project, so I ended up with a couple of problems which I am trying to solve
The first one is related to the validity of JWT. When the user logs in the application, the app generate a... |
I'm working on another tutorial: if l used a computer with an SSD-hard-drive containing an instance of Ubuntu 18.04 LTS installed with a set of Nvidia GPUs loaded with the Nvidia-CUDA toolkit but swapped the SSD-hard-drive for a second SSD-hard-drive containing a separate instance of Ubuntu 18.04 LTS and loaded with di... |
How do you properly reference an entity inside an aggregate? For example, by the index of a list (doesn't seem smart if you re-order the list); a GUID (thought it was supposed to be local?); or some other incrementing counter?
For example:
class Cart
{
public IReadOnlyList<Item> Items => _items.ToList();
public Ad... |
I am wondering why multicast messages like the membership query and the membership report have a TimeToLive setted to 1. I mean: messages like these shouldn't be retransmitted over the net (for example to alert other router that there is a group who wants to receive multicast messages).
|
I have a couple of classes that I've nested together (not in the sense you may think so bare with me), to create what I call a prefab object (similar to Unity's prefab system).
In this particular case, I have a prefab called BarkingHorse that contains its own instances of objects CullingBird and DivingWeasel. All of th... |
I am very new to Machine Learning. I've read about it and I successfully did a tutorial where we looked at the dimensions of Iris petals and predicted what other Iris petal sizes may be. This all made sense because we were just looking at numbers.
I'm having trouble taking the next step. Ultimately the project I want t... |
For the past few days I've been researching the relationship of abstract classes and dependency-injected via the constructor classes.
It appears that any time that I can have a dependency-injected class:
public interface IServiceC
{
void methodC();
};
public class ServiceC implements IServiceC
{
ServiceC(IServ... |
In comments on In C++ do you need to overload operator== in both directions? Story teller waxes enthusistic about the simplified oveloading provided in c++20 with the <=> operator.
That's why operator <=> generates so much excitement. Because it can cut down on a lot of boilerplate
So with one step (and function) we ... |
I found the standard REST API best practices to be very confusing, because you need to know all the HTTP methods such as GET/POST/PUT/DELETE/PATCH etc. Not only that, while calling an API, you might need to provide the following:
Body
Params
Querystring
Headers
In my opinion, this is not only confusing for the server... |
I have to maintain an old application and have to extend some modules.
There is an hashtable that is used for maintaining/holding some objects as representation of running (real) processes (don't see them as plain software processes).
It was easy:
if a new process was created it was added as name + the object
to know... |
I'm a software engineer in a company.
However, I'm planning to start a self project very soon.
I wonder if I am allowed to re-use the code I have written in my company product in my project.
It is not going to be the same functionality or feature.
It's just a basic thing.
For example: A way to handle errors on the back... |
A service A needs to access services B, C and D to process a request. Currently this is implemented as parallel async calls from A to B, C and D. Once all of them has responded, service A follows some business logic to create a final result from partial results received from B, C and D. The final result is then written... |
In my application, I have a few classes. Many of these classes share common state like a reference to the logger for example. For example, both A and B require some common state to get their job done.
class A {
Logger &logger;
CommonThing &thing;
public:
void performTaskA();
};
class B {
Logger &logger;
Com... |
I am writing a finite element software in C++ and Qt. I want to load the input data to the model. I have a Model class that holds the data and does the work. I have created a simple lexer and parser to read the input file (things that resemble database records). I don't have the experience to make an informed decision ... |
I have a following class in my PHP code:
<?php
declare(strict_types=1);
use function Http\Response\send;
use Psr\Http\Message\ResponseInterface;
class ResponseSender implements ResponseSenderInterface {
public function __invoke(ResponseInterface $response) : void {
send($response);
}
}
The interface ... |
I'm reading about property based testing and I'm wondering how can I test this my code using that paradigm.
class Invoice {
private final String id;
private final String companyName;
public String name() {
return id + "_" + removeDots(companyName.trim());
}
}
I want to test Invoice::name met... |
We have to migrate an old (million LOC) system from SAP ADS (formerly Sybase) ISAM based (so called free tables) based system to a PostgreSQL database.
The system implements kind of multitenancy regarding putting some basic information (chancellery ID, client ID, fiscal year, etc.) just into the windows folder paths an... |
I'm doing a project where I have to control a live DALI controller and I'm sending data from the website to the controller with Websocket.
How do I know what Websocket to use?
At the moment I'm learning websocket, and going with the "socket.io" module running it with nodejs.
|
I develop largely in java which has maven or ant/ivy. Is there a recommended way to manage build dependencies for c++ projects? I'm setting up the build on our build server right now but the thing that comes to mind is that if the dependency libraries change how do I track that so old builds are not affected but new on... |
A follow up to another question (Making a design decision about reading model data from an input file).
I wish to ask another question regarding builder or factory pattern. (I read that builder is more complex than factory, and I may not need to use builder for now). So here is the data I have to read:
TABLE: "DEGREES ... |
We have n C projects which reference 4 different versions of a device SDK - 12.3, 13.1, 15.0, and 15.2. There is no public upstream repo for the SDK - it is released as a zip file. We need to patch the SDK to work for our particular needs, and would like to minimize copy-paste code sharing.
I would like to put the SDK ... |
I want to model an activity that involves processing several items in parallel. So to speak, I want to find a Activity Diagram representation for something like the following snippet / pseudocode:
items = findAllReleveantFiles();
handle = threadPool.map(processingFunctionPtr, items);
result = handle.join();
I.e. at th... |
We are a web SaaS company using gitflow and JIRA. As we are 'done' (QA approved) with a feature, we move the story/ticket forward in Jira to a 'done' status. At that point we wait until it gets approved for release which means a developer merges that to develop and will get assigned a fixVersion in JIRA. As bugs are fi... |
I have a doubt about the architecture of a web app when it comes down to differentiating between regular website requests and API requests.
For the purpose of explaining, suppose I am the creator of a service (let's take darksky.net for example). I offer both a website and APIs.
On one side I have my API endpoints, for... |
Consider the following example (very simplified):
public class Basket
{
private readonly List<BasketItem> _items = new List<BasketItem>();
public IReadOnlyCollection<BasketItem> Items => _items;
// _items.Sum(item=>item.TotalAmount)
public decimal TotalAmount { get; private set; }
// ...other prop... |
A developed piece of code goes these phases in our team:
Developers write the code
Then they send it to testers
If tests pass, then testers send the change/new feature/bugfix to operations team for deployment.
Currently, we've adopted the following approach:
We have a master branch from which we create one or more c... |
I have a relatively simple front in good ol' JQuery, that makes a POST Request to a Flask Python web server, that runs a Python script using the subprocess module. Here's the whole route for illustration:
@app.route("/adyen_request_download", methods=["POST", "GET"])
def adyen_request_download():
merchant_manager =... |
Imagine we have a service like the this:
class SomeService {
// A random pure function that transforms the input
// without doing any remote calls or any side effects
function somePureFunction(inputNumber) {
return inputNumber *2
}
}
Now we are using it by registering it with a dependency injec... |
I have an engine and if I want to use the 3d system I always have to pass a pointer to any mesh renderer. If I would make the 3d system static then I just could use them. But the 3d system is big with lots of stuff and resources. I know static fields stay in memory until the end but the graphics system is used all the ... |
We have a system which has been in development for 10+ years and still continues. It is built as an SOA and use SOAP. We have a new client, internally within our company, who wants to integrate with our application. Since JSON and REST are the sexy and new thing, they want to communicate with us using HTTP, following R... |
I am having difficulty understanding which design pattern would be best for the following scenario. An application uses a database. That database can either be the production version (SQL) or a test version (Test). Here's my current design:
The problem with this design is that application has to create Test, which it ... |
I am testing a red-black tree implementation (repository) and I find that with Windows 10 and gcc, malloc starts returning NULL after inserting approx. 50 million nodes but on Linux it works at least up to 100 million nodes.
What conclusion can I make from this result? Is it a bug in my program or is it that malloc is... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.