instruction stringlengths 34 19.9k |
|---|
What is the best way to handle errors that shouldn't ever happen?
My current way to do this is to throw an exception if the 'thing that shouldn't happen' does happen, like so:
/*
* Restoring from a saved state. This shouldn't be
* null unless someone in the future doesn't set it properly, in which
* case they will... |
Scenario
I haven't faced this requirement before, so I'm not confident with my solution. Our team drew up a plan to design a web application using a basic HAT stack for a project with a 4 month development time. We presented it to the client, who added two big new requirements. The requirements were:
The application m... |
My question is specific to php, but i think it can be useful in other languages.
I log into a table all the exception a code can throw:
try{
//Some code
} catch (Exception $e) {
$log = new Log(basename($_SERVER['PHP_SELF']), $_SESSION['id'], LogType::EXCEPTION, $e);
try {
$log ->addLog();
... |
When I programmed in python, I believe I interfaced with the transport layer using sockets. If python was programmed by humans, they must have used an interface that was "lower" than sockets, to provide us with the interface to sockets. I assume firewalls, also programmed by humans, use interfaces of lower layers in ... |
This occurs as a programming language independent problem to me.
I have a file with the content
aaabddd
When I want to insert C behind b then my code needs to rewrite ddd to get
aaabCddd
Why can I not just insert C at this position?
I can not do this in Java, Python, ... . I can not do this in Linux, Windows, ... . A... |
I have a game project that will have two versions:
A simple version of the game, the core.
An advanced version of the game.
I have the 1st version in my public repository, and only I will be working on it. As for the 2nd version, two friends of mine and I will work on it. The crucial part is that I want the two vers... |
I was reading this blog post about Hexagonal architecture and at the bottom it says:
The Loopback pattern is an explicit pattern for creating an internal replacement for an external device.
When I google for "Loopback pattern" I don't find any details about it. Does anyone know what the author is referring to? For ... |
I have a situation where I am trying to retrieve an object. If the lookup fails I have several fallbacks in place, each of which may fail. So the code looks like:
try {
return repository.getElement(x);
} catch (NotFoundException e) {
try {
return repository.getSimilarElement(x);
} catch (NotFoundEx... |
My team has a lot of IOC conventions that look something like...
if (type.Namespace == "My.Fun.Namespace")
{
// do stuff
}
Of course, maintaining this kind of thing becomes brutal after awhile, and we would rather not. The only option I could think of was to store these all in one place, as string constants or som... |
This thread will be long, but I will try to make it as short as I can. Thank you.
I have recently implemented a relatively simple program. What this program does is generate a simple piece of music and play it.
I will describe the object oriented design of the program and would like to hear your review of the design. E... |
Disclaimer: This is a question derived from this one.
What do you think about the following example of use case?
I have a table containing orders.
These orders has a lot of related information needed by my current queries (think about the products; the buyer information; the region, country and state of the sale point... |
I would like to bring our specifications to a better level of fine-grained definition of syntaxes, semantics and the like. I read my fair share of RFCs and just love the way they define things like "how an email adress looks like" or "what a correct URL is".
But, I haven't yet found a definition of the syntax of those ... |
I know the basics of the model driven architecture: it is all about model the system which I want to create and create the core code afterwards. I used CORBA a while ago. First thing that I needed to do was to create an abstract interface (some kind of model of the system I want to build) and generate core code later.
... |
I have a C# application that is developed with VS 2010 pro. The ultimate version would have a sequence diagram feature.
Since I will "create" my sequence diagram manually, how do I deal with quite long method names?
object.createPathForCustomerIDblablablabla_click()
Do I just use the method names as they are already g... |
Currently I am managing a team where we're building a new SaaS application.
The way it is currently structured is that we have a solution that has our business logic and data, and a solution that holds our website (and related projects)
In our current user base, there are clients that use different types of authentic... |
I have a Windows service with a fluent interface like this:
aRequest = Repository.getRequest()
.createProcess()
.validate();
Sometimes getRequest() could return a null value and this would cause an error in createProcess(). I could banally split getRequest() from createProcess... |
I have seen many CS curriculums and learning suggestions for new programmers that call for the aspiring programmer to study a Lisp interpreter that is specifically written in Lisp. All these sites say things similar to, "its an intellectual revelation", "it is an enlightenment experience every serious programmer shoul... |
I have a simulator that pulls data from a DB - calculates and return JSON result to an ajax call that renders a table for the results.
The calculation procedure are as follow:
grab X number of data that are group together and have weights to
them.
use historical data and run a weight distribution algorithm on the
grou... |
Given a colour image whose light intensity is dim at the edges and bright in the middle, such as [dim bright dim], which computer vision technique would be recommended to correct this imbalance?
While I believe Histogram Equalisation could help, I've read that it also introduces an unrealistic look to an image b... |
When working through the book "Implementing Domain Driven Design" by Vaughn Vernon, I have been unable to gain a good grasp on what a bounded context actually is.
The book defines a bounded context as "a conceptual boundary where a domain model is applicable. It provides Ubiquitous Language that is spoken by the team ... |
Watched some MountainWest RubyConf 2014 talks and noticed an interesting theme. Many dynamic programming environments back in the old days used to be self-contained VM images, e.g. SmallTalk, GemStone/S.
One could checkpoint, modify, and ship these images wholesale and have it up and running with very little effort. Fa... |
What the Dependency Inversion Priciple implies in practice is that in a system, high level components should depend on abstractions of the low level components (instead of on the low level components directly), and the low level components should be defined in terms of these abstractions.
The key point for my question ... |
Developing an alpha-beta search for "Colorito", which has the characteristic that sometimes simple hill-climbing is impossible; so a sequence of 2 or 3 moves is the only way to make progress.
I came up with an endgame position where, with a 6 ply search, it's possible to make
good progress in 2 moves but the third move... |
If I retrieve a random number from a database (e.g. RAND() in SQL Server) or using a programming language and send this in some form back to a client machine, is there an economic chance I will be sending an indicator of what's in my server's memory that might form a security problem (like revealing my schema, etc)?
|
I just got back from a conference in Boston called An Event Apart.
A really popular theme amongst the speakers was the idea of progressive enhancement - a site's content should go in the HTML, and JavaScript should only be used to enhance behavior.
The arguments that the speakers gave for progressive enhancement were v... |
I wrote a piece of code at my job sometime ago. While writting the code I wrote few interfaces who would allow me to add more flexibility and at that time I was also trying to understand OOP concept more deeper. So in the interface I wrote I have a method signature similar to this :
void Add(ImyBase objToAdd)
And then... |
I'm trying to write a program in c for Huffman coding, but I am stuck. For input I have:
Sample input:
4 // here I scan how many letters I have
A 00 // and for everyone I scan how they are coded in string down
B 10
C 01
D 11
001010010101001011010101010110011000 //this is a suboptimal huffman code
So first ... |
I'm working on a single page application on the node-webkit desktop app platform, which means 99.9% of all of the logic is written in JavaScript. Since this is a reboot of a project we're working on, I wanted to approach the architecture from more of an MVC approach on the client side.
I'm planning on creating a DAO la... |
After studying HTML 5, I learnt that HTML is purely for defining semantics of data. And it has provided various tag for each purpose. Although we can create our own tags, can provide styling and it will work still we use standard tags because they are known at global level. And all search engines can understand them.
J... |
Why can't I make a class for a Try including what I try and then run that in the try {} block? Why is it impractical?
class DBConnectTry extends Try {
TryResponse response[] attempt(TryObject o[]...){
//try to connect to database
}
}
Then in a try ... catch I could invoke only the DBConnectTry.attempt... |
Over at codereview a comment hinted that using snake_case to name test methods is a good idea.
This contradicted my views and I did some research and there seem to be a lot of examples that actually use snake_case for this.
Myself, I use classic camelCase names like testXyz for unit tests or a BDD approach givenXyzWhen... |
In section 6.4 of Code Complete 2nd Edition there is a paragraph about hiding global data. What I am particularly interested in, is that McConnell (the author of the book) gives examples of the benefits of hiding global data. There is one example that I cannot understand. I don't have the English version of the book, s... |
I've recently read The Art of Unit Testing by Roy Osherove which I found very useful for helping me establish how to define a good unit test.
One key aspect of the guidelines Roy puts forward are to make sure that one test only tests one thing, which is part of the following guidelines he puts forward:
Make sure the t... |
I am confused about use case levels. All I could understand was that use cases that are contained in another use case fall under the level which is below the level of the container use case.
I have identified the following use cases for an e-commerce store and I would like to know if their levels are correctly determin... |
So I took a job where the firm uses SVN (but will be moving to Git sometime in the future). The problem is that I don't know SVN. I've tried numerous Google queries and all I can ever find are SVN->Git tutorials, "Why is Git better than SVN" blogs, and a particular "cheat sheet" that gives (some) comparable commands...... |
What are my responsibilities, as a developer, if I stumble upon a zero day exploit in a widely used third party piece of software?
Should the developer only tell the third party to limit the affect?
What if the third party doesn't come clean to all its user base, who else should be alerted?
What are the responsibilit... |
I'm trying to write a program in c for Huffman coding, but i stack.In input i have:
Sample input:
4 //here i scan how many letters i have
A 00 // and for everyone i scan how they are coded in string down
B 10
C 01
D 11
001010010101001011010101010110011000 //this is an unoptimal huffman code
So first i ha... |
When writing (parameterized) tests for stateless functions, how do I determine the most ideal set of values to test with?
I'm writing a class with mathematical functions in C#, and I want to write unit tests for them. Today I want to write this function (really!):
int Clamp(int value, int lowerBound, int upperBound)
{
... |
I'm about to implement my own very simple programming language, and an interpreter to execute code in that language.
The language will be very basic. Example code:
var x = 3
if x > 2 print x
if x < 2 print "hello"
The language wouldn't feature anything more complex than single-line if statements. This is because it's ... |
I am about to deploy a new project that will have different components being deployed on different servers and in different web sites/technologies/etc. I was just wondering what would be the best way to communicate this with the business?
I want to show that Service X will exist on server Y as a Windows Service and Se... |
Our team has recently agreed on some very light coding standards, and that we need a means of enforcing them. We already have a mature Continuous Integration practice including frequent, small check-ins and pre-tested commits.
We're considering two methods for implementing an enforcement mechanism: a pre-commit SVN hoo... |
We have a large dataset that's current residing in many, many spreadsheets.
I've been tasked with getting part of that data into our MySQL DB.
When all is said and done, I will probably be inserting somewhere around 3 million rows.
I intend to collect the inserts into batches of about a quarter-million or so (parsing t... |
Consider the following:
if(a == b or c)
In most languages, this would need to be written as:
if(a == b or a == c)
which is slightly cumbersome and repeats information.
I know my above sample syntax is slightly clunky, but I am sure there are better ways to convey the idea.
Why don't more languages offer it? Is there... |
I know that I can share files between Visual Studio projects using linked files and assemblies using project references. Is there a good approach for JavaScripts? I'd rather not use linked files since it doesn't allow projects to have their own version of the script.
|
Say your company develops software, and a client wants you to handle their development. It just so happens, that they have their own IT-team, but it is fully tied up, so they outsource to you.
The project is in a quotation phase, and your client's Head of IT now asks for a requirement specification (SRS), an architectu... |
I want to write a simple markup language with its rendering engine.
First, I am not completely sure when I should try this... I am only 12... But I am competent in C++ having learned through the Web and books.
I am also good with JavaScript, PHP and HTML. I am currently learning Ruby and Haskell for a change.
I unde... |
Suppose you had the following interface
public interface IUserRepository
{
User GetByID(int userID);
}
How would you enforce implementers of this interface to throw an exception if a user is not found?
I suspect it's not possible to do with code alone, so how would you enforce implementers to implement the intende... |
We've been interviewing on and off for about two years, and I've run this by about 30 candidates. I wrote some 20 lines of code which perform a relatively basic operation, but has a bunch of errors in it. None of them are syntax errors. Errors range from bad memory management, incorrect data types, multithreading probl... |
I've just finished reading The Art of Unit Testing, by Roy Osherove. It was an interesting book, but I'm having trouble with something he mentions near the end (section 11.2.2):
Identifying "roles" in the application and abstracting them under interfaces is an
important part of the design process. An abstract class... |
Over the past couple weeks I have gotten a lot of help from StackOverflow users on a project, and rather than keep the finished product to myself I wanted to share it unencumbered by licenses, but don't want there to be so much legwork during installation that users shy away from trying it.
I am about to post it to Gi... |
Is it possible to implement generic routines in any language (C#, Java, etc). By generic routines I mean, in specific event Handlers. Lets say, I have 2 Buttons and 2 text boxes. One Button, when pressed, takes the first text box text and converts to Uppercase and second button prints the length of the string in the ot... |
If I add the following in this order into a red-black tree:
tree.Put(7)
tree.Put(3)
tree.Put(1)
7 3
/ rotate(3) / \
3 -----> 1 7
/
1
should I perform a right rotation after the insertion of 1 ?
I am reading the algorithms bible but it the pseudoco... |
We have a data service app working on object graphs. We place some complex graphs in a (memory) caching tier as a single data item, so as to avoid the length of time to retrieve every individual data item in disk storage in order to build the entire hierarchy.
That means whenever any of the data items change, a re-cach... |
Suppose I am using a very heavy applications(or you can say that it is a very bad code which keeps on allocating memory on heap and won't free it and also uses recursion) Now after some point of time both heap and stack will have no space to expand.
Now In this situation heap and stack don't have any free space in betw... |
For example I have this code:
$route = 'product/category';
//variable overload
$type = explode('/',$route);
$type = $type[1];
My thinking behind this is that I actually don't need unique variable name for exploded variable, so why not to overwrite?
Is this really bad concept? Or is there some more elegant way to wr... |
Related to this question i want to know if there is a concise way to eleminate null values out of code in general or if there is not.
E.g. imagine a class that represents a user with birthday as attribute which can be set but does not have to, which then means it's null. In scala and similar languages one could use the... |
I've recently come across a Python library on GitHub. The library is great, but contains one glaring typo in a function name. Let's call it dummy_fuction() while it should be dummy_function(). This function is definitely "in the wild" and most likely used in embedded systems.
The first thing that springs to mind is to ... |
I just starting to use Core Data for my iOS app and I am thinking about how use Core Data for my needs.
What are the features of my app:
The user look for products proposed from a catalog.
The user can add products into a basket.
The user can customise each selected product.
The user have to create an account to purch... |
I have a RESTful call that can modify the state of an instance. My problem is that the JSON is different based on the type of action the user is taking, it could be a SetProperty action or a SetState action (among others).
For example, a POST /api/sample/ _would send the following JSON
{
instanceId: 12312,
... |
I'm sure designers of languages like Java or C# knew issues related to existence of null references (see Are null references really a bad thing?). Also implementing an option type isn't really much more complex than null references.
Why did they decide to include it anyway? I'm sure lack of null references would encour... |
I would like to have a function that will create a word (always the same word) for a given sequence number based on a given alphabet.
word(0, [a,b,c]) = a
word(1, [a,b,c]) = b
word(2, [a,b,c]) = c
word(3, [a,b,c]) = aa
word(4, [a,b,c]) = ab
word(5, [a,b,c]) = ac
word(6, [a,b,c]) = ba
word(7, [a,b,c]) = bb
word(8, [a,b,... |
When lexing, what would be the best way to tokenize operators? Would one just create a BinaryOperator token, or a separate token for every single binary operator? Examples: PlusOperator, MinusOperator, DivisionOperator ...
I am tended towards having a universal one, but going from the documentations and project source... |
Are there any design patterns or best practices around logging events for use in reporting and BI systems.
For example in a system which manages orders from a website, it would be beneficial if a customer support worker could type in an order number and see that it the order was placed on a certain day, dispatched on ... |
I don't consider myself a highly skilled javascript developer, but I thought I got one thing right for sure: don't create global variables unless you really have to.
I've been learning angularjs lately and discovered one strange thing, almost everywhere in code samples for angular you can find constructions like the fo... |
I am designing a web server that handles multiple things such as a user-to-user chat, a user-to-group chat, friends request, forum etc.
The chats have to be real-time chats, the friends requests should be notified in real-time to the user, and the users should be instantly notified about the new topics on the forum.
I ... |
I'm designing a utility that will load data into a legacy SQL Server Database.
I've been trying to mock up a simple WinForms utility with C# using the DataSource connectors (Tried a straight ORM Entity Framework approach first, but was having problems as the db follows few conventions).
I am having particular difficult... |
My coworker likes to see all of our unit tests pass (as would anyone) and he argues that some of the failing tests of a system he wrote are unnecessary "noise" since they all involve the validity of the data and a separate system in our stack is supposed to be responsible for validation.
Personally, I think keeping the... |
I'm working on some inherited code in C++ and am trying to use 2 classes with templates as I need 2-types of each class to operate on floating point or integer data (double v uint64_t to be exact).
In the two classes that I'm trying to "templatize"(?), one inherits from the other. Data definitions needed for both ar... |
Eric Lippert made a very interesting point in his discussion of why C# uses a null rather than a Maybe<T> type:
Consistency of the type system is important; can we always know that a non-nullable reference is never under any circumstances observed to be invalid? What about in the constructor of an object with a non-nu... |
I wonder why I rarely see any IDEs or other developers that use background colors for syntaxhighlighting.
One of the first things when installing and configuring a new IDE is adjusting the colors so that for example comments have a decent light-grey background. This really helps me seeing where documentation is and whe... |
In most, if not all implementations of regular expressions, the \w metacharacter matches all alphanumeric characters plus the underscore.
Historically speaking, why was the underscore character included in this character class? And why not include dashes too?
|
The question title is not good, but I couldn't think of a way to word it better.
I am used to develop using POCO classes in my projects, that is, domain objects contain absolutely no logic, only data.
I am wondering which is the best approach when dealing with class relationships - to put a collection inside the class ... |
I'm interested in building verifications into a REST service to help with service monitoring.
For example, one could run assertions like http://example.com/posts/verify?min-posts=5&since=1-hour-ago which would respond with an error unless 5 new posts had been created in the past hour.
Are there any existing services li... |
I need to connect to a server and do manipulation with respect to HTTP GET and POST for my application and the server is generally used to handle multiple users with heavy load and many users might be sending multiple request at any moment.
I have 3 questions here.
The server is configured with ASP.NET
I am using Java ... |
I was thinking to make some jQuery functions that will use ajax to control mysql. The whole idea is to make separate files of PHP (e.g query.php, addRow.php, update.php and delete.php) provide data to them via the GET variables like query.php?sql=SELECT * FROM table and then control them with jQuery AJAX functions that... |
Is it a lexer's job to undo any escaping done to a string literal? For example:
"Me: \"Hello World!\""
Becomes:
Me: "Hello World!"
Should this conversion be done inside the lexer? I am guessing it should, because it'd allow for a more abstract and modular design. You could add ways to represent strings and you won't ... |
I'm a C++/C# developer and recently I've started to learn Python. I think I understand the concept of duck typing right now except for one thing.
When I'm coding in C++ or C# I sometimes create completely unrelated classes that have similar methods with similar signatures, for example: Create(), Open(), Close(), Proces... |
The Problem
Imagine you have a function in a public API that needs to return some kind of collection. Its type is something like
foo :: a -> b
where b is some kind of collection.
As far as I can see, there a three major kinds of collections -- at least those are the ones used most often:
Sequences (order matters, the... |
I am trying to scrape websites for valuable text for example the title of an article, the author's name, and other distinguished text. I cannot always guarantee that this sort of text will have informative tags, and but this needs to be done as quickly as possible. As a possible short cut I think that I could just try ... |
Since I learnt about MVC, I used it for every app I made (which is arguably not the best idea, but that's not the topic of this question). All of them small, 1000 LoC apps. I am using Java and Swing for the GUI.
What usually happens is this:
The view (the GUI class) reports to the controller about any GUI event (most c... |
I have been self studying algorithms and data structures for some time now and currently enjoying it. Whenever I understand an algorithm, I usually try to code them from scratch for fun and I always will discover some logic I've never thought of before. I'm not so sure, but I always think that when I code algorithms, I... |
My company runs 2 websites, a public facing website for clients, and an employee intranet. The intranet is used as a backend for employees to edit and maintain various parts of the public website. Both are written in PHP. The intranet is years older, and was designed using an inhouse framework. We have recently created... |
The Single Responsibility Principle states that "a class should have one reason the change".
In the MVC pattern, the Controller's job is to mediate between the View and the Model. It offers an interface for the View to report actions made by the user on the GUI (e.g. allowing the View to call controller.specificButtonP... |
Is there a way to find errors caused by crafted input in php, such as naming POST-fields like variable[] instead of variable, causing PHP to implicitly convert it into an array, by using some form of automated testing?
|
I know that exception should be thrown in exceptional case (e.g. out of memory, programmer error). For these cases, I don't need to worry about performance throwing these exception.
But what happen if use exception in normal code path?
In my case, use it to stop user code supplied function.
So for given code, is foo be... |
I'm fairly new to unit testing. In school it's always been, "hey it works, onward!" But I've started to write professionally, and even at work that's been basically the mantra. However, I've started to see the validity of unit testing and TDD. I've come to a realization, that when I write maybe a 20 line piece of code,... |
I wanted to know if there is a way to make your JavaScript private from client side?
|
Database designers building enterprise systems usually assign different sets of privileges to different users of DBMS. They can be as granular as needed.
However, in my experience, web frameworks usually use a single connection to a DBMS, and the privileges are assigned and enforced at the framework level, through some... |
Even if I don't like enforcing people to do things (and I believe that it may decline the productivity and cause anger), I really want to enforce good coding style.
Is there a way to set up something like an integration server that measures the quality of code (for example it runs resharper or some other static checke... |
I'm trying to choose a good name for a new open-source project. The problem is, there is already so much software in the world that Google search reveals one or more existing programs with every good name I can think of (and there have been several already).
Obviously, names like "Linux" or "Windows" or "Java" or "Exce... |
Consider an app that allows plugins to react to its program flow.
I know 2 ways to achieve this: hooks and events
1. Hooks
Use calls to empty functions inside the main program flow. These functions can be overriden by plugins.
For example, Drupal CMS implements hooks which are available to modules and themes. Here's an... |
Now I'm only a novice programmer, but what my friends that are studying programming tell me is that recursive code is a good thing, it leads to less code duplication and it looks more elegant.
Now it may be so, but everytime I've tried my hand with recursive code I've always found it to be significantly slower than no... |
I carefully followed the "always write quality code, unless you're writing a prototype" advice during my career as freelancer and software developer. I was convinced pretty early that avoiding to do code reviews, testing, QA or refactoring doesn't make the project faster, but only slower.
Books like The Mythical Man Mo... |
Using Python and sqlite3. This simple print loop takes a few seconds to execute. I don't know much about databases, so I'm guessing I'm not using these queries correctly. Surely sqlite should be faster? The entire db has 5k or so rows and just a few columns if that matters.
con = lite.connect('gamelist.db')
with con:
... |
I was reading a proposal for value types in Java, and I came across this sentence: "Object identity serves only to support mutability, where an object’s state can be mutated but remains the same intrinsic object."
From what I understand (albeit tentatively), object identity is the idea of your variable acting as a poin... |
Most of the HTTP Servers I know send their application name and version in response http headers as default behaviour. (Nginx, IIS, Apache etc.) Of course we can change the default behaviour but I wonder why they send these information? Does it matter which HTTP Servers we use to the requesters?
The only reason I can t... |
Say you have a Car class. Properties that make sense for a Car class might be:
var make;
var model;
var year;
var turnOn; // a function
But the turnOn function is very complicated and ends up needing a static variable and a couple sub functions:
var isTurningOn; // too specific to be a class variable
function turnOn()... |
I'm working on a coarse API for performing higher level business functions. Under many conditions these functions may fail in a way that is expected (not exceptional), ie. the function may not be able to complete because of failing a validation condition of some kind.
In many cases, what I want to do in these "failure... |
I've seen at SOLID there is a principle Dependency inversion principle.
Also I've seen that: High-level Classes should not depend on Low-level Classes but both of them should depend on abstractions.
What exactly means High-Level Classes and Low-Level Classes?
|
In an MVC architecture pattern (for e.g., in iOS) there is a controller per view. In UML there is a concept of having Control object per use case to encapsulate an use case, which may span more than one view. Sometimes a same view can support multiple use case, in which case it would be nice to have multiple 'use case ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.