instruction stringlengths 34 36.1k |
|---|
I heard that you should avoid leading newlines when using printf. So that instead of printf("\nHello World!") you should use printf("Hello World!\n")
In this particular example above it does not make sense, since the output would be different, but consider this:
printf("Initializing");
init();
printf("\nProcessing");
p... |
Basically what this code does is to determine whether the user is allowed access to the page or not from list of pages as enum, each one has the role name as its name and the page name inside it.
The problem is that I don't think this is the best practice to write this code. why? basically if a new role is added I'd ha... |
Some of the Java libraries I have used so far seem to have a Factory for seemingly every other class in the library. Apache's FTP Server project, for example, provides a UserManagerFactory class which allows for configuring a prototypical instance of the UserManager class and creating copies of said instance - at least... |
I'm refactoring a settlements module in a large healthcare application. I'm trying to follow DDD.
Let me give you a short and simplified description of the refactored code:
A patient has an appointment during which they undergo several medical procedures. Every procedure has its price.
The patient can pay money to the... |
Let's say I want to design a distributed system whose only purpose is to assign each running node a unique identifier in some small range (Say, 5-100 nodes into a 10 bit identifier). When a node is added, it should get an unused identifier. We need to support more than 1024 nodes being added then removed, so of course ... |
Is renaming variables a type of refactoring, or is refactoring something different? In other words, what's the difference between renaming and refactoring? I thought they were the same thing.
"Code refactoring" mentions renaming only here:
Rename method or rename field – changing the name into a new one that better re... |
I have a ConstraintsResolver class which resolves a queue of Constraints. This is done when a ConstraintsResolver object calls meetConstraint() on a Constraint one.
Most of meetConstraint() implementations will return immediately, so I could just return a boolean, but there is at least one that will block, which means ... |
I'm trying to architect (breakdown) one application we have at my work in a few microservices. Before starting going down to the rabbit hole, I wanted to ask: when is a good idea to create another model+function instead of creating a microservice?
Creating a microservice involves more work than just a few other functio... |
My teammate has this class which contains a lot of Strings:
public class Config {
/**
* List of status
*/
public static final String IN = "bla*";
public static final String LUNCH = "bla*";
public static final String OUT = "*bla";
public static final String MEETING = "*bla";
public sta... |
My question is around how branch pushes work exactly; I have come across something that doesn't make logical sense to me and as such would like an explanation as to why I am experiencing this behaviour.
I have two branches: master and dashboard.
I am on (checked out) dashboard. I make some changes on it and (using the... |
Suppose we have a service that returns users in certain categories, e.g.
Listens to a certain artist.
Listens to a certain playlist.
Listens to a certain genre.
Is between ages X and Y.
Is located in geographic area Z.
Suppose an external CategoryService manages valid categories, and we use a CategoryServiceFixture f... |
I have a REST API that has been built on top (in front of) a legacy system, to allow 3rd parties of various platforms to interact with the system.
Most of the time, I can define a resource and create a GET and POST/PATCH etc. However, I have a couple of cases where the GET needs to be able to handle potentially a large... |
I realize that DDD advocates eventual consistency, thus allowing for a certain period of time in which the system might be inconsistent. Embracing eventual consistency, we can therefore model our aggregates in such a way that only 1 is updated per transaction.
However, my question is, what if the relationship between m... |
I am maintaining a public API and have to deprecate a method.
Is there a general rule on how many months/years/versions before the deletion I should deprecate a method?
|
I am making a websocket server that can communicate with clients.
This server is going to be on a private vLAN channel on a public place, AKA only the staff have access to the network which the server is on.
When this is the case, do i need to implement SSL or any other form of security, if the "hackers" cant get acces... |
I have a class named Change which should be abstract and have some basic methods.
I have classes Insert, Update and Delete that extends Change.
In the case of Insert, Update I just use extend and add no logic!
public class Insert extends Change {}
In the Delete class I have an extra method that doesn't exist in the Ch... |
I'm running into a design problem. My code is in C# but the concepts could apply to any OO language.
I'm designing a framework to run experiments, and these experiments have several variables which we will manipulate, and several variables that we will calculate after manipulation (like columns in an excel sheet). Each... |
I was refactoring an application to respect SOLID principles. When I was applying interface segregation I found the following case:
interface A
{
void methodA();
void methodA2();
}
interface B
{
void methodB();
void methodB2();
}
interface C : A, B
{
void methodC();
}
interface D
{
void m... |
Requirement
There is some (for arguments sake) “global” application state that I am interested in injecting into components.
Each candidate component should receive an immutable snapshot of the state as it existed at the time that its constructor was invoked (for absolute clarity, the state snapshot that is injected i... |
I have two classes, Bar and Baz. Both subclass the abstract class Foo which has a method doThing(). Bar implements a functional interface Now which contains method doThingNow() whereas Baz implements a functional interface Later which contains method doThingLater(). It's likely that I will have more classes down the li... |
I have a AR called User, which has among other entities one called City.
The way I assign a City to a User is:
$user->addCity($city);
The problem comes when a id is given at some Controller endpoint instead of a City entity, I can't relate them if it's not through an instance and I can't retrieve the entity intance wit... |
I have a branch (dashboard) which I am developing a new feature on.
To make the example easy to follow, I am developing two separate functions (function1() and function2()).
They work how I want them to, but I now want to attempt to merge function1() and function2() together to make new_function() because I think it wi... |
I face an issue if to use a decorator or facade pattern to accomplish my needs.
Imagine a client wants to play a video. He can use the interface
public interface IVideoPlayer
{
// Prepares everything to set up and plays the video
void Play();
}
The client should not be concerned with the preparation, so the i... |
My program needs to execute a sequence of steps from start to end. But based on different input the start point will vary, e.g, some will run from the first step to end, some will run from the 2nd step to the end, some will run from the 3rd to the end, etc.
I just need a simple design, currently I use fall-through swit... |
My team (yet) did not do much to work on technical debt and our code base includes huge amount of TODO code, unused code, 'could get better' code, @Ignore unitests and more.
I am about to start dealing with those issues, and as we work on production product and have many other things to do, i was thinking of this strat... |
I'm learning to program the Game Boy Advanced (an old Nintendo console.) I was reading one of the best tutorials about it and it said this about how branching can be done with arithmetic.
[To optimise your code] avoid branches. Things that redirect program flow (ifs, loops, switches) generally cost more than other ope... |
When writing web applications I place business logic in controllers. This has worked well for my small App Dev team- our applications run reliably, perform well, and the code is easy to maintain. See below for an explanation of my design.
Contrary to my architecture, the advice I find in programming forums usually ad... |
Is it wise to use kafka as the 'source of truth' for mission critical data?
The setup is:
kafka is the underlying source-of-truth for the data.
-querying is done on caches (I.e. Redis, ktables) hydrated from kafka
Kafka configured for durability (infinite topic retention, 3+ replication factor etc)
architecture follow... |
I currently use the following naming scheme for my unit test projects.. if I have a project "MyApp", I will have..
-- MyApp
-- MyApp.Tests
I see this is quite a common practice.
Now, the problem is, if I then have another project MyApp.Common. Now in solution explorer, my projects are sorted
-- MyApp
-- MyApp.Common
-... |
I have a server-side service (using ASP.NET Core) that should provide a REST API to various clients.
Behind the service, I use a SQL server for data storage.
The controller has the following route attribute:
[Route("api/[controller]")]
[ApiController]
public class CustomDataController : ControllerBase
{…}
There are da... |
I will use the reference tables for the first time so I have some questions about it.
Example Table
------------------------
id | description |
------------------------
1 | Some description1 |
2 | Some description2 |
3 | Some description3 |
------------------------
1) In order to increase code legibility I wa... |
I have a temporary report table which has a foreign key (source_id), e.g. report table:
| id | val1 | val2 | source_id |
| -- | ---- | ---- | --------- |
| 1 | 102 | 0.5 | 1 |
| 2 | 99 | 0.9 | 1 |
| 3 | 212 | 0.1 | 2 |
and example of source table:
| id | descr |
| -- | ------- |
|... |
What algorithm does a video player use to find the subtitles to show at any given time?
I'm building a video player that displays some notes on different times over a video. Each note has a starting time and an ending time, just like subtitles.
I'm having issues coming up with an algorithm to find the all the "notes" w... |
malloc and calloc have these signatures:
void* malloc( size_t size );
void* calloc( size_t num, size_t size );
They do basically the same thing. Both allocate a chunk of memory of the specified size and return a pointer to that chunk. The difference is that calloc initializes the whole memory to zeros. Actually, callo... |
Can anyone tell me which one is better approach between synchronization method and private final object in java and why ??
public class kclass {
private final Object myObject = new Object();
public synchronized void show() {
...
}
public void show1() {
synchronized(myObject) {
... |
Does anyone know a term for these kind of user interfaces? Some examples:
old BIOS menu of PCs
safeboot menu of windows
other old MSDOS applications running on fullscreen using "keyboard navigating menus" (like accounting softwares).
What is the technical term for such types of interfaces? This could be helpful whe... |
I am currently in a continuous software product development project on base of legacy Java code. The source code is very complicated, which is good and bad.
But I am surprised to see that in the core component most of the classes contain thousands of lines, not one thousand of lines but usually over 5000 lines, in only... |
I need to design an AST-like class hierarchy for the introspection of code (like the Java Element API used during annotation processing). But I'm unsure how to make it maintainable and easy to use.
My instinct is to model the language as closely as possible and take full advantage of the type system. In order to do th... |
I was recently looking through the CPython source code and noticed something rather intriguing:
/* Minimal main program -- everything is loaded from the library */
#include "Python.h"
#include "pycore_pylifecycle.h"
#ifdef MS_WINDOWS
int
wmain(int argc, wchar_t **argv)
{
return Py_Main(argc, argv);
}
#else
int
ma... |
Our team has different opinions about the practice of using self-defined exception for handling the business logic.
Someone says it is good as the exception comes meaningful and readable, and the opposition thinks it is redundant to define every possible exception and catching exceptions is performance hurting.
Would... |
What is a firmware design document (FDD) in terms of an embedded system?
I am working on developing an application that would be working on a customised board similar to the Xilinx Zynq Development Board(running on Arm Cortex A9 processor). I am using the SDK IDE provided by Xilinx which provides some in-built librari... |
Let's say I want to parse some JSON and I store the path in a Java constants class the path that I want to follow.
For example:
public static final List<String> path = Arrays.asList("a", "b", "c");
so that I can do this (pseudocodeish):
public boolean checkSomething() {
JsonThing json = ...
for (String pat... |
For example, suppose I have a toggle button listener, and it has some tasks to do according to the state of toggle:
style 1 : use many ternary operator:
tutorialModeToggle(isTutorialOn){
SoundUtility.play(isTutorialOn?"s1.mp3":"s2.mp3");
this.titleLabel.setString(isTutorialOn?"(Tutorial Mode)":"");
this.tut... |
To introduce some license levels (organization, computer, user), I need to pinpoint information that identifies the object (organization, computer, user) without user interaction.
To identify the user for a user based license, I have used the user name, domain (either AD domain, or computer name), and user security ID ... |
I want to program a simple budget application. In my application, the budget is divided into budget periods (months by default, but it can be bi-weekly or weekly periods). In each period there is a list of spending categories.
The user can perform different action on a category, like to record a spending, allocate bud... |
Coming from the world of C and C++, most build system have an install target, notably Makefiles (where it is recommended by GNU for example) or CMake. This target copies the runtime files (executables, libraries, ...) in the operating system (for example, in C:\Program Files\ on Windows).
This feels really hacky, since... |
I have multiple methods that could fail, let's say :
readFile()
parseFile()
compute()
Each of them could fail (e.g file not found, wrong file type, wrong data), should I put each of them in their own try/catch block or should I create one try/catch block then switch the error and log/display text depending on the err... |
I'm making contribution to an opensource project by one of the leading hypervisor providers and I have noticed that there is awfully lot of repetition.
Below is what I mean by it, imagine that they do this multiple times in the same class and then across other classes.
def get_some_stuff_type_A(self, name):
"""The... |
Assumption: Each product codebase is in a separate repo. If the product codebase was a mono repo, it would be a no brainer to just put them together.
Assumption: Integration tests in this context would include end-to-end UI-layer tests (e.g. Selenium) and end-to-end API-layer tests (e.g. GraphQL/Rest). Tests requires r... |
I'm currently building a new application and trying to apply some of the principles of Clean Architecture. One of my first roadblocks is implementing my own Identity system (to avoid being tightly coupled to the AspNetCore.Identity library.
One of my concerns is password hashing and generation. I'm looking at followin... |
I am currently working on a bare metal project with an arm processor using GCC arm compiler. If I call malloc, is the allocated memory tracked in the MMU? For some reason I had assumed an OS typically handled this but since the call to malloc compiles and I see it is defined in the libc/usr/include I am now thinking th... |
I have kafka consumer that get data from kafka and do some process if some circumstances meet and send it for another consumer to do it's job.
How can i build something like this?
One way I think about is consumer-1 get data from a topic-1 process it and send result to topic-2 for consumer-2 to consume. Is there any be... |
I asked this question already at stackoverflow together with a serialization related part and at codereview for the design part only. Since the design related part receives no answers or comments on stack exchange and was off-topic on codereview I'd like to ask about it here.
The problem: I have a complicated class hie... |
Suppose I have a loop (in Python syntax):
xml = "<x>...</x>"
for i in arr:
j = f(x) # some complex computation
obj = Class(i, j)
xml = obj.run(xml)
Does it make sense to use dependency injection for Class in this situation? If yes, what is the proper way to use DI in this context? Please provide an exampl... |
We have a hierarchical database at our institution that has exposed a SOAP endpoint as the only way to make CRUD operations against it. We are primarily a .NET Core shop. I'm trying to conceptualize how the architecture of an app that uses the WDSLs would look. The main use case is to display account info in a pleas... |
This is only an extract from a very long text, the one I'm not sure about. It's about a photo booth (an automata that makes a picture of you if you insert coin).
The automata has a camera that is recording once a coin is inserted. The customer has 2 minutes to freeze the video right after the coin was inserted, such th... |
I have made a small library/application that I intend to distribute. However I want to find out what versions of python can handle my script ? Given that there are many minor and micro versions and two major versions too, how do I go about doing this?
I thought about using docker to do this, but I am not sure if tha... |
Our team is attempting to "modernize" an old ASP.NET Web Forms application. One aspect we want to improve is its visual style as it looks very dated by today's standards. Additionally, its existing CSS stylesheet is an abomination and it would be easier to throw it out and start from scratch. Sadly, none of us are C... |
Assume we have a large enterprise-level application without any unit/functional tests. There was no test-driven development process during the development due to very tight deadlines (I know we should never promise any tight deadlines when we are not sure, but what's done is done!)
Now that all deadlines passed and thi... |
When using a call-back to show progress on a multi-phase task, I don't know how to calculate the progress per phase well. One of the phases is collecting data, which differs in size from run to run.
Putting global percentages into the calls all over the code needs changes as soon as a phase is added/removed, and it d... |
I need to build a REST/HTTP API that has user accounts that other sites can use.
It is my understanding that it is incorrect for the other sites(that use our API) to use a password field to allow users to log into our service. And this is mainly because the other site could log the user's password. So instead you have ... |
How exactly should gitlab-ci behave to version my project ?
A simple git flow on gitlab could be:
commit on master -> build, test and deploy to staging
tag on master -> build, test and deploy to production
But how do you deal with version ?
1- should the deploy version be based on the tag ? if yes do you update the p... |
I'm currently analyzing a problem in a old "distributed" system, that only occurs sporadically - as the system does not support other means of debugging help I have to rely on the logs (I did not design or develop that system).
Currently I do only the steps to trigger that error (of cause only sometimes, without any ob... |
We are developing some Python applications (mostly CLI) for use only internally in the company. Hundreds of machines on which the applications may run. Instead of installing the apps on each machine, we would like to use a shared network filesystems that they can all access as the deployment target. Some packages need ... |
Situation:
In our system there are a lot of certificates. Some of them are used to secure HTTPS endpoints. Many more of them are used as a means of authenticating our system to an external system (we integrate with over a dozen of other systems). Some others yet are used to authenticate external systems to our system.
... |
I really don't understand the SRP applied to a "real" project (really not so real but can help me to know your approach)
I find very difficult to divide and assign responsibility to my classes.
So I posted an example in pseudo code, and I hope someone can enlighten me.
I have a simple Windows form,
INPUT : an excel fi... |
For reasons, my search endpoint returns a maximum of 50 results.
I'm struggling with how best to tell the caller that their results were limited to 50.
The best I've come up with is returning some additional fields:
{
results: [
...
],
resultsTruncated: true,
resultsReturned: 50,
totalMatchi... |
Is it enough for methods to be distinguished just by argument name (not type) or is it better to name it more explicitly?
For example T Find<T>(int id) vs T FindById<T>(int id).
Is there any good reason to name it more explicitly (i.e. adding ById) vs keeping just argument name?
One reason I can think of is when signat... |
In C program I'm doing below stuff
int x = 4;
Let us assume integer has 2 bytes in this case.
So my question here is
the variable x will hold two bytes that mean 16 bits. So here how the value 4 will be stored in 16 bits ?
Till now my understanding is the value 4 will be converted to Hex so it results [0x0004] and th... |
I have this IdentityServer which handles authentication and authorization. It saves users, roles, claims, etc in its own database.
Then, I have a web app that needs to protect some resources to specific roles. This is, of course, handled by the IdentityServer.
Now, the question is, I need to associate some entities in ... |
I am creating server/client application. The server and client parts should be written in C language. However, for user interface I would like to use javafx. So, the question is it possible to combine javafx with C? If it is, then how do i do this in a proper way?
|
Is the Default Constructor of Super or Parent class Can be Inherited into Child class ?
|
What are your thoughts on mediator pattern being used from a client and across a web api?, this means:
Command definitions are shared between the client and api.
Web api exposes only one ExecuteCommand REST method, wich is wired up using mediator pattern to the command handlers.
Client app uses mediator pattern too, t... |
Suppose I am developing a RSS system (following DDD practises). Users have accounts. Accounts have feeds. Feeds have articles. Account, Feed and Article are my aggregate roots as well as ArticleAccountMeta (an aggregate that contains information whether an account has already read an article).
I decided to go without s... |
I want a class A, and I want the relation that A can have zero or one X.
So I wrote this class:
public class A {
private X x = null;
public A() {}
public A(X x) { this.x = x; }
public boolean hasX() {
if(x==null)
return false;
return true;
}
public void setX(X x) { ... |
Let's say we have function A and function B which perform consecutive operations on some data, with B never receiving the data before A processes it.
Function A makes exhaustive checks on potential errors on the input data. For A, it's a no-brainer to write proper unit tests. Should there also be tests written for B? ... |
I am having trouble with a coding question that I found practicing for a interview:
A scatter graph of points on a page, draw two horizontal lines (these lines are parallel) across the page such that the perpendicular y distance to a line from all points is minimized. Count the total distance from each point to the lin... |
I am minding my own business at home and my wife comes to me and says
Honey.. Can you print all the Day Light Savings around the world for 2018 in the console? I need to check something.
And I am super happy because that was what I had been waiting for my whole life with my Java experience and come up with:
import j... |
The question: Is it considered better practice to use derived types/subtypes or to use conditions and exception-handling to restrict the acceptable inputs for a subprogram in Ada? I understand that in Ada2012 you can use contracts, but what about for previous versions like Ada95?
The context: I want to make a series of... |
I was revisiting my question How can I prevent header hell?, when I noticed a comment which said
A good technique for ensuring a header is independent is having a rule that the source file always includes its own header first. This will catch cases where you need to move dependency includes out of the implementation f... |
I was wondering what would be the best approach to allocate/deallocate multiple one-dimensional, dynamic arrays in C. This seems easy at first, however, for me it turned out to be problematic. Consider the following example program, which illustrates my problem:
#include <stdio.h>
#include <stdlib.h>
#define N 10
int... |
Basically, I am asking, whether my code should say
#include “../libs/src/my_lib.h”
or
#include “my_lib.h”
with a complier option of
-I ../libs/src/
I feel (reasonably strongly) that the former is preferable, because:
it is independent of build system
it specifies exactly which “my_lib” is meant, in case ... |
As I understand, the point of unit tests is to test units of code in isolation. This means, that:
They should not break by any unrelated code change elsewhere in the codebase.
Only one unit test should break by a bug in the tested unit, as opposed to integration tests (which may break in heaps).
All of this implies, ... |
I am used to treating the issue tracker as a source of truth and an organisational memory. I use it to record what the issue is and what has been done towards resolving it.
I consider this to be essential and basic to good software engineering (including agile development).
I am willing to consider the possibility that... |
We have about 10 applications in one Monolith that need to be refactored into Microservices.
Following an Agile approach, we would like to split work into vertical slices where each slice would be useful to the User. Each slice would include a persistence layer, a service, and a user interface. However, we are not sure... |
The problem I am trying to solve today is DDoS. I am working on a game project which is hosted on a TCP port (7777). The game is known to have a community full of idiots (pardon the language) that do not like competition among communities, so they just like to DDoS servers to... kill the competition instead. Depending ... |
I am trying to write a spellchecker, I have a huge wordlist (at least 500K, because of the nature of the language). The performance would suffer a lot if I got the lavenshtein distance of all of the words in the wordlist to the current word.
So I am trying to distribute the wordlist into buckets based on the characters... |
I would say no, because a MATLAB licence is required to run the software, but this point isn't completely clear to me.
EDIT: This was a terminology question, not a request for legal advice.
|
I have an app that already locally archives user created objects and has for several years. Each archived object can have several nested objects or arrays of objects in it--all of which conform to NSCoding and are archived with NSKeyedArchiver.
Would it be wise to use the NSData objects I already have from local archiv... |
Where do you draw the line for how much logic can go in your read models? For example, we have 2 BCs: Inventory and Sales. We need to generate reports regarding inventory levels on specific dates: perfect for a Read Model.
Simple SELECT from InventoryItem and OrderLine tables based on the ProductSKU. I can then use the... |
Say I have a TypeScript class:
export class TypeCreator {
entities: Set<Whatever>
registerEntities(e: Set<Whatever>): Set<Whatever>{
return this.entities = e;
}
}
if registerEntities() should only be called once, should I throw an error if they call it twice, or just overwrite the value, or is this a code ... |
I'm relatively new to programming and have never written tests. I want to write unit tests for a group project (Angular web app with node background environment written in typescript), which you can find here. I picked out an examples which I want to test and I hope with your answers I can transfer what I learn to othe... |
I have relatively simple controller logic with ugly parts of object creation. Some of the objects are really huge and even though all the controller does is to return the object, it looks messy and hard to read. So I would like to ask how can I make such cases cleaner. Let me show you a few examples:
For instance, pay ... |
Many place that i have read about static method they said please shouldn't use static method for access to database and should use dependency injection for inject other service and use that service to write other logic.But problem it
happen when i inject AService in BService and inject AService in CService many month... |
I'm working on implementing my first clean architecture and CQRS application, I've stumbled across a bit of logic that's leaving me a bit stumped. I'm working on integrating authorization and authentication into my application, but I'm having some trouble trying to figure out how to architect a portion of my applicatio... |
In the C++, there are 6 bitwise operators:
Symbol Operator
& bitwise AND
| bitwise inclusive OR
^ bitwise XOR (eXclusive OR)
<< left shift
>> right shift
~ bitwise NOT (one's complement) (unary)
In Qt, I have seen |, ~, and & used fairly often in functions:
file->open(QIODevice::Wri... |
So say I have a controller Method
// GET: TimeEntries
[HttpGet("[action]")]
public IEnumerable<TimeEntryDTO> GetLast(int value)
{
return dal.GetLast(value);
}
And a data access layer method of (using AutoMapper to convert TimeEntry to TimeEntryDTO)
public IEnumerable<TimeEntryDTO> GetLa... |
I'm doing this in python, in case that changes anything.
I'm trying to make a lamp/bit go 1-0-1-0 until the user says "okay"
the "okay" should indicate that the user has found the lamp/Bit IRL.
Now i'm struggling to find a way to ask the user a question, (because it stops the program cycle), when I also want the lamp b... |
I am new to C# and have a difficulty with the code structure. My application has:
GUI with button Show my Ethernet IP. When user clicks this button PC's IP address is displayed.
Class ModbusTCPSlaveMachine. Within this class I create TCPListenter and supply it with PC's Ethernet IP address.
In both cases I get local ... |
I was following a tutorial on the normal forms of SQL databases, and I got confused landing on this example : https://www.tutorialspoint.com/sql/third-normal-form.htm.
From
CREATE TABLE CUSTOMERS(
CUST_ID INT NOT NULL,
CUST_NAME VARCHAR (20) NOT NULL,
DOB DATE,
STREET ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.