title: Testing gap between unit and integration: Integration in the Small, Component, Unit Integration Tests

text: Over the past few weeks I've been mulling and researching how to fill a gap in our testing methodology. In simplified terms unit tests are too small and traditional integration tests are too big. A frequent scenario comes up where `A` and `B` both use component `C`. However `A` and `B` have slightly different requirements for, and make slightly different assumptions about `C`. If I'm the developer of `A` how and where do I test my assumptions about `C`? Obviously unit testing `A` with mocked assumptions about `C` is fine for testing `A` in isolation, but it doesn't test the assumptions themselves. Another possibility is to add unit tests for `C`. However this isn't ideal because, while `A` is in development, altering the tests for `C` with evolving assumptions from `A` will excessively be clumsy. Indeed `A`s developer might not even have adequate access to the unit tests of `C` (e.g an external library). To frame this with a more concrete example: Assume that this is a node application. `A`, and `B` depend on `C` to read a file (among other things) and store the file contents in object passed to `C`. At first all files that `C` handles are small and can be read synchronously without significant blocking. However the developer of `B` realizes that his files are getting huge and needs to switch `C` to a async read. This results in a sporadic synchronization bug in `A`, which is still assuming `C` is reading files synchronously. This is the type of bug that is notoriously difficult to track down from full integration tests, and may not be caught in integration tests at all. It is also not caught by `A`s unit tests because the `A`s assumptions are mocked. However it could easily be caught by a "mini" integration test that exercises just `A` and `C`. I've only found a few references to this type of testing. Integration in the Small, Component Integration Testing, Unit Integration Testing. It also relates somewhat to BDD testing direction rather than formal TDD unit testing. How do I fill this testing gap? Specifically -- where do I put such tests? How do I mock the inputs of `A` and `C` for "mini" integration tests? And how much effort should be put into separating testing concerns between these tests and unit tests? Or is there a better way to fill the testing gap?


title: Storing object-graphs with class-evolution in Java with transformation (long time archiving)

text: ## Abstract A common problem is to store objects (with graph), and to load them back. This is easy as long the stored object representation matches the executing code. But as time goes by, requirements change and stored objects do not match any longer the code. The stored objects should not loose their data, and the code in the clients should work with the latest object-models. So a transformation has to occur somehow between loading the data and returning a object to the client. I know that there exist some libraries such as XStream, gson, protobuf and avro. They could load older objects, but afaik just ignore data that does not match any longer the fields in the class (maybe I missed something).   (When I'm talking about storing and serialization I do not mean Java's built in serialization mechanism.) ## Question So what is the question? I'm now researching for some time, and there seems no library that adresses this issue (class evolution) without data-loss. I hope to find another working solution or idea how to implement it by myself here. I have some requirements:   * File-based - I want to be able to store the serialized object on disk   * Appendable - I want to append multiple objects to one file without loading the whole file in memory again and again   * Support for multiple versions in one file - A file could contain objects with different version (only of the same type)   * Transformation - Data should be accessible by using the same type, even when changed in between.   * Generic - The mechanism itself has to be generic, so I could use it for different objects (different objects do not get mixed in one file, only different versions of one type). It would be nice if the storing format is human-readable. Already stored objects are not updateable (at least not without huge effort). Think of an long-term archive. ## Example I could give an example for better illustration. Let's suppose we have two Pojos that we want to serialize.               public class MyPojo {         String text;         Long number;         Integer[] values;         SubPojo pojo;     }          public class SubPojo {         List<String> items;     }      In the next version we might have renamed a field (text->content), changed a type (Integer[]->List), and have transformed a field to List (SubPojo->List) where the previous field now is the first element of the new list (not loosing data, just transforming to new representation).               public class MyPojo {         String content;         Long number;         List<Integer> values;         List<SubPojo> pojo;     }          public class SubPojo {         List<String> items;     }      Some pseudocode how the client might take use of this:               // Write     Serializer ser = new Serializer();     MyPojo pojo = new MyPojo();     pojo.xxx = ...; // set fields     ser.store(pojo, file, append);          // Read (a version later)     Serializer ser = new Serializer();     ser.registerTransformer(new TransformerV1ToV2());     List<MyPojo> pojos = ser.load(file);      This approach has some drawbacks:   * The transformer have to work on some kind of intermediate format (could be the backed stored format such as json or xml)   * You don't know how the class format was at some point in time, since you're only transforming relative to the previous version and mapping to the final class, making search for errors hard   * Performance (depending on how the transformation happens)


title: DDD Proper aggregates division and getting rid of too many references

text: I am designing an application, which will aid designing electric installations. I went for Domain Driven Design, as the topic is complex and the application will be growing with gained knowledge. However, I am newbie to this concept. For now, I have a problem to properly model the domain, especially to divide entities into aggregates. I have defined wiring - **Installation** as a set of **ConnectionPoints** and **Cables** , which connect them. One **ConnectionPoint** has one or more **Cables**. Each **Cable** has a set of wires. I consider end of a wire as a **Terminal** , which we can connect to another **Terminal** creating a **Junction**. **Terminals** differ one from another, as wires have different colours and purpose. **Junctions** are made of two or more **Terminals** and can be done only inside a **ConnectionPoint**. I have illustrated it for a better understanding: ![Illustrated ConnectionPoint](http://i.stack.imgur.com/mU78k.png) Besides **Cables** there are also **Devices** , which also have **Terminals**. They are also connected in a **ConnectionPoint** and their **Terminals** are treated the same way as **Cable** 's **Terminals**. For each **Device** I must be able to track, where the **Terminal** is connected to (it might be a list of end points). The problem, with the design, is the need of having references to **Terminals** outside of a **Cable** and **Device** entities to create **Junctions** and track connections. I could consider a **Cable** and a **Device** as aggregates of **Terminals** , as **Terminals** cannot exist without them and as a knowledge of **Terminal** 's parent is important. However, each **Terminal** has also an identity outside of a **Cable** / **Device** and I have no idea how later in code and database I could keep knowledge of the connections made. Do you have any ideas how could I model it? What questions should I ask myself to define a correct model and avoid keeping references everywhere?


title: Modeling an extensible Domain Driven Design project

text: Say that we are developing an application with modules (Sales, Accounting, Purchasing, etc). An example case here is : Sales module is the basic / primary module available, and Accounting module is a complementary module.               SalesModule     -. Product      And               AccountingModule     -. Account     -. Journal      If we were to say that : > If the Accounting Module were installed, then it will provide a direct > integration with the Product class from the Sales Module, such as : a > Product now has a List of Account which if a transaction is applied to the > Product, a Journal will be posted according to the Account. In my mind, I would picture that `Product` would have a property of `List<Account>`, but that would be impossible without adding that property directly in the `Product` class, making `Product` now dependent on Accounting Module when SalesModule should be able to run without it. Another solution came up to mind is to add `SalesIntegrations` classes (ProductAccount, etc) to complement the previously described `Product`, making it independent. But this solution doesn't sound as 'natural' as saying that `a Product has a list of Accounts`. From what I understand, doing DDD means to know beforehand the whole concept of business rules. What if a requirement come along to add a new project to complement the previous DDD project with only having it's DLL (no access to source code)?


title: Storing revisions of a document

text: This is a follow up question to my original question. I'm thinking of going with generating diffs and storing those diffs in the database 'History' table. I'm using diff-match-patch library to generate what is called a 'patch'. On every save, I compare previous and new version and generate this patch. The patch could be used to generate a document at specific point in time. My dilemma is how to store this data. Should I: a Insert a new database record for every patch? b. Store these patches in javascript array and store that array in history table. So there is only one db History record for document with an array of all the patches. Concerns with: a. Too many db records generated. Will be slow and CPU intensive to query. b. Only one record. If record is somehow corrupted/deleted. Entire revision history is gone. I'm looking for suggestions, concerns with either approach.


title: How is Sencha Touch performing on Android in practice?

text: I'm just about to start a project using Sencha Touch, and just done some minor testing on my HTC desire device. All tutorial videos at Vimeo seems to be using an iPhone emulator running on a Mac. Im not sure how fast this emulator is compared to a real iPhone device or even an real Android device, but from what i have experienced, it seems that my HTC desire is not performing that nicly as this emulator. All animations (sliding, fading, etc) seems abit laggy. You can easily notice that the FPS is much less than on the Vimeo videos. HTC desire is a relativly new and modern Android 2.2 phone, running with decent hardware, so im wondering if Sencha Touch is "ready" for the Android platform. Anybody with practical experience with Android and Sencha Touch ?


title: What is the best way to handle nuances for different platforms?

text: I'm working on a normal Java/SWT desktop application I'm planning on distributing to the three primary PC platforms (Windows, OSX, Linux). Obviously, there are slight differences between them, mainly having to do with files. What's the best way to keep those differences separate? I'm thinking three different SVN branches (win, osx, linux), and trunk for development, but then how do I update the branches without overwriting the differences? Do I need to define a platform constant instead at compile time? And then, of course, there are different versions of libraries (i.e. SWT in my case). How should those be handled? Where should I keep the compiled byte-code ".jars" files?


title: Why are SW engineering interviews disproportionately difficult (vs. research interviews)?

text: First, some background on me. I have a PhD in CS and have had jobs both as a software engineer and as an R&D research scientist, both at Very Large Corporations You Know Very Well. I recently changed jobs and interviewed for both types of positions (as I have done in the past). My observation: SW engineer job interviews are way, way disproportionately more difficult than CS researcher job interviews, but the researcher job is higher paying, more competitive, more rewarding, more interesting, and has a higher upside. Here's a typical interview loop for researcher:   * Phone interview to see if my research is in alignment with the lab's research   * In-person: give presentation on my recent research for one hour (which represents maybe 9 month's worth of work) and answer questions from the audience   * In-person one-on-one interviews with about 5 researchers, where they ask me very reasonable questions on my work/publications/patents, including: technical questions, where my work fits into related work, and how I can extend my work to new areas Here's a typical interview loop for SW engineer:   * Phone interview where I'm asked algorithm questions and maybe do some coding. Pretty standard.   * In-person interviews at the whiteboard where they drill the F*** out of you on esoteric C++ minutia (e.g. how does a polymorphic virtual function call work), algorithms (make all-pairs-shortest-path algorithm work for 1B vertices), system design (design a database load balancer), etc. This goes on for six or seven interviews. Ridiculous.  Why would anyone be willing to put up with this? What is the point of asking about C++ trivia or writing code to prove yourself? Why not make the SE interview more like the researcher interview where you give a talk about what you've done? How are technical job interviews for other fields, like physics, chemistry, civil engineering, mechanical engineering?


title: Seeking Delphi (Pascal) code beautifier

text: Preferably a tool which will run from inside of the Delphi IDE (I use Delphi 7), but I can accept a standalone program. Should have the ability to define rules (X space indent, no tabs, one statement per line, etc, etc (perhaps capitalization rules too?)) Nice if it can handle an entire directory or project at one touch, rather than just a single file. Anyone?


title: Do setters and getters always break the Single-Responsibility Principle?

text: As we know, The SRP states that every class should have single responsibility and that responsibility must be entirely encapsulated by the class. But setters and getters do serve another responsibility - they do abstract class property(data) access. if _Setters and getters_ do abstract class property access, then **they do serve another responsibility**. So if I have something like this,               class Config     {              private location;                   public function write(array $data)         {             ....         }              public function read($key)         {             ...         }              public function exists($key)         {             ...         }              public function delete($key)         {             ...         }              // Below comes property abstraction              // Here I doubt - I CANNOT USE this class without them         // but they seem to break the SRP at the same time!?              public function setFileLocation($location)         {             $this->location = $location;         }                   public function getFileLocation()         {             return $this->location;         }                   public function setConfigArray(...)         {             ...         }              public function getConfigArray()         {             ...         }     }      I do break the SRP. The problem is that, that's the only way class may exists. So the question is, In my situation, it's almost impossible to avoid `setFileLocation()` and `getFileLocation()` methods with CRUD ones. So if by combining CRUD methods with Data Access abstraction I do break the SRP, Is there any way I can adhere the SRP and keep the common concept of the Config class (CRUD operations) at the same time?


title: When should an IT consultant use full disc encryption?

text: In what circumstances should an IT Consultant encrypt their hard drive to protect their code/data of their clients? I am thinking that if it does not add much to your work load you might as well use full disc encryption with a 'weak' password to at least prevent someone from accessing your email files and other documents if your laptop is stolen, even if they will not get access to any database files or other very sensitive data.


title: How do you decide what to work on in your own time?

text: I've got an itch and it needs to be scratched. I've got nothing to program these days. Normally I'd just pick my flavour of the month technology and fiddle with it, but I want to make something and take a break from serious research/experimentation for a while and just write something for fun (ie. not necessarily purely educational/professional development). Problem is,   * I can't think of software that I need that I don't already have.   * Sifting through the open-source projects on various sites to help out on is excruciating (5 hrs down the tubes so far - not worth the trouble) I'm not looking for a specific suggestion for what to work on because that would be a terribly hard task. I don't think that here knows nearly enough about eachother to effectively give good suggestions. So I ask, is there any mental exercise that you use to decide what to make when you're not "fiddlin'"?


title: Problem sets or challenges and solutions for beginners to practice MVC, OOP, MVT etc. type problems

text: Coding bat, project euler, python challenge for example are all amazing brain teasers that usually provide you with some learning material, ways to compact your code, and enhance your problem solving skills. At the end of the day, when you go through a few of those exercises, you learn something new, or you better understood a concept. Are there similar exercises for OOP, MVC, MVVM, MVT, and so on type situations? In class it is usually taught to think of an object as a cat, part of an animal class. and you have mammals and so on. However, in real life, objects are more abstract, and harder to imagine and implement. The same could be said about MVC, MVVM, and MVT, where applying a small system is usually simple, but when the problem is scaled, it suddenly becomes a bit more daunting.


title: By the definition of a Tree(ADT), is it "wrong" for a node to add a sibling?

text: The title pretty much says it all. I'm just having a little computer science exercise and am building a Tree. I want a node to be able to add a sibling which requires one to first get a reference to the parent, obviously. I was wondering what is the "correct" way, by definition of what a Tree is, to do such a thing?


title: MVC: Does the Controller break the Single Responsibility Principle?

text: 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.specificButtonPressed()`), and is able to call the appropriate methods on the Model in order to manipulate it's data or invoke it's operations (e.g. `model.doSomething()`). This means that:   * The Controller needs to know about the GUI, in order to offer the View a suitable interface to report user actions.   * It also needs to know about the logic in the Model, in order to be able to invoke the appropriate methods on the Model. That means that is has **two reasons to change** : a change in the GUI, and a change in the buisness logic. If the GUI changes, e.g. a new button is added, the Controller might need to add a new method to allow the View to report a user press on this button. And if the business logic in the Model changes, the Controller might have to change in order to invoke the correct methods on the Model. Therefore, the Controller has **two possible reasons to change**. Does it break SRP?


title: How to unit-test for PHP implicit conversion errors?

text: 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?


title: What is a Ph.D. good for in the software industry?

text: I'm a self-taught programmer and have just started a computer science degree to supplement my knowledge and fill in the gaps. However, I'm already debating the direction of my education. I want a 4 year bachelor's degree for sure, but after that, I'm not sure: Is it worth it to get an M.Sc? What about a Ph.D.? What opportunities do these degrees open up? Currently my goal is to be a software developer, but there are a number of fascinating fields in the software industry and I'm certainly interested in investigating many of them. It is in this respect that I think a higher degree may be worth it -- even if it wouldn't necessarily help a career of software development. So will it be worth it? Will grad school open doors?


title: Is there any technology similar to LINQPad for compiling C# that runs in a browser?

text: Think JSFiddle. LINQPad is pretty sweet for fast C# with similar options. Is there anything like LINQPad that runs in a browser?


title: What level do I mock when I have function A calling function B which calls the database?

text: I have created a scenario in which I have two functions, A and B, both are tested, but despite the tests I still injected a rather stupid bug and some data is not getting into the database. Note that there is no ORM present. I've written my CRUD operations directly, and I'm paying the price therefor. In this scenario, I have (perl) something like this:               sub A {       ... do a bunch of work ...       my $res = B( %data );       ... do a bunch more work ...     }          sub B {       my ( %data ) = @_;       ... record data to the database and return a result ...     }      What happened, though, is that in my higher-level application and in A itself, I changed the name of one of the fields that goes into %data, but forgot to change it in B. I have a test for A which stubs/mocks out a _lot_ of the things A does (A needs to meet with a goodly refactoring), including B. The stub for B verifies that all of the correct parameters, including the correct field names get passed in, and so the test passes. _BUT_ the test for B verifies the old field names, the real B actually uses the old field names, and that test passes as well. And, thus, I put into production some code that, because of this oversight, is putting NULLs into the database where I don't want NULLs.   * A is clearly too big. To isolate it, I mock out six different functions, each of which could cause a system state change.   * A, and thus the test for A is theoretically unconcerned as to the strategy by which B will store data in the database or even what kind of database B will store data to, so I think the test for A probably should not query the database directly.   * But, I changed the format of %data, and I think that the test for A should have detected that I basically changed the API without propagating the change down. What is a better way to set up a test to catch this case beforehand?   * Continue with the isolation strategy for A and B, but also write an integration that tests A --all the way to-> the database? This would lead to a proliferation of possible test cases, and I'm already having trouble justifying the existing test case proliferation to management (though I know the coverage to be woefully inadequate).   * Just write the test for A to query the database, possibly through an abstraction?   * Is there something different that would help here? * * * Ultimately, I took Karl Bielefeldt's suggestion. I added the data validation code into function B. I also added the integration test that tests from A all the way to DB. As far as I can tell, I need to have as many integration tests as I possibly can, verifying that the overall state of the system resources change predictably. At the same time, I expect I'll still need to mock network resources if I cannot actually get a test network environment.


title: Is there a reason to prefer lambda syntax even if there is only one parameter?

text: List.ForEach(Console.WriteLine);          List.ForEach(s => Console.WriteLine(s));      To me, the difference is purely cosmetic, but are there any subtle reasons why one might be preferred over the other?


title: Synchronous sockets with Node.js

text: I want to port an existing app from Java to Node.js - would like to seek your advise. The java app is a multithreaded socket server where arbitrary number of clients can connect. The app runs on java executors. Each client is given a socket to connect to the app. The client will connect to the socket server and there will be handshake. After handshake, the data will be transmitted between the client and server. The data transferred is in sequential order because the client sends the data over as such. And I.m able to control the thread that the client is connected on. Now, Node.js does not have threads so I am confused on how to port the multithreaded Java socket server over. Any ideas?


title: How are atomic operations are a dynamic language feature?

text: I was told that atomic operations are a dynamic language feature. I was too afraid to ask in that context what this actually means because I didn't want my coworkers to think I'm stupid. But I actually don't really understand this statement. My understanding of the term "atomic operations" is any operation that is either wholly executed or wholly not executed; you will definitely never be halfway through the operation when the thread context switches. What does this have to do with dynamic vs static typing?


title: Difference between an architecture and a framework

text: A terminology question appeared when I was comparing EJB 3 and Spring. Wikipedia says that > Enterprise JavaBeans (EJB) is a managed, server-side component architecture > for modular construction of enterprise applications. and also > The Spring Framework is an open source application framework and inversion > of control container for the Java platform. "EJB 3 in Action" suggests that > Together, the components, or EJBs, and the container can be viewed as a > framework that provides valuable services for enterprise application > development. Is any framework an architecture? If not, what is the difference between these terms? Could EJB be considered a framework?


title: Should OAuth token be shared to implement SSO?

text: What's a commonly accepted way of implementing SSO using a third party OAuth provider? I have a server with user resources associated with server's user ID, the user ID also has a Facebook user ID associated. Would it be a good approach to authenticate a client to the server if the login was redirected to, say, Facebook where it would return an OAuth token and the token is then shared with the client? Suppose SSL is implemented, the OAuth token would then act in the same way as a session cookie that gives permission to user resources on the server. The same user an different client can then reauthenticate with Facebook which would return the same Facebook ID, which gives access to the same user's resources and a different OAuth token which expires independently and removing the app on Facebook can callback the server with a deauthenticate request to keep things synchronised. Is this a good policy to use? Is it safe against attacks like session sidejacking, cross site reference etc?


title: What do you absolutely have to know about a candidate before hiring him?

text: What **essential questions** do you have to know the answer for, about a prospective software development candidate, before hiring him/her? I'm not seeking specific interview problems (e.g. sort this 3D array of numbers in O(1) complexity), but simply for things you need to find about, for yourself, about a new hire. (e.g. which source control systems / languages / frameworks / OS has he used?) Cross-posted to Quora


title: Memory read/write access efficiency

text: I've heard conflicting information from different sources, and I'm not really sure which one to believe. As such, I'll post what I understand and ask for corrections. Let's say I want to use a 2D matrix. There are three ways that I can do this (at least that I know of). **1** :               int i;     char **matrix;     matrix = malloc(50 * sizeof(char *));     for(i = 0; i < 50; i++)         matrix[i] = malloc(50);      **2** :               int i;     int rowSize = 50;     int pointerSize = 50 * sizeof(char *);     int dataSize = 50 * 50;     char **matrix;     matrix = malloc(dataSize + pointerSize);     char *pData = matrix + pointerSize - rowSize;     for(i = 0; i < 50; i++) {         pData += rowSize;         matrix[i] = pData;     }      **3** :               //instead of accessing matrix[i][j] here, we would access matrix[i * 50 + j]     char *matrix = malloc(50 * 50);       In terms of memory usage, my understanding is that **3** is the most efficient, **2** is next, and **1** is least efficient, for the reasons below: **3** : There is only one pointer and one allocation, and therefore, minimal overhead. **2** : Once again, there is only one allocation, but there are now 51 pointers. This means there is `50 * sizeof(char *)` more overhead. **1** : There are 51 allocations and 51 pointers, causing the most overhead of all options. In terms of performance, once again my understanding is that **3** is the most efficient, **2** is next, and **1** is least efficient. Reasons being: **3** : Only one memory access is needed. We will have to do a multiplication and an addition as opposed to two additions (as in the case of a pointer to a pointer), but memory access is slow enough that this doesn't matter. **2** : We need two memory accesses; once to get a `char *`, and then to the appropriate `char`. Only two additions are performed here (once to get to the correct `char *` pointer from the original memory location, and once to get to the correct `char` variable from wherever the `char *` points to), so multiplication (which is slower than addition) is not required. However, on modern CPUs, multiplication is faster than memory access, so this point is moot. **1** : Same issues as **2** , but now the memory isn't contiguous. This causes cache misses and extra page table lookups, making it the least efficient of the lot. First and foremost: Is this correct? Second: Is there an option **4** that I am missing that would be even more efficient?


title: When to use (Or not) C# myVariable { set; get; }

text: I have been trying to wrap my head around the finer points of this today. Essentially I have fallen in love with this format for booleans:               Class {     public static bool myBool {set; get;}         private static void Method()         {             if (!myBool)              {                 myBool = !myBool;                 // stuff that needs to be done              }         }     }      Obvious things like do not use a public when a private will work and scoping properly applies. But when is this a best practice vs using a simpler:               Class {     bool myBool = true;         private static void Method()         {             if (!myBool)              {                 myBool = !myBool;                 // stuff that needs to be done              }         }     }      Or do I have this backwards completely? I understand that by using the format `public static bool myBool {set; get;}` I doing the following:               public static bool myBool     {        get        {            return myBool;           }        set        {            myBool = valuePassedIn;        }     }      I feel like the first method is the best approach, but I have no idea why I think this. Is there a best from these choices? Am I doing something horribly wrong, or all three methods equivalent?


title: Is Haskell's type system an obstacle to understanding functional programming?

text: I'm studying Haskell for the purpose of understanding functional programming, with the expectation that I'll apply the insight that I gain in other languages (Groovy, Python, JavaScript mainly.) I choose Haskell because I had the impression that it is very purely functional, and wouldn't allow for any reliance on state. I did not choose to learn Haskell because I was interested in navigating an extremely rigid type system. My question is this: Is a strong type system a necessary by-product of an extremely pure functional language, or is this an unrelated design choice particular to Haskell? If it is the latter, I'm curious what would be the most purely functional language that is dynamically typed. I'm not particularly opposed to strong typing, it has its place, but I'm having a hard time seeing how it benefits me in this educational endeavor.


title: Data structure for grid with negative indeces

text: Sorry if this is an insultingly obvious concept, but it's something I haven't done before and I've been unable to find any material discussing the best way to approach it. I'm wondering what's the best data structure for holding a 2D grid of unknown size. The grid has integer coordinates (x,y), and will have negative indices in both directions. So, what is the best way to hold this grid? I'm programming in c# currently, so I can't have negative array indices. My initial thought was to have class with 4 separate arrays for (+x,+y),(+x,-y),(-x,+y), and (-x,-y). This seems to be a valid way to implement the grid, but it does seem like I'm over- engineering the solution, and array resizing will be a headache. Another idea was to keep track of the center-point of the array and set that as the topological (0,0), however I would have the issue of having to do a shift to every element of the grid when repeatedly adding to the top-left of the grid, which would be similar to grid resizing though in all likelihood more frequent. Thoughts?


title: API Caching Layer

text: **Primer:** We have a mobile app being served by an API (written in PHP). The main point of the app is to display products from a large items table in the database, in a multitude of different configurations. Categories, suggested items, user compiled feeds, "similar to" feeds. Basically most, if not all of the display data comes from a single table, however the filtering and sorting is really what the app does. Some feeds are fairly simple such as "get all items that are in one of these categories using an items to category link table". Others are more complex using fulltext search to filter, along with category filters and stock filters and sometimes we may even require that the results have an additional filter such as "exclude items from any category that doesn't have 10 matching items in that category" (sort of like a self regulating, category filter invalidation). * * * We are now in the process of trying to speed up the API and looking to start putting the tech in, to allow us to scale. We've already decided on certain things like seperated search engines (i.e. elasticsearch for fulltext replacement e.c.t.). However one thing which i'm a little "new" in, is caching the API feeds. My only caching experience has been either caching full webpage outputs in things like magento/wordpress. Or caching complex objects that are built from several queries and processes. I've decided, object caching probably isn't suitable here, as most of the final object data comes from a single table. So object caching would not provide much speed improvement. I'm currently figuring i need to cache the final output collection of objects, as its really the complex filtering and sorting which slows everything down. But that's where i get stuck... First of all, should we cache the entire collection of objects, or just store a collection of the object id's, and still go to the database to do the final data lookup (my theory being, that with all the different compilation of feeds, the memory usage would grow quite quickly caching all the objects themselves). Secondly, do we cache the very final output of the feed, or do we try and find a common point at which we can create a cached copy of the feed that isnt quite right. So for example, rather than caching "similar products to X where the similar products are in 1,2,3 categories", we would instead cache "similar products to X", then on each request, get the collection from cache, and do the additional filtering manually after retrieving the "base collection". Hopefully that all makes some sort of sense,a nd apologies if its a little rambly. I'm a little out of my depth with this one, but im keen to learn. No doubt whatever solution i decide to implement first, will need many, many iterations before we deem it "correct". But at the moment, i just don't have any experience in this, to give myself a suitable, appropriate starting point, to start development.


title: xml based programming languages

text: I was looking at wikipedia - Category:XML-based programming languages. Why would someone take this approach for designing a language?   What are the advantages of it? I can only think of disadvantages.   * hard to maintain   * hard to read   * hard to write


title: .NET MVC project architecture / layering

text: When planning the architecture for a mid-large scale MVC web application how do you implement the layers to be as decoupled as possible and easy to test? (basically follow best practices) Let's say I'm using code first as my data access. I struggle with what to define "business logic" as, and how it is meant to interact with the data layer. Taking a vehicle sales application as an example, would business logic be classes that performed tasks such as calculating the tax band for given vehicles, comparing mile per gallon statistics etc? As for the business entities (e.g. Cars, Vans, Motorcycles) I would put these in the data layer along with my datacontext class. Also what would constitute application logic as opposed to business - I'm guessing things like session / user input validations? So for example, a car controller might return an action/view result that lists the top ten cars filtered by type and best mpg. So let's say I have an ICarRepository 'carRepo' injected into my controller(using the repository pattern / DI), I filter my cars from an action method parameter e.g. var cars = carRepo.getCarsByType("hatchback"); So I've kept the data access knowledge out of my controller using a repository, now to keep the business logic out of the controller using a domain model - var result = new MpgCalculator(cars); - Let's say I need the calculator class because it needs to perform additional logic to calculate the best fuel efficiency, more than just loading / filtering entities from the DB. So now I have a data set for my view to render that used a repository to retrieve from the data access layer, and domain specific object to process and perform business related tasks on that data. Am I making mistakes here? do we still need to use the repository pattern or can I just code against an interface to decouple the ORM and test? On this topic, as my concrete data access classe(s) dbcontext are in the data layer, should the interface definitions go into the domain/business layer meaning that if the data access technology is ever changed, my other layers aren't effected? From what I have studied thus far my structure looks like this: MVC Internet Application - The standard internet project - models in here are ViewModels Domain/Business layer - business specific classes/models that controllers can use to process domain entities from the data layer before passing on to the relevant views Repository abstraction necessary? - I hear lots of debate on this, especially when using an ORM Data layer - Entity classes (Car, Van, Motorcycle), DbContext - Concrete data access technology layer Apologies if my examples do not make sense, I'm trying to learn the best patterns without making applications unnecessarily complicated!


title: Clean way to use mutable implementation of Immutable interfaces for encapsulation

text: My code is working on some compost relationship which creates a tree structure, class A has many children of type B, which has many children of type C etc. The lowest level class, call it bar, also points to a connected bar class. This effectively makes nearly every object in my domain inter- connected. Immutable objects would be problematic due to the expense of rebuilding almost all of my domain to make a single change to one class. I chose to go with an interface approach. Every object has an Immutable interface which only publishes the getter methods. I have controller objects which constructs the domain objects and thus has reference to the full objects, thus capable of calling the setter methods; but only ever publishes the immutable interface. Any change requested will go through the controller. So something like this:               public interface ImmutableFoo{              public Bar getBar();         public Location getLocation();     }          public class Foo implements ImmutableFoo{              private Bar bar;         private Location location;              @Override         public Bar getBar(){             return Bar;         }              public void setBar(Bar bar){             this.bar=bar;         }              @Override         public Location getLocation(){             return Location;         }      }           public class Controller{          Private Map<Location, Foo> fooMap;               public ImmutableFoo addBar(Bar bar){              Foo foo=fooMap.get(bar.getLocation());                   if(foo!=null)                  foo.addBar(bar);                   return foo;          }     }      I felt the basic approach seems sensible, however, when I speak to others they always seem to have trouble envisioning what I'm describing, which leaves me concerned that I may have a larger design issue then I'm aware of. Is it problematic to have domain objects so tightly coupled, or to use the quasi- mutable approach to modifying them? Assuming that the design approach itself isn't inherently flawed the particular discussion which left me wondering about my approach had to do with the presence of business logic in the domain objects. Currently I have my setter methods in the mutable objects do error checking and all other logic required to verify and make a change to the object. It was suggested that this should be pulled out into a service class, which applies all the business logic, to simplify my domain objects. I understand the advantage in mocking/testing and general separation of logic into two classes. However, with a service method/object It seems I loose some of the advantage of polymorphism, I can't override a base class to add in new error checking or business logic. It seems, if my polymorphic classes were complicated enough, I would end up with a service method that has to check a dozen flags to decide what error checking and business logic applies. So, for example, if I wanted to have a childFoo which also had a size field which should be compared to bar before adding par my current approach would look something like this.                public class Foo implements ImmutableFoo{               public void addBar(Bar bar){              if(!getLocation().equals(bar.getLocation())                 throw new LocationException();                   this.bar=bar;          }      }           public interface ImmutableChildFoo extends ImmutableFoo{          public int getSize();      }           public ChildFoo extends Foo implements ImmutableChildFoo{                private int size;                @Override           public int getSize(){               return size;           }                @Override           public void addBar(Bar bar){               if(getSize()<bar.getSize()){                   throw new LocationException();                    super.addBar(bar);           }      My colleague was suggesting instead having a service object that looks something like this (over simplified, the 'service' object would likely be more complex).                public interface ImmutableFoo{          ///original interface, presumably used in other methods          public Location getLocation();          public boolean isChildFoo();      }      public interface ImmutableSizedFoo implements ImmutableFoo{          public int getSize();      }          public class Foo implements ImmutableSizedFoo{          public Bar bar;               @Override          public void addBar(Bar bar){              this.bar=bar;          }               @Override          public int getSize(){              //default size if no size is known              return 0;          }                @Override           public boolean isChildFoo              return false;           }      }           public ChildFoo extends Foo{                private int size;                @Override           public int getSize(){               return size;           }                @Override           public boolean isChildFoo();              return true;           }      }           public class Controller{          Private Map<Location, Foo> fooMap;               public ImmutableSizedFoo addBar(Bar bar){              Foo foo=fooMap.get(bar.getLocation());              service.addBarToFoo(foo, bar);                   returned foo;          }               public class Service{                   public static void addBarToFoo(Foo foo, Bar bar){                      if(foo==null)                    return;                 if(!foo.getLocation().equals(bar.getLocation()))                     throw new LocationException();                 if(foo.isChildFoo() && foo.getSize()<bar.getSize())                     throw new LocationException();                      foo.setBar(bar);              }        }     }      Is the recommended approach of using services and inversion of control inherently superior, or superior in certain cases, to overriding methods directly? If so is there a good way to go with the service approach while not loosing the power of polymorphism to override some of the behavior?


title: Want to use a lib for my project, confused with license (AGPL vs MIT License)

text: Im working on a Java Software and there is a need to use some extern libraries. I found two relevant libs. The one is on an AGPL and the other on the MIT License. Now Im asking my self, can I use these libs if:   * I would make a non-opensource-nonfree-software or   * I would make a non-opensource-free-software I dont really understand the whole license stuff, could somebody tell me which one of the libs for what kind of software would be better? Thank you


title: Events where junior-level developer/CS student can prove himself?

text: I spotted a "Google Summer of Code" announcement recently, and though eager to join, I see my chances are plainly poor. I'm short on time to shape my ideas and study the source code. I just wonder - Are there any similar events that provide an opportunity for students to develop real working projects? Especially ones that are worth mentioning in one's CV?


title: Introducing Programming To a Mathematician

text: I currently am a programmer, I'm almost 16 years of age and have pretty much narrowed my careers down to something involving a Computer Science degree or Electrical Engineering degree (I know they are quite different but this question is about my friend) but my friend isn't so sure. He is very interested in maths and is very good at it and I think he would enjoy programming but he isn't willing to try it ( **edit** he _is_ willing to try but has never done before). Can anyone give me an suggestions for a language or tool that he could dabble in programming (at a reasonably basic level I assume) to solve maths problems or involve some kind of maths. As I say he enjoys maths a lot but I think he would enjoy programming, the problem is I don't want him to be put off by the stuff that isn't relevant at introductory levels such as memory allocation et al. I know that is very important but the point is that I want him to learn a bit of programming with maths then hopefully if he is interested enough he can start learning programming as programming. **Edit:** Its not that he's completely uninterested - more that he hasn't actively explored the area before, maybe because he isn't informed about it. I wouldn't want to force him to do something he doesn't want to, I see this as more of a little push so that he can learn about programming. If he doesn't like it - fair enough, I can't control that and don't want to but if he turns out to enjoy it - this push will have been the right thing.


title: How do I handle 3rd party search result data (via cache)

text: I have a search function on my site and it is taking data from 6 different 3rd party resources. The problem is, it takes too long requesting the data over and over again on the results page. I've read for questions like this on SO about session not being a good choice but for me **'memcache'** is not an option, because the server doesn't have memcached installed and I have no way to install it now. Is there any other approach to do this? Storing in the database seem inappropriate because the data depends on the search terms requested. What I've been thinking is writing a file on the server that would act as a cache for this file but I don't know how I would know when to delete it after.


title: Servicing background tasks on a large site

text: We're dealing with an interesting problem on StackOverflow. We've got a whole bunch of little "needs to be done soon-ish" tasks. An example is updating "Related Questions" lists. What we've done in the past is to piggy-back those tasks onto some users' page loads. This was never ideal, but it wasn't really noticeable. Now that SO has passed the 1,000,000 question mark, those unlucky users are starting to feel it. The natural solution is to actually push these tasks into the background. There are two broad ways of doing this I'm considering. ### 1. In IIS as a custom Thread-Pool/Work-Queue Basically, we spin up a few (non-ThreadPool, so as to not interfere with IIS) threads and have them services some collections we're shoving Funcs into. The big pro here is simplicity. We don't have to worry about marshaling anything, nor do we have to make sure some external service is up and responding. We also get access to all of our common code. The con is, well, that we shouldn't use background threads. The objections I know of are all centered around starving IIS (if you use ThreadPool) and the threads dieing randomly (due to AppPool recycling). We've got existing infrastructure to make the random thread death a non-issue (its possible to detect a task has been abandoned, basically), and limiting the number of threads (and using non-ThreadPool threads) isn't difficult either. ~~Am I missing any other objections to in IIS process thread-pooling/work- queues?~~ Moved to StackOverflow, as it wasn't really addressed here. ### 2. As a Service Either some third-party solution, or a custom one. Basically, we'd marshal a task across the process boundary to some service and just forget about it. Presumably we're linking some code in, or restricted to raw SQL + a connection string. The pro is that its the "right way" to do this. The cons are that we're either very restricted in what we can do, or we're going to have to work out some system for keeping this service in sync with our code base. We'll also need to hook all of our monitoring and error logging up somehow, which we get for free with the "In IIS" option. **Are there any other benefits or problems with the service approach?** In a nutshell, are there unforseen and insurmountable problems that make approach #1 unworkable and if so are there any good third-party services we should look into for approach #2?


title: Is linq more efficient than it appears on the surface?

text: If I write something like this:               var things = mythings         .Where(x => x.IsSomeValue)         .Where(y => y.IsSomeOtherValue)      Is this the same as:               var results1 = new List<Thing>();     foreach(var t in mythings)         if(t.IsSomeValue)             results1.Add(t);          var results2 = new List<Thing>();     foreach(var t in results1)         if(t.IsSomeOtherValue)             results2.Add(t);      Or is there some magic under the covers that works more like this:               var results = new List<Thing>();     foreach(var t in mythings)         if(t.IsSomeValue && t.IsSomeOtherValue)             results.Add(t);      Or is it something completely different altogether?


title: How to get different resources in a single endpoint in RESTful?

text: I have a REST webservice that have a couple of resources, like Company and User. But now I need to make a modification to the API to return a special list combining company, user and maybe other type of resource. Like a list of recommendations with various type of resources. Which is the best approach to solve this? I need to make a new endpoint (resource), something like: `/recommendations`? I already have the `/company` endpoint, and the `/user` endpoint returning the corresponding objects. This is fine. But now I need some way to return an array with a combination of users and companies. Also I'm thinking that the json will look like an array of objects, but how the client can know which type of object is parsing if every object in the array is a different resource? **EDIT** I want that my client could show a recomendations screen in the app. The problem is that this list can combine multiple types of data (users, companies). It doesn't matter if this resources have a relationship or not. The client shoud recive a json like that:               "recomendations": [         {             "id_user": 1             "name": "Jean"             ...         },         {             "id_company": 2             "name": "Starbucks"             ...         },         ...     ]


title: Messaging technologies between applications ?

text: Recently, I had to create a program to send messages between two winforms executable. I used a tool with simple built-in functionalities to prevent having to figure out all the ins and outs of this vast quantity of protocols that exist. But now, I'm ready to learn more about the internals difference between each of theses protocols. I googled a couple of them but it would be greatly appreciate to have a good reference book that gives me a clean idea of how each protocol works and what are the pros and cons in a couple of context. Here is a list of nice protocols that I found:   * Shared memory    * TCP    * List item   * Named Pipe    * File Mapping    * Mailslots    * MSMQ (Microsoft Queue Solution)    * WCF I know that all of these protocols are not specific to a language, it would be nice if example could be in .net. Thank you very much.


title: What can go wrong if the Liskov substitution principle is violated?

text: I was following this highly voted question on possible violation of Liskov Substitution principle. I know what the Liskov Substitution principle is, but what is still not clear in my mind is what might go wrong if I as a developer do not think about the principle while writing object-oriented code.


title: Career Confusion

text: For someone who has not worked anywhere in Java Technology except learning just the core concepts in his Masters (MCA) and Graduation (BCA, bachelor degree course):   1. Is it possible to get job anywhere in Java technology? Considering he/she has not studied it in regular college and not First Class throughout except BCA, MCA (in case of Indian or international companies).   2. How will he/she get his/her dream job (in the Java field) and what are the prospects for his/her career life?   3. If the knowledge he received in his grad/univ is not enough, than what more should he do to make this his specialty before getting started for the search job or to increase job offers? All kinds of suggestions are welcome. And thanks very much for kind suggestions.


title: Blaming the ills of today on the technical debt of yesterday

text: A surprising number of quality, scalability, and load problems have been occurring on an application I currently support that I did not originally write. Thankfully I have new projects that I have been doing from the ground up to retain some semblance of my sanity. The original team consisted of 20 some developers (most of them with outdated skill sets), no business requirement documents or quality assurance testers, and poorly managed from the very beginning in a waterfall fashion. The early days of production were an embarrassing nightmare that involved patching brittle procedural-like code with even more brittle fixes. Features were added later that were sledgehammered into a datamodel that was never meant to support them and it is not uncommon to see the same code duplicated 10 times over and to see resources not being safely closed and ORM queries that fetch tens of thousands of entities just to throw out all but a handful. It is just me now and everytime there is a new problem that crops out I rewrite a module to better standards and make it MUCH more stable but Management needs a proper explanation as to why all of this is occurring. They seem shocked and perplexed at the notion that this application is of poor quality and drowning in technical debt. Fortunately they understand the concept of technical debt and support me in my quest to eradicate it and they are very supportive and appreciative of me, but I feel as if I just keep **blaming** the original team (who all left to ruin another project in a different division). The bottom line is that I don't want to be _"That Guy"_ who always complains about the developers on the project before him. I have seen this attitude before from people in my career who I personally felt were being ignorant and not considering the circumstances and design influences that encouraged things to be the way that they were. Usually I see this attitude of blaming the previous team for poor design and implementation from idealistic junior developers who have not had the life experiences that more senior members have had and benefitted from. Do you feel that there is a better way, perhaps softer way of doing of reporting these kinds of problems to management without stepping on the reputation of the person/team before you?


title: Recommended secure approach to confirming an URL is called by a legitimate caller

text: I'm using a CRON on AppEngine and the cron calls my web app at a specific app. I only want to execute functionality when called by my AppEngine app. What's is/are recommended approach to confirming that the caller is legitimate? I don't wish to rely on no one else knowing the specific URL.


title: Purpose of ending tags in SGML/HTML/XML?

text: There are those tags which have immediate effect (< br >) and those which affect what is between them ( < a > < / a > ). Closing tag is **verbose** , and I believe also **redundant** :               <tag parameters> ... </tag>      ## verbose Compare to LISP's s-expresions.               (tag parameters)      ## redundant Ending tags are not even necessary. These language are context-free and this is not possible there:               <tag1> <tag2> </tag1> </tag2>      Basically these should be equivalent:               <tag1> <tag2> </> </>     <tag1> <tag2> </tag2> </tag1>             ## questions Are ending tags there to aid readability? What is purpose of redundancy in closing tags? I want to understand inside the logic behind desing of this. Thanks. :)


title: Is it a security flaw to log the class and method name when an exception occurs?

text: I have the following :               public class doCheck(){              public void performCheck(){             try {                 perform all checks......             }             catch(Exception e){                 logger.error("Exception occured in class doCheck in method performCheck");                 thrown new MyNewException(e.getMessage());             }         }     }      Is it safe to log the class and method name?


title: Are there coding tests to recruit a QA engineer?

text: I'm a software engineer in a small company and we are currently recruiting our first QA engineer. The guy will have to write as many as possible automated tests on our web-based tools suite. As I've participated in the recruitment of almost all the developers of our engineering team, the QA manager has asked me to interview the candidates. Most of them sound really smart. When they explain their past experiences, they give the feeling that they know what they were talking about, even when they give a lot of details on the framework or tools they are familiar with (like selenium or ohter stuff). However at the end of the interview I like to challenge them with a small coding test. I know we aren't recruiting a developer but as he'll have to _code_ tests, I believe that he has to be a bit skilled in that domain. I systematically ask the same question: "In the language of your choice, could you write a the body of the function that takes in input a integer and return its string representation.   For instance in C#, the prototype of the method could be something like `public string itoa(int n)`" And unfortunately, until now, 100% of the candidates have failed... So, is it because the question is somehow out of scope for a QA engineer? and in this case could you propose a better exercise?   Or is it just unacceptable and we still have to look for someone that would be at least able to pass the test? Thank you for you answers.


title: Is object oriented really good for kids?

text: I read, that Smalltalk was designed for kids or for education. So was it good at it? Better than the other languages? Was it good/easy also for average kid (I read that bright kids enjoyed). Is there any study to back it up? Or is Your experience it is good?


title: What advantages does Linux give me when developing in PHP for the web?

text: I'm about to begin a big PHP project with a friend. It's my first time using PHP and I've been wondering wether I should try developing on Linux since it's so popular.   I've had some past experience with Linux and the choice of an editor won't be hard since I know vim (though I've looked at VS.PHP and it's putting me back from the change).   Does using Linux when developing PHP (or any web language) give me an advantage?


title: Is functional programming strongly related to mathematics?

text: Is functional programming so related to mathematics because much of the functional programming is depicted with mathematical notions? Is it a MUST to have a strong base of maths to learn & understand functional programming for a programmer with a imperative background?


title: Do Fortran compilers really generate faster code than C compilers?

text: When I was studying in the university I often heard the idea that Fortran compilers produced faster code than C compilers for an equivalent program. The key reasoning went like this: _a Fortran compiler emits on average 1,1 processor instruction per line of code, while a C compiler emits on average 1,6 processor instruction per line of code_ - I don't remember the exact numbers but the idea was that C compilers emitted noticeably more machine code and therefore produced slower programs. How valid is such comparison? Can we say that Fortran compilers produce faster programs than C compilers or vice versa and why does this difference exist?


title: Where do you use ROT13?

text: I was reading through the docs for vim, and noticed there's a shortcut, for example `g?w` would transform the next word using ROT13. I also know that you can change the encoding of a Python file to ROT13. Here's my question: Why? It seems like it wouldn't be that useful, aside from prank programs like Django FUNserver.


title: If the model is validating the data, shouldn't it throw exceptions on bad input?

text: Reading this SO question it seems that throwing exceptions for validating user input is frowned upon. But who should validate this data? In my applications, all validations are done in the business layer, because only the class itself really knows which values are valid for each one of its properties. If I were to copy the rules for validating a property to the controller, it is possible that the validation rules change and now there are two places where the modification should be made. Is my premise that validation should be done on the business layer wrong? # What I do So my code usually ends up like this:               <?php     class Person     {       private $name;       private $age;            public function setName($n) {         $n = trim($n);         if (mb_strlen($n) == 0) {           throw new ValidationException("Name cannot be empty");         }         $this->name = $n;       }            public function setAge($a) {         if (!is_int($a)) {           if (!ctype_digit(trim($a))) {             throw new ValidationException("Age $a is not valid");           }           $a = (int)$a;         }         if ($a < 0 || $a > 150) {           throw new ValidationException("Age $a is out of bounds");         }         $this->age = $a;       }            // other getters, setters and methods     }      In the controller, I just pass the input data to the model, and catch thrown exceptions to show the error(s) to the user:               <?php     $person = new Person();     $errors = array();          // global try for all exceptions other than ValidationException     try {            // validation and process (if everything ok)       try {         $person->setAge($_POST['age']);       } catch (ValidationException $e) {         $errors['age'] = $e->getMessage();       }            try {         $person->setName($_POST['name']);       } catch (ValidationException $e) {         $errors['name'] = $e->getMessage();       }            ...     } catch (Exception $e) {       // log the error, send 500 internal server error to the client       // and finish the request     }          if (count($errors) == 0) {       // process     } else {       showErrorsToUser($errors);     }      Is this a bad methodology? # Alternate method Should maybe I create methods for `isValidAge($a)` that return true/false and then call them from the controller?               <?php     class Person     {       private $name;       private $age;            public function setName($n) {         $n = trim($n);         if ($this->isValidName($n)) {           $this->name = $n;         } else {           throw new Exception("Invalid name");         }       }            public function setAge($a) {         if ($this->isValidAge($a)) {           $this->age = $a;         } else {           throw new Exception("Invalid age");         }       }            public function isValidName($n) {         $n = trim($n);         if (mb_strlen($n) == 0) {           return false;         }         return true;       }            public function isValidAge($a) {         if (!is_int($a)) {           if (!ctype_digit(trim($a))) {             return false;           }           $a = (int)$a;         }         if ($a < 0 || $a > 150) {           return false;         }         return true;       }            // other getters, setters and methods     }      And the controller will be basically the same, just instead of try/catch there are now if/else:               <?php     $person = new Person();     $errors = array();     if ($person->isValidAge($age)) {       $person->setAge($age);     } catch (Exception $e) {       $errors['age'] = "Invalid age";     }          if ($person->isValidName($name)) {       $person->setName($name);     } catch (Exception $e) {       $errors['name'] = "Invalid name";     }          ...          if (count($errors) == 0) {       // process     } else {       showErrorsToUser($errors);     }      # So, what should I do? I'm pretty happy with my original method, and my colleagues to whom I have showed it in general have liked it. Despite this, should I change to the alternate method? Or am I doing this terribly wrong and I should look for another way?


title: voting system to select next set of product features

text: My product just deployed 2.0. Now there are many thing to plan for next sprint. From the list of 5-10 items, we need to ask everyone of our staff to order these 10 items based on importance. It all should be single vote and anonymous. Is there any site giving this service? It could be made in an hour but it wont appear anonymous to the staff, no matter what I say. (Sorry, if its the wrong place to ask. I could not find other.)


title: Creating a site just for URL redirecting (.NET MVC) due to changing domains and URLs

text: I'd just like to hear about any experience creating a (simple) site for redirecting requests. Basically we have multiple domains, but as we add more domains and change URLs, there is a huge problem of maintaining old links. When discussing this we are considering using one constant site to determine where the present url is located. The idea would be pretty simple, just e.g. `links.url.com` and then a parameter to find a database row which would contain e.g. domain, parameters, and any other necessary fields to redirect successfully. for example: `links.url.com/id=12345` would read the new domain e.g. `url2.com` and the `parameters id=324324324&id2=34234` so the controller would just redirect to `url2.com/id=324324324&id2=34234`. Is this a good way to handle changing URLs as the domains and URLs change? Are there downfalls to this approach, or better ways to go about URL change?


title: What is pattern based programming?

text: Can somebody explain the obsession with patterns and anti-patterns in programming? I ask because I have absolutely no idea what any of the patterns mean. When faced with a programming task I think about the problem for a little bit, write down some data structures that I think will be relevant, prototype a solution, separate out some modules and iterate. Nowhere in the process do I think "Oh, I need FunkyLookyTastic pattern here".


title: Java vs. C# - Productivity perspective

text: If you have a number of years experience in working with Java and a number of years experience in working with C# and .NET, I would value your opinion on software development productivity differences between these two environments. One of our customers is considering replacing their existing software solution. As the replacement will require approx. 10 - 15 man years work, a choice for Java or .NET, based on productivity differences between the them, may significantly influence the investment required and time-to-market. Would you be able to provide us, an indication of software development productivity differences between Java and C#/.NET? I would prefer to receive an answer as follows: > My experience is based on X years experience working with Java and X years > experience working with C#/.NET. Java is X% more productive then C#.NET or > C#/.NET is X% more productive than Java if you take the the following into > account.


title: Hiring at start-ups vs established companies

text: I have always wondered about this and perhaps experienced folks here can comment on this. I always read that big established software companies such as Google, Microsoft, etc are always wary of hiring software engineers/(or other related professionals) who don't exactly meet the job requirements, and would rather turn down a close "Yes/Maybe" decision. There's also the general perception that start-ups are generally more willing to hire such "less-than-perfect" employees. But to me this sounds counter- intuitive: start-ups are generally much smaller and resource constrained so they would actually need a "10/10" hire while established companies with bigger teams and more resources would be willing to take a (small) risk on a hire. Anyone have any comments on this from first-hand experience? Thanks,


title: How to verify the code that could take a substantial time to compile?

text: As a follow up to my prev question: What is the best aproach for coding in a slow compilation environment To recap: I am stuck with a large software system with which a TDD ideology of "test often" does not work. And to make it even worse the features like pre- compiled headers/multi-threaded compilation/incremental linking, etc is not available to me - hence I think that the best way out would be to add the extensive logging into the system and to start "coding in large chunks", which I understand as code for a two-three hours first (as opposed to 15-20 mins in TDD) - thoroughly eyeball the code for a 15 minutes and only after all that do the compilation and run the tests. As I have been doing TDD for a quite a while, my code eyeballing / code verification skills got rusty (you don't really need this that much if you can quickly verify what you've done in 5 seconds by running a test or two) - so I am after a recommendations on how to learn these source code verification/error spotting skills again. I know I was able to do that easily some 5-10 years ago when I din't have much support from the compiler/unit testing tools I had until recently, thus there should be a way to get back to the basics.


title: How important are daily builds?

text: One of the criteria of the Joel Test is daily builds. The idea is that if the build is broken, whoever broke it is around to fix it up. If the build cannot be fixed, everyone will have to check out an old version and work on that. I can understand how this can be pretty bad on centralised version control where it is important to avoid merging and branching as much as possible, but this only sounds like a minor nuisance for distributed version control. Do you agree with this? Are there other reasons why daily builds are important?


title: Is Objective-C an Interpreted or Compiled language?

text: I want to know if Objective-C is an interpreted or a compiled language.


title: Moving from C# to C++, and tips?

text: I've been using `C#` for a while now, and for the sake of furthering my career and extending my knowledge of programming, I want to get into `C++`. `C#` is very useful, and fast to work with, but since my team and I will be making large scale projects I need to consider working at a lower level language for several reasons. Most commercial companies use `C/C++` due high performance and portability. Of course, `C#` isn't necessarily bad compared to `C` or `C++`, but I just prefer to have a different tool for each job. So I read C++ is harder because it is a low level language, machine code, and doesn't have memory management. But the fact that it is machine code also reduces the amount of memory consumed. The language is hard to work with, but in a way difficulty makes it a powerful language. It was made to be fast and efficient, machine code, but this makes it harder to understand and learn "since it is closer the the machine". * * * I've made up my mind, and I want to learn `C++`, so what are some tips to keep in mind while learning? It's best to avoid getting into bad habits rather than to try and break them later, safe than sorry. I plan to use the resources stated here, but I would prefer any personal recommendations, books or online guides, possibly those that can be easily understood by someone who has fair knowledge of `C#`.


title: what is a phone interview?

text: So..I am going to have a phone interview with a company tomorrow. I never had a phone interview before so I don't know anything about it except that I am going to talk to someone over the phone. This is a PHP developer position. Is she/he going to ask PHP questions only? or is she/he going to ask any other questions? Please advise me!


title: What do I need to know to develop a paperless application using .NET?

text: I want to develop a paperless application in .NET to reduce paper usage at my university. It will contain Exchange data and reporting. What do I need to study before I start?


title: Possible hack aftermath

text: After being hacked companies often give numbers and details on how much of their data was compromised e.g "13K user and passwords". After a possible intrusion how do you know what the hacker did in your server?


title: Which one is better offline method for large scale application

text: We've a big data management website used by several property. Some of our customers have downtime (they can't access net for an hour or two). We want our site to support offline data viewing and inventory management (typical data search and add/remove) and when the user goes online we can sync the changes back to our central database. Customers use several platforms like Windows, iOS, etc. We've been looking into several different options, here are the major choices - Develop offline web app supported in HTML5. Develop a 'fallback' mechanism and interact with data from the app cache as explained in here (http://www.htmlgoodies.com/html5/tutorials/introduction-to-offline-web- applications-using-) Develop a desktop based cross platform solution. I remember the old MONO which has been popular. Here's a post (What do you suggest for cross platform apps, including web cross-platform-apps-including-web) and another one (Technology choice for cross platform development (desktop and phone)? platform- development-desktop-and-phone?rq=1) I realize the the desktop solution might be hard to maintain and result in some compatibility issues and demand test environments. Can HTML5 handle moderate to high level complexity and data flow? Or would it be better to rely on a desktop based app for better scalability & performance?


title: Is automatically checking code quality via metrics possible?

text: For several years now I am a big fan of using static code analysis tools for checking the source code quality. We are mostly doing C# development so NDepend was the best way to go for me. Most of the time I manually perform the analysis, for example once every two weeks. Lately I have had a discussion with a college whether we should include NDepend in our continuous integration process so that the build automatically turns red if for example a method has a too high complexity. My opinion hereby is that it's not possible to define metrics that are valid for the whole code. I think that you would either get way to many "false complaints" - code that generally is ok but does not match the metrics. The following code for example has a very high complexity, even if I think that sometimes you can't prevent it.               if (remoteResult == RemoteResult.Dummy1 || remoteResult == RemoteResult.Dummy2 ||          remoteResult == RemoteResult.Dummy3 || remoteResult == RemoteResult.Dummy4 || ...      Of course it would also work to increase the thresholds of the metrics, but in this case I would loose valuable information. Another example for example is the maximum number of members for a class. I would like to keep this lower than 10 for classes with lots of logic. But on the other hand there are many "domain models" with more than 10 properties. I wouldn't like to extract another class just because of the metric - as this would lower the readability and does not improve it which should be the goal of code quality metrics. Do you think automatically checking code quality via metrics is possible? If yes, for all or only for specific metrics? (A list of common NDepend metrics can be found at http://www.ndepend.com/Metrics.aspx )


title: syncing code with repo/backup

text: I am doing a small software project on my local PC. I'm the only person working on this. I'd like to back this up to the cloud every day so that if anything happens to my HDD I have a various copies going back in time. I have a box account although that seems to want to sync continuously and with constant file changes with code I don't really want this. Can anyone recommend any site or software that will allow me to back up to an external location online? I'm happy to manually kick off this process at the end of each day.


title: Why do binary files load quicker than alphanumeric text files?

text: I've noticed that when I load/store large data files in a binary format, the program runs much faster than if I load data from an ASCII encoded file. Why is this the case? The data in my case is plain, with limited parsing involved other than `read()` or `fscanf()`.


title: How to understand the beauty of UNIX?

text: Some of my friends say that UNIX is beautiful and simple. But I really don't know what they mean. Why are they saying so? For me, UNIX is just a boring command prompt with different shells. How can I experience the beauty of UNIX? Can you share any experience?


title: Pythonesque global variable assignment

text: I'm designing a language with Pythonesque syntax, including casual creation of variables by assignment. I'm wondering at the moment exactly how to deal with assignment to global variables (and object/class variables, since I'm implementing classes as scopes). In Python itself, by default the attempt will create a local variable instead:               x = 1     def f():         x = 2 # creates a local variable      but you can override this with a `global` declaration:               x = 1     def f():         global x         x = 2 # updates the global variable      I'm going to implement a prefix `.` for referring to variables in outer scopes (somewhat akin to prefix `::` in C++, but will probably jump one scope instead of all), so that could be written as:               x = 1     def f():         .x = 2 # updates the global variable      Would it be better to have just that one way of doing things, or would it be clearer or more convenient to have the mechanism of declaring variables as global the way Python does it?


title: Working with a remote developer

text: My company is going to hire an external developer to write some simple PHP modules and some minor bugfixing in our software. We have never hired an external developer by the hour before. How can we measure external developer's productivity and coordinate with them? I thought about using a combination of http://worksnaps.net/ and https://github.com/. Any better ideas?


title: Steps after SQL Injection detected

text: I've come across SQL injection vulnerabilities on my companies ecommerce page. It was fairly poorly put together. I believe I have prevented future attempts however we are getting calls about fraudulent credit card charges on our site and others. This leads me to believe that someone was able to get a list of our credit card numbers. What doesn't make sense is that we don't store that information and we use Authorize.net for the transaction. If someone was able to get the CC#s, what should I do next? Inform ALL of our customers that someone broken into our system and stole their information? I have a feeling that will be bad for business.


title: How do you find local fellow programmers?

text: I'm a self-tought programmer living in a small town. Except for the occasional meetups at the other end of the country, I rarely talk face-to-face with other programmers. I'm well aware of the merits of pair programming, feedback, discussion with other programmers and all... What do you do to get in contact with other local programmers? p.s. If you live near Loenen (gld), Netherlands, I'd like to have contact ;)


title: What is the most accurate/frequent report on browser usage on the Internet?

text: I'm determining which browsers a new site should support. I'm looking for a respected and accurate (as possible) report on the browser versions that are currently in use. This report should, at minimum cover the % of people who use what browsers, and versions of that browser. Is there a widely accepted source for this kind of report? If so, are they regularly released and available for free? Bonus points for other metrics such as breaking down by OS, Flash versions, JS versions, etc.


title: function works fine without return value in c++

text: I forgot to write `return 'a';` in function and `return 0;` in main function but its works fine in Code::Blocks.               #include <iostream>          using namespace std;          char show()     {          cout<<"this is show function"<<endl;     }          int main()     {         show();     }      i am using Code::Blocks 10.05 in Ubuntu 12.04. Why this happen and why does the same thing cause an error in TURBO C++?


title: Layout of mathematical views (iOS)

text: I am trying to figure out the right way to encapsulate graphical information about mathematical objects. It is not simple. For example, a matrix can include square brackets around its entries, or not. Some things carry down to sub-objects -- for example, a matrix might track the font size to be used by its entries. Similarly, the font color and the background color would carry down to the entries. Other things do not carry down. For example, the entries of the matrix do not need to know whether or not the matrix has those square brackets. Based on all of the above, I need to calculate sizes for everything, then frames. All of this can depend on the properties stored above. The size of a matrix depends on the sizes of its entries, and also on whether or not it has those brackets. What I am having a hard time with is not the individual ways to calculate sensible frames for this or that. It is the overall organizational structure of the whole thing. How can I keep track of it all without going crazy. One particular obstacle is worth mentioning -- for reasons I don't want to go into here, I need to calculate the sizes and frames for everything before I instantiate any actual views. So, for example, if I have a Matrix object, I need to calculate its size before I make a MatrixView. If I have an equation, I need to calculate the size of the view for the equation before I create the actual view. So I clearly need separate objects for those calculations. But I can't figure out a sensible class structure for those objects. If I put them all into a single class, I get some advantages because copying then becomes easy. But I also end up with a bloated class that contains info that is irrelevant for some objects -- such as whether or not to include those brackets around the matrix. But if I use a lot of different classes, copying properties becomes a real pain. If it matters, this is all in Objective C, for an iOS environment. Any pointers would be greatly appreciated. EDIT: To clarify: I have model objects that contain mathematical information and can compute the text that will be displayed. I also _think_ it will make sense to have style sheet objects that will know the font size. Therefore, between the two, I can compute everything. This still leaves the issue of how to keep track of the resulting information. I don't want to call the "compute- your-size" methods more than necessary as they are expensive. So I have to cache some things. But where? And how do I manage that caching?


title: Backbone/JQuery, ExtJs 4.... is there something else worth looking?

text: Im currently evaluating a front-end architecture for a big app that will be developed by a team of about 6 developers + 1 web designer so that said, having a robust SVN friendly architecture is a must. So far I'm evaluating this two options:   * A mixture of JQuery/UI/Mobile + Backbone/Underscore + Require JS + Twitter-Bootstrap   * ExtJS 4 This are the requirements the architecture needs to meet:   * SVN Fiendly (or Friendly depending on you previous experiences)   * Active community and extensive documentation   * Extensible   * Easy to learn and to maintain (nice to have)   * Cross-browser support (most of the time at least)   * Support for Mobile devices   * Easy to maintain (MVC, MVVM)   * OpenSource (nice to have) The previously mentioned ones meet most of the requirements in different levels and so far they are the only ones I've found about, am I missing any others?


title: what programming languages and skills are necessary to learn hypervisor development?

text: I would like to know the skills and programming languages necessary to learn hypervisor development and any good resource to start learning?


title: Why are Javascript for/in loops so verbose?

text: I'm trying to understand the reasoning behind why the language designers would make the `for (.. in ..)` loops so verbose. For example:               for (var x in Drupal.settings.module.stuff) {         alert("Index: " + x + "\nValue: " + Drupal.settings.module.stuff[x]);     }      It makes trying to loop over anything semi-complex like the above a real pain as you either have to alias the value locally inside the loop yourself, or deal with long access calls. This is especially painful if you have two to three nested loops. I'm assuming there is a reason why they would do things this way, but I'm struggling with the reasoning.


title: What have you learned from the bugs you helped discover and fix?

text: I liked the core of this question, and wanted to re-ask it in a way that made it less about 'fun' and more about 'What do these past mistakes tell us about how we can write and test software better?' As an SDET, I'm always looking for anecdotes about new and interesting ways that programs can fail. I've learned a lot from these tales in the past, and would like to get that from the intelligent people in this community as well. I'd be interested in hearing what the issue was, how it was caught, if you think there was anything that could have reasonably done to catch it earlier or to avoid the same issue on later projects, and any other interesting lessons you took away from this bug. Please only write about bugs you _personally_ were involved with, ideally on a project you worked on (e.g., no "10 years before I was born, this happened and it was FUNNY!" answers). Please vote up answers that are thought-provoking or could change how you develop or test in some way, so this isn't just 'social fun'. Try to avoid voting up something just because it was funny. Edit: Please also focus on concrete examples of bugs or classes of bugs, not general discussion of what you've generally learned. They don't have to have been super-difficult or extremely weird, just something that made you go, "huh".


title: Office design and layout for agile development

text: (moved from stackoverflow) I have found lot of discussions here on about which keyboard, desk, light or colored background is best - but I can't find one addressing the layout of the whole office. We are a company with about 20 employees moving to a new place, something larger. There are two main development practices going on here with regular combination, the back end people often needing to work with the mobile people to arrange web services. There are about twice as many back end people as mobile people. About half of the back end developers are working on-site at any time and while they are almost never all in the office at once at least 5-10 spaces need to be provided - so most of the time the two groups are about equal. We have the chance to arrange desks, partitions and possibly even walls to make the space good. There won't be cash for dot-com frills like catering or massages but now's the time to be planning to avoid ending up with a bunch of desks in a long line. Joel on Software's Bionic Office is an article I've remembered from way back and it has some good ideas but I* (and more importantly the company's owners) are not completely sold on the privacy idea in an environment where we are supposed to be collaborating. This is another great link - The Ultimate Software Development Office Layout - I hadn't even remembered enclosed meeting rooms until reading this. Does the private office stand in the way of agile development? Is the scrum enough forced contact and if you need to bug someone you should need to get up and knock on their door? What design layouts can you point to and why would you recommend them? *I'm not against closed offices at all but would be happy if some other solution can do just as well. If it can't... well, that's what this question is all about. * * * Two updates - April 2013. The first move was to an office that was "funky". Basically open but with weird features like one wall carpeted, half the floor carpeted, half the floor polished concrete. Everyone seated on the concrete wanted to be on the carpet. It looked OK but in practise I would recommend not carpeting only half the office, the people who felt the cold really hated it. For standups it was fine - huge whiteboards occupied one wall, plenty of space to talk and break out. Then I moved to a very crowded place mixed in with another company (same owners) whose function was all about collaboration, design, phone calls, maintenance and installation of physical things. That sucked. Then we moved to new premises and someone decided warehouse/industrial was cool. Hard surfaces everywhere, glass and polished concrete. Developers sharing one big table in the middle of the highest traffic area right next to a kitchenette and dishwasher, not even in an alcove, just out there. Next to the people who spent all day on the phone. It sucked and continued to suck despite bandaids like noise absorbing panels. It sucked for agile because there was no space designed in for the board or for the standup and the acoustic characteristics of the place made hearing any one person above the clatter very difficult - as well as that feeling, during quiet moments, of shouting in a cathedral. Nobody ever listened to the complaints. I quit and so did a few others. Oh, it didn't help that the person who insisted on being "product owner" never bothered to show up.


title: Algorithm for compression of a dictionary (words and definitions)

text: The theoretical situation is this: Let's say that we have a digital dictionary (by which I mean a traditional list of words and definitions, not an associative array). For the sake of simplicity, let's also say that each word can be replaced by its exact definition, and still make sense in a sentence; for example, if this dictionary holds the definition of the word "ocean" to be "large body of salt water", then the following passage:               "We ourselves feel that what we are doing is just a drop in the ocean."       could be modified to:               "We ourselves feel that what we are doing is just a drop in the large body of salt water."      without any loss of logic or meaning. Now my question is this: given a dictionary with all of the words in the English language, what is an algorithm that could be applied to compress the dictionary, through the replacement of all the occurrences of a given word with its definition, and in doing so find a base set of words through which all of the meanings of the original language could be expressed? To clarify even more; if "sadness" is defined as "an unhappy emotion", then the word sadness can be completely removed from the dictionary by replacing all instances of the word "sadness" that occur in the definitions of other words with its definition. The definition of "depression", for example, might change from "a sustained period of sadness" to "a sustained period of an unhappy emotion". In this way, the algorithm would eventually arrive at a base set of words from which all other words could be represented. Are there any algorithms that exist that can do this, or something similar? How might this be done programmatically, without using brute force? Any insight is appreciated.


title: What license is best for this: Software is open source and free to use as long as you don't charge your customers

text: I'm releasing an open-source jQuery plug-in that is free to use, modify and redistribute as long as you don't directly or indirectly charge your customers. Your software doesn't need to be open-source, it just need to be free. If you charge your customers, you need a commercial license. I'm not sure about the licensing. http://www.turnjs.com/ is a plug-in that is similarly licensed and it is `Non-comercial BSD license`. But I can't find the definition for this license online. Can anyone help me determining the best license for me based on my description? Thanks.


title: MorphAdorner Licensing confusion

text: I want to use the MorphAdorner library available free for commercial use. But it uses several other libraries that restrict commercial use (like Gate etc). Can I use this library in my application?


title: Why does void in C mean not void?

text: In strongly-typed languages like Java and C#, `void` (or `Void`) as a return type for a method seem to mean: > This method doesn't return anything. Nothing. No return. You will not > receive anything from this method. What's really strange is that in C, `void` as a return type or even as a method parameter type means: > It could really be anything. You'd have to read the source code to find out. > Good luck. If it's a pointer, you should really know what you're doing. Consider the following examples in C:               void describe(void *thing)     {         Object *obj = thing;         printf("%s.\n", obj->description);     }          void *move(void *location, Direction direction)     {         void *next = NULL;              // logic!              return next;     }      Obviously, the second method returns a pointer, which by definition could be anything. Since C is older than Java and C#, why did these languages adopt `void` as meaning "nothing" while C used it as "nothing or anything (when a pointer)"?


title: Questions over Excel programming

text: I have always heard about the powerful programming capabilities of Microsoft Excel (not VBA, I am referring to the formulas of Excel itself), but have never seen it.   * Does it really have all that power on formulas or have I misunderstood?   * If it does, what is the extent of Excel's programming capabilities?   * How is it done (what does serious, complex programming looks like in terms of syntax, patterns, styles, etc.)?   * Does it pertain to a paradigm (say, functional programming)?   * Do Excel programmers exist?   * What is it mainly used for?


title: Future of SOAP, with REST?

text: Considering that more and more Web Services are implementing a RESTful interface, I am wondering what the future of SOAP will be? I'm looking for any kind of papers, statistics, articles or publications from official sources (e.g. books, articles and journals) which provide information on the future of SOAP. Thanks in advance!