instruction
stringlengths
34
36.1k
I need to reduce the cyclomatic complexity of my input tests. I have no control over the inputs, so I have to go through all of these checks. if(y1 < 2000 || y2 < 2000 || !(m1 >= 1 && m1 <= 12) || !(m2 >= 1 && m2 <= 12) || !(d1 >= 1 && d1 <= DaysInMonth(m1)) || !(d2 >= 1 && d2 <= DaysInMonth(m2)) || ...
This seems to be a recurring requirement for me, so I'd like to get some feedback on how to implement it and what sort of test code makes sense. I need to retrieve batches of data and stitch it together for further business use. I need to select all the As from 1 datasource and match them with any Bs from a second data...
I have php application like airbnb. I want to store search values each time user search for listings. my number 1 solution would be storing it in mysql table, but I'm not sure its wise to do, if site has lots of searchs wouldn't it will slow things down. should I use mysql or something else?
I currently have a 15 year old legacy monolithic webapp with close to 1 million users, using a home-grown authorization & authentication system: JAAS, user names & pwds store in a DB with basic password hashing, some 2FA personal verification questions (with different hashing algorithms, etc). I will be overhauling the...
I'm reading the book Clean Code by Uncle Bob. I'm also enrolled in a data structures & performance course and reading several algorithms and data structures books. One immediately apparent difference is that in Clean Code, Uncle Bob criticizes non-semantic variable names such as "k", "x", "j", etc for general use in a ...
I'm trying to make a simple blog from scratch, but it occurs to me that I probably shouldn't have a bunch of static html pages that I link to, especially since I want the home page to be a cascade of previews of each post. So I was thinking I would store the posts in a database, and I would just retrieve parts for the ...
We are basically in process of moving from monolith system to microservices and we avoided migrating monolith system all at once, or as they call it a "big bang" https://www.nginx.com/blog/refactoring-a-monolith-into-microservices/ Since our microservices are built using DDD, where domain is persistence ignorant, we a...
Imagine I am working on a C compiler. I have made some changes to the compiler's code, and am interested to know what effect these changes have on the performance of generated binaries. I have a benchmark program, written in C, which runs for a minute or so and outputs a megaFLOPS value. I can compile this benchmark us...
Currently we don't do much testing at our company, except some manual checking. We occasionally create some unit tests, integration tests and ui tests, but not on a regular basis. Since a new project is coming up I want to take the opportunity to implement a better way of testing. Question Since most of our web applic...
I'm new to object oriented programming and I don't understand what's the purpose of the main. Yes, I read that it's the "entry point" of the program but what I don't understand is what should be in the main? And what are its responsibilities? It may happen that something written in the main could be encapsulated in ano...
Consider a Selenium test that does some steps on the UI (e.g. fill a field and then click a save button), and afterwards checks with a DB query if the data entered in the new field was really saved into the DB. Is this good or bad practice? What are the advantages and disadvantages of such an approach? (Let's suppose t...
In programming, what are the benefits of referential transparency? RT makes one of the major differences between functional and imperative paradigms, and is often used by advocates of the functional paradigm as a clear advantage over the imperative one; but in all of their efforts, these advocates never explain why it...
The following is a quote from Microsoft's framework design guidelines: Collection Properties and Return Values X DO NOT provide settable collection properties. Users can replace the contents of the collection by clearing the collection first and then adding the new contents. If replacing the whole collection is a comm...
I have two kinds of data streams that both implement the same interface: public interface DataReceiver { public Data getData(); } public class DeviceDataReceiver implements DataReceiver { // Receives data from an external device public Data getData(); } public class PlaybackDataReceiver implements DataRec...
I need to model a very simple mobile object (Robot) on a rectangular grid. Its state is described by position (basically a pair of integers) and direction (e.g., N, E, S, W). It only has two methods (apart from constructor): it can move one step in its direction, or rotate by 90, 180 or 270 degrees. Apart from the obvi...
Singleton pattern saying "there should be no more than one instance of same class", is this something one should stick to when designing PHP OOP applications? What are advantages / disadvantages? class myDOMDocument { private $DOMDocument = new DOMDocument(); private $HTML; public function __construct($html...
I'm using MVC 5 Core on my Web API and I wanted to know what is the most optimal way of storing an Array into a database? Should I store Arrays, does it matter, or should I parse the array and input them individually into their own separate rows? By optimally, I mean being able to have more control over the data and cu...
I'm just wondering—Are the programming language features unit tested? Basic features, i.e. built-in types, operators, arrays, generics, etc. The question applies to unit testing for runtime behaviour, not a compile-time, and not for a syntax validity. The question doesn't apply to helping libraries (classes for string...
I'm wondering how costly C# introspection really is in terms of class type inspection. Let's say I have a problem, where in a method of D I have to decide to take an action depending on the type of different objects B:A and C:A. Now I could do this with introspection: public class B: A {} public class C: A {} public ...
Having a service that eg. downloads data, whos responsability is ProgressReporter? Should it be caller responsability to pass a valid one, as in CodeSample1, or it would be better if it's object's creator responsability like in CodeSample2? First option gives more flexibility regarding possible reuse of this function ...
We have a system with about 250 tables. The first-time-setup include running about 50 queries (known also as seeds). We're trying out strategies to automatize our acceptance tests, and our first choice was to clean and rebuild the database on every scenario (aka: every test), so that we could keep them isolated from th...
I'm trying to reference a member of an object of type 'ExternalSourceProvider' that's been instantiated through reflection like this: Type type = GetProviderType(vendor); ConstructorInfo constructorInfo = type.GetConstructor(new Type[] { typeof(NameValueCollection) }); ExternalSourceProvider ven...
I'm using reflection as a way of implementing a factory pattern: Type type = GetProviderType(vendor); ConstructorInfo constructorInfo = type.GetConstructor(new Type[] { typeof(NameValueCollection) }); ExternalSourceProvider vendorSourceProvider = (ExternalSourceProvider)constructorInfo.Invoke(ne...
I just wrote this code that uses a goto statement. if (PyMethod_Check(attrib_value)) { PyObject *im_self = PyObject_GetAttrString(attrib_value, "im_self"); if (im_self == Py_None) { js_value = FunctionTemplate::New(isolate, py_class_method_callback, js_name, signature); } else { goto method_...
We have recently begun to split our monolithic web app up into microservices, slowly slicing functionality off and rewriting into individual microservices. All is going well except we are unsure of the best way to organise the frontend work. We have split up into product teams with each managing the code for a small nu...
I'm in the process of designing an application structure and am currently thinking how to structure my asp.net MVC5 front-end. My application is wizard-like with tabs for each step. It's not a strict wizard as in you need to finish previous step to get to the next one but it's close. There will be 12 tabs/steps and eac...
I'm developing a simple noughts & crosses game where the player plays against the computer. Obviously, I use the Randomize function of the language, however, the final stage of refinement is to try to get the computer to block my winning move (as you normally would in a real game). This, of course, requires more intell...
My boss had an idea of simplifying tests to English like statements so that non programmers could write tests as well. We chose Lisp as the syntax in which the tests would be written. This testing framework is built for web applications and uses Selenium. By English like syntax I mean we've abstracted away most of the ...
I've been tasked to create an NPM package that our Frontend teams can make use of that has styling for the companys UI elements: Layout Grid unit proportions, gutters and spacing. Typography Headings, body text, links, lists, inset text, hidden text. Colour Colour contrast, Sass variables, colour palettes. Icons and i...
Is it good style to use additional, technically superfluous, local variables to describe what's happening? For example: bool easyUnderstandableIsTrue = (/* rather cryptic boolean expessions */); if(easyUnderstandableIsTrue) { // ... } When it comes to technical overhead I expect the compiler to optimize this addi...
If I understand correctly, every RIGHT JOIN: SELECT Persons.*, Orders.* FROM Orders RIGHT JOIN Persons ON Orders.PersonID = Persons.ID can be expressed as a LEFT JOIN: SELECT Persons.*, Orders.* FROM Persons LEFT JOIN Orders ON Persons.ID = Orders.PersonID My personal opinion is that the statement's intent: First ge...
I am in the process of developing a website for a driving school that will also act as a management app. One requisite is that at some point the student can choose a day for the driving lesson to take place out of a list of possible schedules. Since there are many users that could be watching the same schedule I want t...
We are running jobs whose parameters come from a web page and are executed on large files on a spark cluster. After processing, we want to display the data back, written to text files using rdd.saveAsTextFile(path) We have a session id that is a common root for the output folders. Meaning it is a random folder but ...
Many articles in Internet say that singleton is an anti-pattern, because it makes debugging more difficult. However I don't understand why debugging a program with a singleton object is difficult. Please explain. I think that singletons are inevitable, when we need (usually for performance reasons) lazy initialization ...
In The Art of Unix Programming, Eric Raymond tells that the data-driven style is about creating small interpreters for "mini-languages" to allow controling the control-flow of the program at runtime. How is that related to displaying data ? I could not find anything that was about creating DSLs in D3.js
We have acceptance tests for our REST endpoints using rest-assured. The tests currently have they're own fluent JSON builders. They help us remove noice from our tests. For example. .body(someUser().withEmail('joe@games.com').toJson()).post(... We could even improve that design more by creating fluent beans with Jackso...
I'm writing an API that will interface with an SPA front-end. For simplicity I currently have the API at api.example.com, and the SPA itself is at example.com. I have CORS set up and everything is working correctly. In my ignorance, however, I was unaware that a preflight request is sent for quite a few method calls. I...
On your favorite terminal, the special ANSI character for red text is ^[[31m. The special ANSI character for a blue background is ^[[44m. So, to have red text on a blue background would be ^[[31m^[[44mHello World!. However, the library ncurses does things differently. Instead of having an individual red foreground char...
I'm trying to understand RESTful communication, but I still have a few doubts. I have a main web application (on the right side of the Architecture) made in AngularJS, which shows data coming from multiple web servers containing other applications or databases (on the left side). Some of these applications don't have...
I am developing a Web API, with an n-tier approach, using Entity Framework and using code first approach. My questions is does my DAL, and Business Logic layer are following DI/UoW/DDD pattern if not where should I change my code to make it more standard. What should my service layer look like to bridge between the we...
I'm trying to decide whether to change IDEs as I've read promising things about both NetBeans and IntelliJ, but I have two interrelated (perhaps dumb) questions: Is there any difference in the final application produced by all 3 IDE's, assuming that all 3 use identical code (Java)? In other words, do IDE's package the...
The C Programming Language says that I/O is not built into C and is instead accessed through stdio.h. But if stdio.h is written in C, how does stdio.h implement I/O? I've looked at the source code and I don't understand it.
I am curious whether there are metrics on whether code coverage actually improves code quality? Any research studies? If so, at what percent does it become a case of diminishing returns? If not, why do so many people treat it as a religious doctrine? My skepticism is anecdotal and is brought on by 2 projects I was inv...
We have a product that we currently use TFS as the source control for. TFS's branching/merging capabilities seem incredibly lacking and we are migrating the project to git, and I want to take this as an opportunity to clean up our source control practices as best as possible. Currently we have a single repository in TF...
Let's say we have a legacy database. We find out the Orders and OrderLines tables contain each 100 columns. Some of them cannot be null, they are not and will not be part of our business logic but they need to be initialized. Also there will be another set of columns we will not use either. Now we want to start buildin...
Assume I have a sort of Observer-Pattern, where message objects are sent to observers. So I have say class Message as the top of a hierarchy and observers working on them. Concrete messages are derived from that and identified by an ID, by which it is possible to cast the message to its concrete subtype and work with i...
My employer uses TFS VCS as more of a shared storage location for source code rather than source control with clear policies and branch owners to help organize things. I've been given a mandate to clean things up, so I am looking for strategies on how to reorganize an existing repository without losing history, creatin...
There are many claims about existence of clusters of bugs or defects. A simple search reveals multiple results, for example: 1, 2, 3, 4, 5. However, all the evidence cited is anecdotal and I could not find any concrete data to back this up. While my own experience does not contradict these claims, people love to see pa...
The JWT specification describes only the payload and how it is sent, but leaves authentication protocol open, which allows the flexibility, but quite unfortunately, flexibility can lead to antipatterns and misdesign. I'm looking for some well thought and tested enterprise patter for JWT authentication, which I could u...
Our customer (a bank) needs to publish a web-service API for use by 3rd party applications. The security is going to involve OAuth2 and JWT (JSON Web Token). The problem is that the customer is afraid of misuse of the published APIs by the 3rd parties to whom they don't trust completely (please, don't comment on this)....
There is an object which is very complicated to build and many algorithms needed to figure out how it should be created (for your curiosity it is an object that represents and draws the beaming of notes in music notation). The object has a rats nest of internal logic which I want to, at least partially, externalize in ...
I would like to enrich some streaming data, with one service per enrichment, possibly each service written in a different language and managed/deployed separately. Each service would consume some Kafka topic, enrich the message, and publish it in some Kafka topic. In the end, I would have a topic of fully enriched mess...
I've been programming for a few years, and have become very familiar with C# and JavaScript over time. I have some larger C# and JavaScript projects that I have no trouble navigating around. I recently started a PHP & AngularJS project for work with no prior experience with PHP. The flow of the PHP side of things is be...
I am implementing a certain algorithm that works like this: Create a closed contour (list) of elements in a matrix, where closed means that the last element is adjacent (by row, column) to the first. Weight (multiply) each of the elements addressed by the contour by a scalar associated with the element's position in t...
I really like to make tools prior to starting some assignment, so for the C programming assignments I have prepared dynamic array library. We are restrained to only using C99 standard. Note that all programming I'm describing below is, as per question title, done for education purposes. This is not production code but ...
What are the Benefits of running a UniKernel. Isn't it more work to coordinate multiple UniKernels spinning up and down versus the traditional application? What pieces of Software will be rewritten using a UniKernel, where does it make sense?
In my code, I'm using repository pattern. For example, I got deal repository. I just curious how you decide the name of the function when the function itself doing so many things. I think when the function name too long it can decrease code readability. Is this considered bad because of function name too long in terms ...
A recent question mentioned the term canonical schema in a context of microservices architecture. After reading the Wikipedia article, as well as one of the answers to the question, I still don't understand what canonical schema is about. I get that it's a way to decouple the microservices by doing some magic with the ...
I am currently coding a productive study app. In my app, the user can input a list of productive, non-productive and necessary tasks which he will be doing throughout a period of time. The user is able to click which task he is going to work on and the app will track the time he has spent on that specific task. At the ...
I've been reading a lot about different servlets/application servers like Tomcat, WildFly, Jetty and GlassFish. However, I don't understand if they're only used for testing server-side code during development, or can you also use them for deploying the final production code to end users (commercially)? My understanding...
Let's consider the following objects : Article which can be of different types Equipment which point to an Article, some fields on equipment are only used for some types. I want to add constraint to the Equipment, this constraint depend on the type or Article. I have three choices : Use triggers so I can query the...
I have a big challenge to solve where I have some ideas but I don't know what would be the best solution. Basically I have to develop an application where I have to develop a back-end(web service) and Multiples front-end. The core for all the applications is going to be the same, same requests and functionality. What ...
For the example's sake let's say there is a given file math.js. Think of it as a module containing many reusable functions. The content of file is: export function area(shape) { normalize(shape) ... // real stuff here } function normalize(shape) { ... // real stuff here } export function circumference(shape...
The scenario: Our customer creates physical devices used in infrastructure across the globe Their new devices have IoT capabilities and can communicate their status and other sensor data to the cloud We are building a web portal that displays information about these devices This web portal provides access to customers...
My team and I are trying to follow semantic versioning 2.0.0 to keep tabs on our library versions. We primarily use C# for our development and are currently in a situation where we are going to add a property to one of our interfaces. We are a little unsure how this influences the rest of our applications that use this...
So I will be creating a feature to a php application that does the following: Create a session that expires after 30 minutes. After 30 minutes, if there is no user activity in the application (including typing to a textbox, moving a mouse throughout the page), the session will be destroyed and the system will redirect...
My domain consists of lots of simple immutable classes like this: public class Person { public string FullName { get; } public string NameAtBirth { get; } public string TaxId { get; } public PhoneNumber PhoneNumber { get; } public Address Address { get; } public Person( string fullName,...
An interesting design choice/discussion has cropped up in code review, and I would like to understand more about proposed solutions. The original review includes re-factoring of a messy piece of code which I cannot share, but I think focussing on the problems with the original code is skewing opinions about what a good...
During its evolution C# gradually gets more and more features which belong to functional paradigm. Subjectively these features allow (at least me) to be more productive, fluent and write maintainable and readable code (well.. I thins so). But I'm curious whether some rigorous proofs (not just testimonials) exist that ...
For example, web application monitoring services like New Relic RUM or Bucky use JavaScript to collect data on a user's session and eventually send that data back to an endpoint. For New Relic, the data is sent to an endpoint like "http://bam.nr-data.net" with a great deal of parameters. With Bucky a similar payload is...
We have an application that consists binary files (containing a mix of text and numeric information) and programs written in various languages that create, modify and read these binary files. Because the text fields are stored in a binary file, an individual text field is stored in a binary file as a fixed number of by...
I'm trying to get my head around the big picture when producing a new website using ASP.NET Core. I want users to my website to be able to register and log in with social media such as Facebook and Google. Once registered when they make requests to my WebAPI for resources I need to know which user is logged in so that ...
I am developing restful services using resteasy for an application. This application has UI which will consume these rest services. Now I am having a case where I have to do a server push to UI(Client). Across browsing over internet I see Websockets, atmosphere2.0, etc.., however I am wondering how I can capture all t...
I have Microsoft Azure Cloud Application built with App Service. It is supposed to be always "up" for its consumers. When we need to do upgrade and we still need to keep the older one active for sometime till its consumers need (max 1 month). Any other consumer will always use the latest version of the application whil...
Let's say I have two classes Base and Derived : Base. Derived shall be able to use a DerivedComponent : BaseComponent, just like all other derivates of Base use their own derivate specific component. All these BaseComponent components, like DerivedComponent, have some common functionality accessible in Base. Since I do...
I've designed a single-instance database for a multi-tenant application which uses composite-keys to enforce tenant-segregation at the database-layer (thus preventing incorrect 3rd-degree relations). So the schema looks like this: TABLE Tenants ( TenantId int NOT NULL IDENTITY(1,1) Name nvarchar(1...
I've noticed alot of hatred about OpenSSL because of it's lack of documentation. And all advice and guide about the library must be passed around our people in song and story. I always doubt myself, because how could hundreds of people put so much time into this wonderful work of engineering if they don't even write do...
I have an idea of making application in php that will not have any public files other than index.php i.e. different pages of project load as parameters sent to index.php Also if someone wants to book mark page its okay because i can probably use .htaccess to send arguments to index.php based on what page requested. Do...
Suppose I have the following interface used for publishing messages onto a message queue: interface IMessageProducer { void Publish<TMessage>(TMessage message); } Normally, an implementer of this interface will attempt to publish a message onto the message queue immediately. However, I've found that sometimes I ne...
I have two components, both are a parser/builder pair. So component A can parse A and build A, component B can parse B and build B. A and B both contain different entities, which are extracted by the parsers. Example, BParser works the same: $AParserResult = AParser::parse(A); dump( $AParserResult->getEntityZ(), ...
Just reading through the AWS CLI docs, and I've noticed that all JSON output is indented (i.e. "pretty" formatted)... Doesn't this add a disproportionate amount of bloat to the responses? If so, why would they choose to keep "pretty" formatting? Is there a way to disable this?
We are using some sort of microservices approach in our app (although it is not really consequently adhered to). When a service is down or throwing an exception, the approach is to put it into a queue (ActiveMQ), and retry when the service is up again. Is this a "standard" solution? Or should it be avoided for some rea...
I'm designing API for a python library that accepts asynchronous input and produces the asynchronous output: various signals come in, and various signals are generated in response (there's no one-to-one relationship between input and output signals). The input could come from a network socket/file/interactive (terminal...
In OpenGL you have to bind an object to the context to be used in subsequent calls, instead of just using it as an argument in those calls. For example, in OpenGL you write this glGenBuffers( 1, &vbo ); glBindBuffer( GL_ARRAY_BUFFER, vbo ); glBufferData( GL_ARRAY_BUFFER, verts.size(), verts.data(), GL_STATIC_DRAW ); I...
I have a dilemma. Let's say I have an AST that describes some grammar, for instance. I can write a function to stringify this AST back into human-readable BNF form or generate a parser from it. I can and want to generate both from given ast. I can do it either by defining two corresponding functions, ast => string and ...
I am thinking about adopting something like the GitFlow branching strategy. Instead of using a permanent develop branch, I would like to create a release branch for each sprint (from master) at the beginning of each sprint. Feature branches would be merged into the release branch. Our CI process (TeamCity) would be con...
We are discussing in team regarding best practices. For eg. there are three tables Users Groups Teams A user will create a request to join a Team or Group or to follow a Private User. A request actions will be: Create Approve Reject Cancel This process will be almost same for all kind of requests. The question is: ...
It's confusing because type declaration and usage both use the <T> syntax. I think there are only 2 places where you can declare new generic types in Java: 1. In the definition of a class or interface class MyClass<T> ... // ^^^- Type declaration interface MyInterface<T,U> ... // ^^^^^- De...
I've published a small FOSS library (link below, but what it does is not very material to this question), on GitHub. It doesn't have releases yet, but it's quite usable and (sort of) tested. Now, I have a beefy front-page document for the repository - describing design principles, giving some example mini-snippets of c...
Using JS as an example here, if I am creating a library/plugin, and intend to make it available to others, should I keep it in Javascript? Or would jQuery be an acceptable dependency? At what point does the ease and added control of coding in jQuery outweigh the potential inconvenience of someone else having to include...
I have a couple of Philip Hue lights in the hallway. These show the build status on their lights with a small Node.JS application. Its working like a charm. Currently I am in the process of testing and refactoring this application, but in my app.js I have some lines of code where I am having a hard time to figure out h...
I recently reviewed some C++ code written by a fellow student, and he did something I wouldn't think is necessary. In main(), he creates a class object on the heap with the new operator. Then he calls a method of the object, which itself calls the new operator to create a large vector. My gut tells me this is unneces...
I'm building a C# library and have some dependencies through NuGet packages. I'm trying to minimise entry barrier and using the very early versions of dependency packages. For example I use Newtonsoft.Json of v6.0.1, but current version is v9x. This is for cases when people install my package, but don't have the lates...
I'm working on an update of an existing medical software and I defined user stories together with some end users. If you're not familiar with medical environments: A doctor usually has multiple patients. Each patient has multiple cases (broken leg, skin disease, etc). In medical terms, a case will be closed once the pa...
Here are the main classes I can think off the top of my head. All business objects will follow the abstraction (implement interfaces). I have not mentioned interface names to avoid verbosity. I have mainly focused on high level scheduling algo and high level classes without going into too much details Principles I mai...
I am currently studying some basics on git Version Control System on tortoiseGit for my project management so far i know that Git keeps track of the history of changes, and allows you to easily go back to an earlier version if necessary. However when it comes to binary vs text files I am unsure which files are more use...
I'm just starting to explore SOLID and I'm unsure if reading from files and writing to files are the same responsibility. The target is the same file type; I want to read and write .pdf's in my application. The application is in Python if that makes any difference.
We are a small-ish firm with multiple teams who manage their own git repositories. This is a web platform and each team's artifacts are deployed at the end of the day for nightly tests. We are trying to formalise the process around versioning and packaging. Every team has a master branch where they do day-to-day devel...
In a web application, we create an email provider, which in turn creates an SMTP client: my question is whether we should create an SMTP client per request or create only one client and have it service all requests? Which is the best way to use an SMTP client? We are only sending (not receiving) email.
I have a feature I'm building that aggregates data across about a dozen or so tables. This data is aggregated from a heavily joined query. This page then has a lot of filtering, sorting, counting, and display options that need to work on top of this aggregated data set. There is one "global" condition/filter on the pag...