instruction
stringlengths
34
36.1k
Let's say I have a MediaPlayer class which has play() and stop() methods. What is the best strategy to use when implementing the stop method in case when the play method has not been called before. I see two options: throw an exception because the player is not in appropriate state, or silently ignore calls to the stop...
I'm having a bit of hard time finding a solution to the following problem. I need to find tuples of (a-c, 0-2) such that if I make a choice with one letter and a key I can't select it again. Example: input: {'a': [0, 1], 'b': [1, 2], 'c': [0, 1]} output: [(a, 0), (b, 2), (c, 1)] Example valid choices which lead to inco...
I've recently poured a couple of hours into JavaScript because I wanted to benefit from the massive userbase. Doing that I have noticed a pattern that most people attribute to dynamic languages. You get things working really quickly, but once your code reaches a certain size you waste much time with type, spelling and ...
A colleague of mine came up with an idea that I found interesting. Wouldn't it be beneficial to write tests during code review, by the person doing the review assuming that we don't do TDD? For this question assume that this is a purely academic project so there is no life at stake. Moreover the team is 4 people. Ever...
I was reading some code here and saw that an enum is used to store names of html tags. Why do we ever need to do this? What benefit do I get using this strategy? I know that how useful enums are in compiled or statically typed languages but when I see enums in dynamically typed languages I get curious, like the example...
Background I have a project that depends on the usage of a certain type of hardware device, while it doesn't really matter who makes that hardware device as long as it does what I need it to do. With that being said, even two devices that are supposed to do the same thing will have differences when they are not made by...
Sometimes, we need to stuff an integer ID into a string, for example when generating HTML form <select> items. Calling int.ToString() can result in digits outside the range [0-9] in certain cultures. For that reason, you need to specify the invariant culture in culture-spanning apps (e.g. int.ToString(CultureInfo.Invar...
I'm trying to tackle the While Language problem on HackerRank using Scala. I've been given a set of grammar rules and have to implement the actual interpreter underlying it. I've decided to approach this by building a lexer and parser in two separate stages. My lexer works perfectly: it correctly tags tokens and wraps ...
I am writing a rather large class where the user can specify at runtime whether she wants to use algorithm A or B of an third party library e. Basically there is only one function call different in choosing A or B, but this function is called in many different places in the code. I would like to omit having to write ...
I'm doing a object Garbage class using c++: #include "Object.h" class ObjectGarbage { public: ObjectGarbage(); ~ObjectGarbage(); void Call_All_Objects() { //(some for loops) {Garbage[..][..][i].Main(); } } void GetObject(Object *obj) { //Data type get (...
I'm working on an API and I always seem to run into this thought debate. When designing the code structure that interacts with the database (repositories, data providers ect..) how do I structure the repositories based on hierarchical relations? For example I have an app with Items and those items have images. Do I ma...
I need to write a part of the program which will work with a string, find in it some substrings and copy they to dictionary. Example of the string: thestring ='\ #: somethings\nchars0 "substr0"\nchars1 "substr1"\n\n\ #: something\nchars0 "substr2"\nchars1 "substr3"' so it have current substrings 'chars0' and 'chars1' ...
I am attempting to refactor a component of a large project, which currently has a lot of dependencies to global state of the project environment. The goal (for my taste) is a "SOLID" architecture, where everything can be properly tested. Sometimes the dependency may simply be a string or value: A specific directory, a ...
I support an Internal ERP system and an external Reporting/Dashboard that our customers use that both use the same database. Internal normal application users can control what customers can access through the external dashboard - this can be sites, jobs, documents etc as who can see what on which accounts/sites gets ve...
Let's say I have a basic procedural program which is well structured into decomposed functions. For example, a main() function which calls functions a and b, which in turn each call functions c and d, and e and f. In pseudo-Python, this could be written bottom-up like this: def c(): # Do stuff def d(): # Do st...
Extracting functionality into methods or functions is a must for code modularity, readability and interoperability, especially in OOP. But this means more functions calls will be made. How does splitting our code into methods or functions actually impact performance in modern* languages? *The most popular ones: C, Java...
About the subject I hesitated for a while between using singletons objects or plain static ones. After having read a lot of different opinions, I made mine: If you don't need to prevent multiple creation of an object, don't use a singleton. Therefore I used mostly static objects. Context My program is a complex sci...
I'm currently developing my own (sort of) programming language. It currently looks something like this: asdf = 2; print(asdf); And print(2); And surprisingly, it works. (Both output 2) However, the problem is I can't do this: print(sqrt(25)); I also can't do this: asdf = sqrt(25); print(asdf); My big problem is I c...
I'm building a simulator which parses some events from STDIN and "runs" them. My background is mostly functional programming these days, so it seemed natural to do something like this: data Event = Thing1 String Int | Thing2 Int | Thing3 String String Int Parse :: String -> [Event] Simulate :: [Event] -> [Result] wher...
Is it bad to pass a reference to the behavior's owner object to the behavior? For example, if I have a Duck and DuckBehavior class. DuckBehavior is a part of the Duck Class. But what if I need to get some internal information of the Duck. Can I pass a reference of Duck to the DuckBehavior class when I'm constructin...
The company I work for follows a business model where a core product exists (originally written in C, now in C++) with some default implementation but details are tailor-made for each customer (there are cca. 10-20 of them). What's the best programming approach in such a scenario? Is there a good design pattern/methodo...
Looking through this article on Rust's concurrency safety: http://blog.rust-lang.org/2015/04/10/Fearless-Concurrency.html I was wondering how many of these ideas can be achieved in C++11 (or newer). In particular can I create an owner class that transfers ownership to any method to which it may be passed? It seems tha...
When a beginner starts off reading ifstreams, his/her instinct is to read the file using a loop that usually looks like this: while (!ifstream.eof() { ... } However, when I used this code I noticed that it didn't stop until it had read the last line of the file twice. C++ programmers note that this isn't actually how ...
I have an Asp.Net MVC application where I need to create a report. This report will show some data about an entity (activities), but only activities of ONE specific type that will be inserted in the database (until now). My data model is: Activity: Int ID DateTime Date Int TypeId Activity Type: Int ID String TypeName ...
I got inspired by a similar question on the Stackoverflow.com and after reading what Martin Fowler has written (and Jez Humble, of course at http://continuousdelivery.com/), I still struggle to understand the difference, or the border line, between continuous integration and continuous delivery. Let's assume there is a...
in my project I am finding that I mix and match the following two patterns, when it comes to organizing classes in folders/namespaces: Modularized MVC Blocks module/Album/Feature/Controller/AlbumFeatureController.php module/Album/Feature/Repository/AlbumFeatureRepository.php module/Album/Feature/Form/AlbumFeatureForm.p...
I'm attempting to migrate some of my already existing pages over to bootstrap 3, and I'm wondering the best design to do this. On the non-mobile devices, I display a list of items on the left. If you click an item, it will either render a detail section or pop up a dialog. On mobile, however, I need this to slide into...
This could be a simple yes/no answer, but I invite detailed explanations. Scenario I have been asked to extend a closed source system at my job, which is not formally released under any license. I thought I'd learned once that meant all rights are reserved by default, but I can't find a source for that now, so please c...
According to oracle docs: the class name in java should be nouns, in mixed case with the first letter of each internal word capitalized. Is this just a good practice rule or a mandatory rule? (I'm a beginner so please excuse me if this is too silly)
The following scenario happened to me several times. I programmed a algorithm that solves a certain problem. It works fine and finds the correct solutions. Now, I want to have an option to tell the algorithm "write a full explanation of how you got to the solution". My goal is to be able to use the algorithm in online ...
I recently just started looking at Func in C#, and as far as I can tell, they pretty much are the same as methods, which is fair enough. However, I was wondering if there is any point in using them, because as far as I can tell they seem to just be a slightly less version of methods. Consider the following: Func<int,in...
C has family of integer types i.e {short, int, long, long long}. Any new programmer is likely to use int to represent integer variable in the application and since int type has 32 bit space with range (-2,147,483,648 to 2,147,483,647), there will be bug as soon value of the variable goes out of the range. As you can se...
Let's say I have two files I am working on - "a.txt" and "b.txt". I need to commit my change to "b.txt" but want to keep working on "a.txt" for some more time. I do a "git add b.txt". Now, before I actually commit this change, is there a way to test that the commit will not break the master branch? If I run a test loca...
Even after thorough requirements engineering we end up with users wanting to attach 'notes' to their otherwise well-structured data records, in other words: arbitrary key-value pairs. Their primary interest is to find records later based on this meta data. Example: { fixedattr1: 10, fixedattr2: 11, fixedattr3: 12...
Is O(n^2 * 2^(log n)) == O(n^2) ? Why I think that this could be the case: In big O, you only take the parts of the term that are most relevant, right? O(n^2 + 3n + 9) == O(n^2). The n^2 has a lot more influence to the result of the term than the 2^(log n)-part. http://www.wolframalpha.com/input/?i=Plot%5B%7Bn%5E2,+2%5...
I am implementing a trigger system. There are objects that take the role of observers (this is not strictly an observer pattern because the observers are inter-dependent, see my question here). They register to be triggered during certain events (by being added to the list of that event) and provide the functionality w...
The following piece of Python code uses a superclass solely as the repository of functions that one of more subclasses may draw from: class Class(object): ''' A trivial repository for functions to be inherited ''' def function(self): print self class Subclass(Class): ''' A subclass where the actio...
Though I like recursions and understand it, I fail to master it! I am stuck with a problem which I know that recursion can solve, but I do not know how. I have an array of strings like: "hundred", "fifty", "thirtythree" etc. I have 'x' number of places to arrange them but the condition is, the string following in next ...
I recently realized that I have way too many dependencies in many of my classes. Now I am trying to solve that for the most important class. I think I have an idea how but I'm not sure if it is the best idea. The most important class is a Service class. What it does is make one "thing" in the app go through different s...
What would you call a test that is similar to a unit test, except it actually modifies a file, directory, or database data? It is similar to a unit test in that it does test a single method of a single class as opposed to testing an entire feature of a program or a scenario a user would run through. It does not use moc...
Definitions used by this question: 'functional' Try is what https://github.com/lambdista/try is. Success and Failure are subclasses of Try. Exceptions aren't thrown by the called function. 'rx' Try is what https://github.com/aol/cyclops/wiki/Try-:-functional-exception-handling-for-Java-8 is. Exceptions are thrown by t...
I have a dilemma. How to do better? I have a bunch of API interfaces and their implementations which use some specific frameworks/librarys which I would not like to expose. I cannot make a decision about whether to put both API interfaces and their implementation in the same package or split them up to different packag...
In functional programming, given a function f and a function g we can define a function . (compose): let (.) f g = fun x -> g (f x) Is there a term for the function which applies arguments in the opposite order? What would be an appropriate term for the # operator in the following definition? let (#) f g = fun x -> f (...
I read a lot of questions about this concern, and some of them are Presentation VS Application layer in DDD Application layer vs domain layer? So my question is if the top layer is REST API and there is no need for any UI, is REST api considered as a presentation layer or application layer? Update Since I received som...
I've seen some people overusing default arguments and I was wondering when it is reasonable to use them. The main issue that I have is that sometimes it makes me think it using overloading when it isn't.
I just changed branch settings on my GitHub repository, so that my [next] branch requires a passing CI build through a pull request. A discussion followed with a number of team members, about failing tests. For context's sake... The repository has a [master] branch that's only PR'd into when there's a release, so [mast...
It is usually well known how to deal with model classes that have a 1:N relationship: classical examples are order->items or client->orders. Every layer of the software has its appropriate and typical solution: a sort of prepared template. Again, the same classical example: a GUI of an order where the user can enter a ...
So, I recently noticed something on some code I was writing. I could get a variable for a different class/object using dot notation to get the variable: object.someVarable or I could do it the way I was taught and use an accessor method: object.getSomeVariable() to return the variable. So, my question is: which is ...
I am using a modified Linux kernel from a NAS company for my own project. It has been more then one month since the company released a new version of their software which includes the modified kernel so far the code has not been made available. Is it allowed to delay the release of the source code or does GNU GPL v2 re...
I have a client that wants me to build a SaaS application with a multi-tenant architecture, where different clients will go in a separate schema on the same db server. I have seen this architecture before, but never really used it, so I am quite new to the concept. I am strongly against this as I think it would add a l...
Say I have my project that looks like /src/main/java/... /src/main/resources/... /src/main/webapp pom.xml And I have this stored in my version control, Git/SVN etc. My artifact has a signature like <groupId>dwj.me</groupId> <artifactId>some-project<artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packagi...
I am on a micro controller (which means I can only have static memory allocation) and I am trying to work with inheritance..... Suppose I have a abstract class Image and an abstract class Font. An instance of Font can return an Image based off of the char given in a function like so: Font* mf; Image* image = mf->GetIm...
Suppose I have a custom object, Student: public class Student{ public int _id; public String name; public int age; public float score; } And a class, Window, that is used to show information of a Student: public class Window{ public void showInfo(Student student); } It looks quite normal, but I fo...
Which programming languages support operators as first class citizens? eg: Return an operator (+, -, =, ==, etc.) from a function, or store within a variable.
Scenario: I have a situation where I need to refactor a Web service with a single API endpoint that uses complex logic to insert, update and fetch data from a database. The clients use one call, and depending on the data transfer object they send, the service is doing different things (the API was not designed by me so...
Computer vision includes: Character recognition (converting an image to text) Face recognition (detecting a face in an image) Object recognition (detecting various objects in an image) Human recognition (detecting a human shape in an image) Motion detection/object Tracking (detecting motions/movement) All of these ar...
It seems Java has had the power to declare classes not-derivable for ages, and now C++ has it too. However, in the light of the Open/Close principle in SOLID, why would that be useful? To me, the final keyword sounds just like friend - it is legal, but if you are using it, most probably the design is wrong. Please prov...
In my project I've used a library marked with the LGPL license as a reference example to developed my own library which is completely different but it works roughly in the same way. Now I would like to sell my project which clearly links my own library and not the original one. Is there any limitation? Thanks
My application is growing in complexity. Currently, I have a collection of classes that make up a "Backend", this contains a DataInterface that talks to a database and returns POCO classes, a ModelProvider that wraps them up in models, and a ViewModelProvider that creates views, all dependent on each other. These insta...
I am looking for a Term/Word for specific type of tables. I have tried to search a lot, but I could not come up with best search terms for this. Tables that hold some master information, such as products, users, customers, brands etc. for the system are called - Master tables. Tables that hold some transaction informat...
I'm working on a ASP.NET application that is required to communicate with a Flask web service. My initial thought was to include the communication with web service directly into the aspx file, similiar to Scenario 1. However, I thought that Scenario 2 could be a cleaner solution as I can hide the properties such as ur...
I'm partitioning a stream of input data between n servers. The simple way of doing it is to use the hash of some property of each input data packet to assign a single server, using mod or similar, and be done with it. However, I want some degree of resiliancy - if one server goes down, nothing is lost. I want to partit...
In "Rob Pike's 5 Rules of Programming", he states, "Fancy algorithms are slow when n is small, and n is usually small. Fancy algorithms have big constants. " and as the next rule he states that "Fancy algorithms are buggier than simple ones, and they're much harder to implement." What does he means by "fancy" algorithm...
Background I am working on a project with C# .NET, and I've just added a new unit test project to my solution in Visual Studio. The way that I always have been doing this is: Create a new unit test project. Have that project include a reference to the project under test. Just include (using) the project. I guess the ...
In my Android app I want to have a couple of demonstration functions (i.e., functions that are not yet implemented but I want to show what they would look like if they were). All that needs to be done is to change the text and background color of TextView elements, at specified times. For example, when the app starts u...
My job involves a project that has a lot of different pieces that all need to communicate via XML messages. There are two schools of thought on how these messages should be organized. In reality these messages can contain hundreds of fields and lots of nesting, but I'll try to simplify. So let's say the project is for ...
I have a System which depends on Transactions, and a few other things. This list can become very long. Transactions can be (and will be) implemented in two ways or more, so every transaction is an interface. public class System { ctor(ITransactionA a, ITransactionB b, ... ITransactionN n, ...) } In my DI tool, I r...
Programmers often talk about point-free style. In contrast to the imperative style (pseudocode): h := function(x) { y := f(x) z := g(y) return z; } one might write the following point-free: h := f . g where . is composition and the argument is now implicit. I'm wondering if there is a name for h := function(x) ...
In the past, I used the standard way of adding @Deprecated annotations to API methods which will be removed in a later version. Now I am preparing a major version for a library, with many API parts removed and renamed. To make the transition easier for existing users, maybe it could be helpful if the new library versio...
I have been experimenting lately with enums, and I found out that in Java they can do much more than simply representing a fixed set of constants. Now, I am thinking about creating a new enum for my Logger class, to hold the different log severity levels (info, warn, error, etc), but I am wondering why shouldn't I tak...
What's the semantic version of the same software for different OS ? For exemple : X.Y.Z X is a major version Y is a minor version Z is a patch If I have the same version but for 3 different OS; How can I call them ? I don't find the answer in semver.org or in google..
I'm desing API for generic task executor that currently supports two calls: Accept task Get task info The (2) provides detailed information about the task with the task status and custom message, for example in JSON format: { ... status: "SUCCESS", message: "The task has been finished successfully" ... } ...
This question may have been asked before and if so feel free to link to the answer. I'm looking for a modern and effective recipe for a common problem. I have a project with a main module, A, that depends on another module, B, that I develop separately. this module has 2-3 (C-E) other modules it depends on, each of whi...
I'm having trouble understanding a small passage in The Structure and Interpretation of Computer Programs, and I'm hoping someone can help me interpret it. In the book's introduction to Orders of Growth (Big O Stuff--Page 48 in volume 2) the book states: We say that R(n) (resources required to compute a problem of siz...
I am working on a project which is a rewrite of an existing legacy software. The legacy software primarily consists of CRUD operations (create, read, update, delete) on an SQL database. Despite the CRUD-based style of coding, the legacy software is extremely complex. This software complexity is not only the result of t...
In Erlang, an ordering of the built-in basic data types has been established: number < atom < reference < fun < port < pid < tuple < list < bit string This means that sorting a list with a variety of different data types is possible. ([1, 2, 'foo', 42, {3}, 1] becomes [1, 1, 2, 42, {3}, 'foo']). However, it seems very ...
After some time in every project sooner or later you will need to find a feature in it a fix it or extend it so I was wondering if there is already a system or a convention for marking those features in code... what I mean is to somehow mark a place or places in code where a particular functionality is implemented or t...
In C#, when a field getting or setting requires logic, we use properties. For example: private int _age; public int Age { get { Console.Writeline("Club member is {0} years old", _age); } set { if(value > 0 && value < 120) { _age = value; } else ...
Still learning and getting my head around Unit Testing, (also trying to get into TDD, though I appreciate it isn't the same thing) and in many ways it is changing/improving my code. But I come across scenarios where I am unsure how to test a piece of functionality. Which leaves me wondering whether it's my code desig...
My colleagues like to say "logging/caching/etc. is a cross-cutting concern" and then proceed using the corresponding singleton everywhere. Yet they love IoC and DI. Is it really a valid excuse to break the SOLID principle?
I'm investigating how we can notify UI/async clients (websocket) about an update which happened in an embedded view. Let me elaborate... We currently have a newsfeed where NewsItem is an aggregate root which acts as a wrapper for news about other aggregates. News is extracted asynchronously from domain events of sever...
How to implement some constrained .NET struct/structure (let's say LimitedString), where its state with default values (set by CLR to technical defaults, i.e. nulls, zeros, etc.) should be prohibited due to some design constraint? For example in case of trivial struct LimitedString, properties are String Value and int ...
This programming style document has a general rule, that says : The rules can be violated if there are strong personal objections against them. This collides with the way I am thinking, and there are many articles saying that coding style is actually important. For example this says: A coding standards document te...
I'm reading the JavaScript guide on MDN and trying to understand the usefulness of closures. This sentence helped me the most, "In other words, the functions defined in the closure 'remember' the environment in which they were created." And I understand that part, but I don't get why this function... var getCode = (fun...
In order to be able to create better documentation, better tests and to start using the just gotten to know requirement traceblity matrix I'm trying to understand the different software requirement layers/levels first. I found that there are actually three of them. Would you say that in general this is true? Business ...
Our application is a 6-year old legacy application made by out-of-house contractors. Occasionally we stumble upon the skeleton of something they put together but never implemented, and it causes us to stumble as we try to figure out how it's used in the app. One of these classes seems like it might be close to what I...
I'm working on application in C#, where I need to serialize and deserialize some classes into/from XML. This operations will be implemented in Class Library. I chose XMLSerialization class to serialize/deserialize these classes to XML file. As you know, this implementation uses reflection, which has the condition that ...
I am currently learning C++ from the C++ Primer 5th edition. The book's chapter on functions states that only large objects (large being relative as standard library strings count, but "primitive types" such as int or char don't) should be passed as references. For instance, the following function serves as an example ...
This is how I do my JWT refresh token: A token is check for validity every time a request is made. If it's not expired, allow access. If it's expired calls another function named RefreshToken to give a new token to the user. Ok this mechanism is good enough except that every expired token (of that user, provided that i...
I am writing a simple IRC chatbot in Python and, in an effort to get more into OOP, made a basic "connection" class that manages all the backing-and-forthing involved. But IRC protocol is rather annoying to work with, so I wrote a function that takes the raw message from the server and translates it into a form that's ...
I want to implement gamification in my education mobile application. I have a database with user activity and I want to analyze it and give badges to a user. There will be many badges with totally different conditions. Some badges will be given once, others repeatedly. My current approach: badges_awarded table that co...
Like: switch (value) { default: something_common() case 1: niche_case() ... } etcetera. if-else statements require an "if" first and an "else" last, but switch statements are more flexible in their ordering. I think it's important to know what will happen "normally", which default indicates.
Im a beginner using visual studio 2013, and I know what they are, but I'm puzzled, why would one use a local variable? I would always just use a global variable.
I had a discussion with a co-worker about interface members having parameters that some implementations don't use. Say I have an interface interface IDoctor { string GetMedicalOpinion(Age age, Weight weight, SleepSchedule sleepSchedule, Symptom symptom) } Implementations of IDoctor won't necessarily use every meth...
The compiler doesn't leave its own code in the software or link proprietary libraries with it, the source code is exactly the same one I used throughout the development process, everyone is free to access and modify the source code, but no one can actually build a modified version of the software unless they have bough...
According to a book I read you can pass variables from one function to another by passing by value/address. When you pass by address it will no longer preserve the variable if it is changed in a function and returned back to the original function (ex: main()). The very next chapter, the book reviews "returning values"....
In Instagram (web), when you click back/forward arrows - I've noticed that the content isn't loaded from the server and it immediately show up. After reading the docs on react.js + flux, I had this understanding: Action -> Dispatcher -> Stores ... where the storeswould listen for changes and load new data from server i...
I have recently worked on a Python project where we did dependency injection heavily (because we must in order for the app to be testable), but we didn't use any framework. At times it was a little tedious to wire up all the dependencies manually, but overall it worked great. When an object had to be created in multipl...
I add a lot of elements to a list of lists. If the list of lists my element should be saved to, does not exist yet, I handle this by catching an exception and adding a new list to my list of lists. The reason I do this instead of checking every time, if the specified list already exists, is, that I add thousands of ele...
When uploading a lot of images to a server, to minimize the space taken by the images, is it better to resize the images before sending to the server or upon receiving them? It seems to me that resizing them in JavaScript can take long time for not a lot of gains. Is there any value to doing it on the client side? EDIT...