title: Designing unit tests for a stateful system

text: ## Background Test Driven Development was popularized after I already finished school and in the industry. I am trying to learn it, but some major things still escape me. TDD proponents say lots of things like (hereafter referred to as the "single assertion principle" or **SAP** ): > For some time I've been thinking about how TDD tests can be as simple, as > expressive, and as elegant as possible. This article explores a bit about > what it's like to make tests as simple and decomposed as possible: aiming > for a single assertion in each test. Source: http://www.artima.com/weblogs/viewpost.jsp?thread=35578 They also say things like this (hereafter referred to as the "private method principle" or **PMP** ): > You generally don't unit test private methods directly. Since they are > private, consider them an implementation detail. Nobody is ever going to > call one of them and expect it to work a particular way. > > You should instead test your public interface. If the methods that call your > private methods are working as you expect, you then assume by extension that > your private methods are working correctly. Source: How do you unit test private methods? ## Situation I am trying to test a stateful data processing system. The system can do different things for the exact same piece of data given what it's state was prior to receiving that data. Consider a straightforward test that builds up state in the system, then tests the behavior that the given method is intended to test.   * SAP suggests that I should not be testing the "state build up procedure", I should assume that the state is what I expect from the build up code and then test the one state change I'm trying to test   * PMP suggests that I can't skip this "state build up" step and just test the methods that govern that functionality independently. The result in my actual code has been tests that are bloated, complicated, long, and difficult to write. And if the state transitions change, the tests have to be changed... which would be fine with small, efficient tests but extremely time consuming and confusing with these long bloated tests. How is this normally done?


title: Network computation

text: I'm pretty sure that someone has already thought about it and researched it extensively, but I'm having trouble finding any materials or even keywords to look for, for the idea that I was thinking about recently. I thought about this concept, where in distributed systems, actual computation and processing would happen on the network, rather than on nodes (server or client) on their way from the source to the destination. Where network routers in addition to routing network packets to the next node until delivered to the destination, they would also execute some embedded instructions in those packets. So for example a network packet would be split into two areas: data and instructions (+ some headers) And when a router routes a packet to the next router, it would send a transformed packet according to the embedded instructions:               +----------------------+     |Network Packet Headers|     +----------------------+     | DATA SLOT 1          |     | DATA SLOT 2          |     | ..........           |     | DATA SLOT N          |     +----------------------+     | Increment slot1      |     | SLOT3 = SLOT1 + SLOT2|     +----------------------+     | instruction ptr      |     +----------------------+      So that by the time those network packets would get to their destination, a portion of it (depending on how many hoops it had to go through) would already be computed (say audio decoded, etc..) offloading both endpoints. Routers are technically capable of doing this. They do process data based on network packet's values - like choosing where to send the packet next basing on the IP header. There is nothing stopping them from being utilized as "the real cloud", right? Each router would execute one packet or a couple of instructions from that packet (and update the instruction pointer) depending on it's HW resources and capabilities. So a network packet would be a stack frame rather than just a network packet. Of course, there is a whole class of problems associated with this model, like properly partitioning data (or even the ability to do so.), but it's all based on old concepts from heterogeneous computing and functional programming. Could someone please point me to any research, materials or projects that deal with similar concepts? Thanks!


title: Experimenting with "big data" and map reduce

text: I was thinking about experimenting a bit with using mapreduce and such on a dataset we have to see if we can benefit from it in any way. What route should I go if I want to be able to instantly, without any major modification, deploy my findings to some kind of grid/cloud-system to see if there is any extra benefit to have it scaled in the cloud.


title: Persistent storage for Apache Mesos

text: Recently I've discovered such a thing as a Apache Mesos. It all looks amazingly in all that demos and examples. I could easily imagine how one would run for stateless jobs - that fits to the whole idea naturally. Bot how to deal with long running jobs that are stateful? Say, I have a cluster that consists of N machines (and that is scheduled via Marathon). And I want to run a postgresql server there. That's it - at first I don't even want it to be highly available, but just simply a single job (actually Dockerized) that hosts a postgresql server. How would one organize it? Constraint a server to a particular cluster node? Use some distributed FS?


title: How to write Requirements for a specific module

text: I am familiar with writing Software Requirements Specification, but not quite sure how to write the requirements for a specific module. Let's say I need to develop a Reservation System and there will be a module to perform validation. Now, an SRS is already available for the entire system, but prior to designing(API Specification and Class Diagrams) the Validation module, what would be the format of writing Requirements for this module.


title: AJAX or web sockets for client-server communication?

text: I recently took a course on AngularJS, and quite frankly I loved the concepts of a website that fetches json to handle subsequent requests, however I still feel like Javascript is far too slow for what I want to do on a server. I have recently been hired to build an online auction website. I built two mockups, one with AngularJS and one in PHP. The PHP website is much faster on initial load and handling large requests, but the AngularJS-powered site is much more responsive on simultaneous requests, and writing JavaScript and HTML frontend is much easier, so I got to thinking that I might just make a counterpart to AngularJS using PHP, JS, and HTML, giving me the best of both worlds. As I go forward in implementing the design, I started to question if AJAX was the right tool for the job. It seems like I could use a simple node.js websocket server as an intermediary to between the client-side JS and PHP, passing commands from the client over websockets to the server, then passing the data back. Would you consider this premature optimization, and if not, would removing the HTTP overhead really make much difference at all in terms of bandwidth and request size?


title: Would it be better to have extra checks, or would it be a waste of time?

text: In your opinion, do you think it is a waste of time to make checks that you know there is no possible way of it being there/not being there, or would you just put it there just in case there is a bug or something? For example, below checks to see if a button is visible, then music is playing, but there is no way for that button to be shown without the music playing:               if (buttonVisible)         if ([music playing] == true) //is always true if the button is visible             [music stopPlaying];


title: Need help with clarifying the design of an Android game

text: I'm going to develop a Kakuro (Cross-Sums) game for Android, and have got the algorithm right. But I can't seem to get the user-interaction part right- i.e. The puzzle is very large. So only a portion is shown at a time to a user _depending_ on their device (eg: HVGA smartphone vs XGA tablet). It should be scrollable. To make it more clear, see the images below: ![Grid as rendered on a smartphone](http://i.stack.imgur.com/4FuiJ.png) ![Grid as rendered on a tablet](http://i.stack.imgur.com/rZPWy.png) So what I'm asking for: Do you know a suitable method to approach this? I mean, like a design or a structure that will achieve this kind of behavior? Please note that I'm completely new to game programming and do not know anything about canvases, etc (but have got experience in application development). So any help really appreciated.


title: How do I maintain states

text: I have a winforms application with a display window that can show 3d geometry. I have another control on which I have a series of options to turn on/off different items in my display window. However the display state of these items is changed a lot of places in my code. Does a design pattern or some other example of how to structure code to maintain states exist?


title: Storing archived index data

text: We use RavenDB as our data store for transactional information, and it works well for data that is currently "in use". We also collect audit events as people use our application, where each event looks something like:   * Type, date, summary, etc. - pretty standard   * Related document IDs (could be one, could be 5) As a document store, Raven does a great job of indexing these so that we can ask questions like "find all events related to document XYZ". Unfortunately as the data builds up over time, these audit events can account for 90% of the data stored in our database - and it's rarely used. We'd like to get this data out of Raven, and into some kind of storage that might be better suited. What other storage solutions exist for storing hundreds of thousands of audit- type events? We're happy to sacrifice speed to save storage and indexing costs.


title: Should Business Interfaces be part of the Model layer?

text: In an oriented-services enterprise application, isn't it an antipattern to mix Service APIs (containing interface that external users depends on) with Model objects (entities, custom exceptions objects etc...) ? According to me, Services should only depends on Model layer but never mixed with it. In fact, my colleague told me that it doesn't make sense to separate it since client need both. (model and service interfaces) But I notice that everytime a client asks for some changes, like adding a new method in some interface (means a new service), Model layer has to be also delivered... Thus, client who has not interested by this "addition" is constrained to be concerned by this update of Model... and in a large enterprise application, this kind of delivery is known to be very risked... What is the best practice ? Separate services(only interfaces so) and model objects or mix it ?


title: "Everything is a Map", am I doing this right?

text: I watched Stuart Sierra's talk "Thinking In Data" and took one of the ideas from it as a design principle in this game I'm making. The difference is he's working in Clojure and I'm working in JavaScript. I see some major differences between our languages in that:   * Clojure is idiomatically functional programming    * Most state is immutable  I took the idea from the slide "Everything is a Map" (From 11 minutes, 6 seconds to > 29 minutes in). Some things he says are:   1. Whenever you see a function that takes 2-3 arguments, you can make a case for turning it into a map and just passing a map in. There are a lot of advantages to that:      1. You don't have to worry about argument order     2. You don't have to worry about any additional information. If there are extra keys, that's not really our concern. They just flow through, they don't interfere.      3. You don't have to define a schema   2. As opposed to passing in an Object there's no data hiding. But, he makes the case that data hiding can cause problems and is overrated:      1. Performance     2. Ease of implementation     3. As soon as you communicate over the network or across processes, you have to have both sides agree on the data representation anyway. That's extra work you can skip if you just work on data.   3. **Most relevant to my question. This is 29 minutes in:** "Make your functions composable". Here's the code sample he uses to explain the concept:              ;; Bad     (defn complex-process []       (let [a (get-component @global-state)             b (subprocess-one a)              c (subprocess-two a b)             d (subprocess-three a b c)]         (reset! global-state d)))          ;; Good     (defn complex-process [state]       (-> state         subprocess-one         subprocess-two         subprocess-three))      I understand the majority of programmers aren't familiar with Clojure, so I'll rewrite this in imperative style:              ;; Good     def complex-process(State state)       state = subprocess-one(state)       state = subprocess-two(state)       state = subprocess-three(state)       return state      Here are the advantages:     1. Easy to test     2. Easy to look at those functions in isolation     3. Easy to comment out one line of this and see what the outcome is by removing a single step     4. Each subprocess could add more information on to the state. If subprocess one needs to communicate something to subprocess three, it's as simple as adding a key/value.      5. No boilerplate to extract the data you need out of the state just so that you can save it back in. Just pass in the whole state and let the subprocess assign what it needs.  Now, back to my situation: I took this lesson and applied it to my game. That is, almost all of my high level functions take and return a `gameState` object. This object contains all the data of the game. EG: A list of badGuys, a list of menus, the loot on the ground, etc. Here's an example of my update function:               update(gameState)       ...       gameState = handleUnitCollision(gameState)       ...       gameState = handleLoot(gameState)       ...      What I'm here to ask about is, **have I created some abomination that perverted an idea that is only practical in a functional programming language?** JavaScript isn't _idiomatically_ functional (though it can be written that way) and it's really challenging to write immutable data structures. One thing that concerns me is he _assumes_ that each of those subprocesses are pure. Why does that assumption need to be made? It's rare that any of my functions are pure. Do these ideas fall apart if you don't have immutable data? I'm worried that one day I'll wake up and realize this whole design is a sham and I've really just been implementing the Big Ball Of Mud anti-pattern. * * * Honestly, I've been working on this code for months and it's been great. I feel like I'm getting all the advantages he's claimed. My code is super easy _for me_ to reason about. But I'm a one man team so I have the curse of knowledge. # Update I've been coding 6+ months with this pattern. Usually by this time I forget what I've done and that's where "did I write this in a clean way?" comes into play. If I haven't, I'd really struggle. So far, I'm not struggling at all. I understand how another set of eyes would be necessary to validate its maintainability. All I can say is I care about maintainability first and foremost. I'm always the loudest evangelist for clean code no matter where I work. I want to reply directly to those that already have a bad personal experience with this way of coding. I didn't know it then, but I think we're really talking about two different ways of writing code. The way I've done it appears to be more structured than what others have experienced. When someone has a bad personal experience with "Everything is a map" they talk about how hard it is to maintain because:   1. You never know the structure of the map that the function requires   2. Any function can mutate the input in ways you'd never expect. You have to look all over the code base to find out how a particular key got into the map or why it disappeared.  For those with such an experience, perhaps the code base was, "Everything takes 1 of N types of maps." Mine is, "Everything takes 1 of 1 type of map". If you know the structure of that 1 type, you know the structure of everything. Of course, that structure usually grows over time. That's why... There's one place to look for the reference implementation (ie: the schema). This reference implementation is code the game uses so it can't get out of date. As for the second point, I don't add/remove keys to the map outside of the reference implementation, I just mutate what's already there. I also have a large suite of automated tests. If this architecture eventually collapses under its own weight, I'll add a second update. Otherwise, assume everything is going well :)


title: Developing an Interface to a Dynamic System

text: I work for a small company and have been designing a GUI to interface our embedded system. The problem with this embedded system is that it is not a finished product (may never be) and is constantly under development and being tweaked and updated for different customers and applications in small volumes. So to deal with this I made a program that can export all the data from a spreadsheet where most of the embedded system variables are sourced from and throw them into a small database for the GUI application to use. This database program I made also spits out a cross reference file for the embedded system which allows the GUI to look up all the variables. This system works pretty well so far, and is even integrated with version control among the GUI, database, and embedded system. The big problem is that there is constant development on several projects that use this system and it gets terribly tedious to keep the system up to date and bring in new changes. This has gotten to the point to where I have had to code the GUI to dynamically (generically) generate all interfaces since I am never guaranteed to find the same data the same way. I have not been able to come up with a good way to uniquely identify the data I import from excel since all fields are able to be changed (due to engineering stubbornness, code re-factoring and/or excel issues) and I cannot assign a fixed reference within the sheet itself. So, are there any good methods or ideas on how to handle the chaos?


title: What is a good tag management system?

text: I work for a publishing company where we have to track converts, etc. Suffice to say we have tags for different areas of the world, and the list can get very large. We need to find a systemt that can give tag `A` to country `B` and so on, and I need to make it so my less technical gifted can manage it. Does anyone know of a good solution?


title: Implementing a sort of navigation system

text: So I am undertaking a project which does navigation sort of thing. So here is how the problem statement looks like. Say, given a map of a floor, with different rooms, now somehow, this information is provided to the program and what the program does is, it takes two more inputs, The starting location. The final location. Now having had these two locations, the program draws out the best possible route from starting to ending location. I will be using C language for the implementation of code. Now, the problems:   1. How do I provide the information about the floor, i.e. whether there's a wall or a door or just empty space, to my program. Here's my take on it. I will have a 2-D matrix, where in the 1 in the matrix shows an empty space, and a 0 signifies a wall. But now I am not sure, how to mark a cell as 0. i.e how the dimensions of the matrix shall be chosen? For example, say my floor is 8 by 8 (length units). Now shall my matrix be 8 by 8 or 16 by 16 or what? And what if, having chosen the dimension of a single cell, if some part of the cell is wall and the other is empty space, shall it be a 0 or a 1? But I guess, it would be a manual input after all? But I dont expect someone to create this kind of matrix for me manually? So, some help in this direction will be appreciated? Is this way of representing the data allright, or shall I go about in a different direction?   2. Say, If I go by the above way of data representation, what do I do next? I was thinking, somehow, I will have to convert that matrix of data into a graph and after that it will be an easy problem to deal with. I am not quite sure, how I will do it but I will appreciate some sources, wherein I can read about something similar.   3. Are there any other tips, that I shall go by, for this project? PS : By Navigation I mean, given the starting and end point, and considering the starting point to be the same as the current location of the device, it shall move to the final location on its own. Thanks.


title: How to authenticate an archive

text: Background: I have a updator feature in my program which will downloads updates to a directory specified be the user. Then user can install these updates whenever he/she wants by just opening them. These updates are nothing but a compressed archive file which is associated to be opened by my app. Problem: Now, I want when the user install the updates, my program should ensure that they are original updates created by me and are not modified by someone else. How can I ensure that? I have heard about Winrar authenticity verification. but I'm unsure whether it is good or not? Edit: User have two ways to install the updates. A) User download the updates from the server. An update file will get saved on user PC. User will open the update file to install it. B) This is for user who don't have internet connectivity on his PC User download the update on a cyber cafe, copy it to his own PC and then install them. Since in option B, user don't have internet connectivity in his PC, so my program can not check the base value on update server.


title: Is there any professional way to illustrate difference between 2 diagrams?

text: I made a documented which is to describe the difference between the same logical structure from different version ( e.g Structure A from version 8 and Structure A from version 9 ). Luckily I've got the logical structure diagram from the 2 functional specification. I've managed to copy the image of each logical structure and paste them in MS Word and compare the 2 version side by side. I don't know if there is a standard way to illustrate the difference. I simply draw a cross over the removed logical member from the previous version and draw a rectangle around the new logical member of the next version. I know my way is kinda childish. I am wondering how to present them professionally. ![enter image description here](http://i.stack.imgur.com/UpGFG.png) In addition, You won't believe this, but MS Word doesn't have a shape of CROSS, so I am actually using a multiplication sign that look like a giant monster: ![enter image description here](http://i.stack.imgur.com/h5Lim.png) This is why I hate myself. Unlike 2 separated lines, this shape is easy to use, draw and resize. I am wondering if MS Word would care about a normal cross.


title: DSL enabling users to reference forms and records to display?

text: There are three main "unique" components to my system:   1. Visual form builder (AngularJS backed);      * generates an `id`     * CRUD automatically available for it at `/form_type/id`   2. "Aggregate page"; with a form contain a title and **DSL input area**     * specify an `id`; which will present CRUD for forms created in `1.`     * can specify read-only     * CRUD "Aggregate page"   3. Search * * * With the DSL; I was thinking to use Markdown with an additional braces syntax, for example:               Heading      =======          Lorem ipsum          {2_columns: [{form_type:id}, {form_type:id read-only}]}      Alternatively I could provide a simple drag-drop interface; so you drag text boxes and widgets around a predefined template (e.g.: two columns). * * * Suggestions on this approach and/or my DSL syntax would be greatly appreciated. Note that I will likely FOSS this once it's ready.


title: How can I find trends relating to the adoption of different programming technologies?

text: > **Possible Duplicate:**   >  Statistics of language use per industry I'm looking for data on programming technology adoptions rates. I'm curious to find data of job demand and programmer supply across a number of different technologies. So far, I've been looking at LinkedIn's Skills and Google Trends, but these only track programmer interest. Any suggestions on finding the data that I'm looking for?


title: Given known inputs and outputs, can we generate candidate functions that will map the inputs to outputs?

text: I've run into a problem where I have a set of inputs, as well as a couple known input-output pairs. I am interested in the output, but in order to get that, I need to figure out how the input is used to generate the output. So for example, I might have the following input strings along with a few known output strings               char001 --> dasjudash2 // known input/output     char002 --> ef2y789e2y // known     char003 --> jnjxf9823d // known     char004 --> ?          // unknown output     char005 --> ?          // unknown output      I believe that there may exist some algorithm that takes an input and produces the given output, but this algorithm is unknown. It is very possible that the pairs are randomly generated as well (eg: look at the sky, randomly pick a string of characters). I could stare at it long and hard and try to think of how they are related, but computers can probably help me out. Basically, given known inputs and outputs, is it possible to come up with potential functions that will take known inputs and generate known outputs, and then use that to take the rest of the inputs and generate the corresponding outputs? Given that the solution may be one of an infinite possibilities (including the possibility that no solution exists, in the case that someone did just look at the sky and pick random characters out of a hat), I would quickly dismiss it as a computationally infeasible task, but perhaps my intuition is wrong and there is research evidence to show that this problem is solvable?


title: Is Microsoft Solver capable of solving such complex scheduling problems

text: I'm writing a application that will decide the scheduling plan for a few dozen people according to their occupation (role) and availability (week day and hours). I've used a excel spreadsheet to help solve this problem, I was then able to devise a logical and decision based approach to assign these people to shifts and roles, following a few set of constraints. When I was about to write this into code, I was suggested to try Microsoft Solver. I've read a while about it's capabilities but I'm unfamiliar with some terminology encountered. Well, suffice it to say that I never used Microsoft Solver and I do not even know if the following scheduling problem can be solved with it or not. So far I've found very few examples about scheduling problems and even those are simple by comparison. So my question is, can Microsoft Solver solve the following scheduling problem? * * * **Scheduling problem** Assign people to shifts for an entire week based on their availability and what role they are qualified to fill following a few set of constraints and goals. **Structure**   * Weeks are composed of seven days.   * Days are composed of shifts (dawn, morning, afternoon and night sifts are the most common). Shifts are specified in this way:      * Dawn: 00:00 AM -> 08:00 AM     * Morning: 08:00 AM -> 12:00 AM     * Afternoon: 01:00 PM -> 07:00 PM     * Night: 07:00 PM -> 00:00 AM   * There are some weekdays which might not have any shifts while others can have one, two or more.   * Each person has a weekly availability following the same week day / shift structure.      * Example: Peter is only available on Monday night's (Monday 07:00 PM -> 00:00 AM).   * Sometimes people have two or more days on which they are available and would like their schedule to rotate through these.      * Example: Kyle is only available on Wednesday night's and Thursday morning's, also he would like to rotate them. One week Wednesday another week Thursday.   * Each person has a set of roles he or she can fill (one or more).      * Driver     * Medic     * Doctor **Goals**   1. Each shift must have at least: two drivers, one doctor and three medics.   2. Every person with availability must be assigned to a shift, it does not matter if one shift has three drivers while another only has two. **Constraints**   * A person can only fill one role per shift.   * A person can only be assigned to a shift if he or she has availability to perform it.   * A person can only be assigned to a role if he or she is qualified to perform it.   * A person can only be assigned to one shift per week, unless when the organization is understaffed _(by understaffed means we need more people to fill shifts to meet goal #1)_. If thats the case one additional condition applies when assigning people to shifts after the first one.      * A person assigned to a second shift in the same week must be the person that hasn't performed a second shift for the longest time, while still meeting the person's availability and role capability. _Moderator note: Could not find the appropriate tags._


title: How do I evaluate an IDE?

text: I don't want to know which IDE is best, because that's subjective. I'd like to know how to evaluate an IDE. I'm primarily a `vim` user, and realistically happy there, but occasionally look at languages that have powerful IDE's and I consider using them. The problem I run into is that they mostly seem the same to me. Certainly any of them will work, but when trying to decide which IDE to invest time in how do I decide? What features should I be testing to see if I like the way A or B works better? Obviously some IDE's are specifically tailored to a language, but given a choice between say Netbeans, Eclipse, and Intellij IDEA, how would I decide? as a novice they seem the same. When evaluating I generally try the editor, a few configuration options, file browser. I think my colleagues all basically the same as me and don't use IDE. I also doubt I'd end up using the IDE for work, because Perl shop, and I'm happy with vim for that, I'm simply trying to figure out how to use them in the context of languages that aren't day job and have solid IDE support.


title: How to manage releases with multiple features at different states?

text: We have a branching structure of:   * multiple dev branches for each major new feature   * Main branch, merged into from a dev branch once a feature is ready for testing   * Release branch, merged into from Main once a feature is ready for production We often have new features completed at around the same time that end up in Main, with some of the same source code changed. Then Feature A may be declared ready for production and need to be deployed, while Feature B requires more work. Once changes are incorporated in Main, particularly with multiple revisions to Feature A and B, **their identity as separate features is lost**. It then becomes risky and difficult to promote just one of them to production. We use TFS and I don't know if this is one of its limitations. What is the best way to resolve this? Should we be using a different branching strategy, or would a DVCS fix it?


title: Refactoring: Two big chunks within a function

text: I am designing an API which mostly involves refactoring the original code. So Right now I have a method which has two big chunks which are seperated by an If-else condition, which in my opinion is not exactly the best idea. The code looks like               do_something():          if (isTrue):              #Large block of statements.          else:              #another large block of statements.      The reason I have them both under a single function is because both the chunks do the same thing but with some slight variations, which introduces the ugly if-else block. I wanted to know what would be the best idea to refactor this code in a better way, if it is possible to do that using OOP, that would be even better. I am not going with the obvious defining two methods way because at the moment both the chunks are doing the same thing.


title: Does anyone use virtual machines for web development, and why?

text: I see a few developers that like to use virtual machines for web development. Are there others that do this? If there are, why do you do it? Are there any pros / cons to developing on a VM rather than in a non virtualised environment? I would think things are slower in a VM.


title: Project managers: Do you encourage any sort of task division between morning and afternoon?

text: I haven't read about this anywhere, but here are my thoughts: programming is inherently intellectually hard. I remember reading in Code Complete something that stuck with me: the author pushing and working on something long hours only to spend the rest of the week fixing it. This is something managers don't understand. For example, in the last company I worked in, we were expected to switch between tasks and projects as if we were switching from tightening bolts to painting in an assembly line. Getting into a project or fixing a bug, especially with the terrible code we had to maintain, has a lot of momentum and takes a while to get all the needed information in your head and start getting things done. I was thinking it would be good to concentrate design and coding in the early hours when we tend to stay more alert and do training, administration or meetings in the afternoon. Has anyone thought about this before? any studies?


title: Meta-programming

text: I have just started my journey as a C++ developer, and I have recently been researching a topic called meta-programming. So far, I have gone through a lot of information on the topic, and have few questions.   1. Usage of Reflection in c++: Is it possible? As per my understanding reflection is a meta-programming technique which has the ability to manipulate a state of a program, and its manipulation can be introspection or introcession.   2. What is the difference between reflective architecture and meta-level architecture? In which category does meta-programming architecture fall in?   3. Meta-programming comes in two levels: meta level and base level. In my understanding, the object program or the system under investigation is the base level, and the meta program that is going to operate over the system under investigation is the meta level. Am I correct? Also help me by providing some guidelines about working on template metaprogramming in C++.   May you suggest me some workable examples I can look for to get hands-on in this programming technique?


title: 'Save' button in our web app ( 20-30 textboxes), client is worried that users will forget to click it and lose their data

text: I am in a meeting with a client later on, regarding an ASP.NET web app we are creating for him. The app includes a lot of 'form' style screens with 20-30 textboxes, and of course a 'Save' button that posts back to the server and saves the data. The client really does not like this as he is worried users will forget to click 'Save' and lose their data. While I obviously understand that we can use AJAX to save as the user goes along, I believe this is beyond the scope of the project and is prone to error. Has anyone dealt with clients like this?


title: I want to write a 2-player web-based board game. Which framework should I use?

text: I am a C# software developer. I was recently approached by a client to develop a multiplayer board game (max 4 players). I fiddled around with WCF, WPF and EF 4.1 to get something going but I keep running into small stumbling blocks. It certainly does appear that integrating all these technologies into one solution is problematic. I do not have extensive experience in WPF/WCF but I find the concepts easy to grasp. It's just that I keep running into little problems which are huge stumbling blocks. My thoughts were to first create a WCF service to manage the boards and rules. I would then turn to the UI (possibly Silverlight/WPF). I am actually at the point where I think I should try a framework or even venture to PHP/Ruby/Python. The requirements are simple:   * Web based   * Turn based   * Board game   * Database backend As a C# developer (possibly a poor one), what would you suggest?


title: Specializing in a Vendor Software Package - am I putting my career at risk?

text: So, I have this opportunity to specialize in a vendor software package (like SAS, SAP, PeopleSoft, Pega, Lombardi BPM...). You know the deal - they need a coder to learn their package and _"there's all this demand for the skill"_ ; _"big growing companies are using it"_ , etc, etc. And (now, at least), the money's better. I'm worried about whether or not I'll be able to keep my "normal" programming skills current.   I'm worried about what it will look like on a resume if I switch back to "normal" programming in a couple of years.   I'm worried about whether or not it will be fun. What do you think?


title: Do you test your SQL/HQL/Criteria?

text: Do you test your SQL or SQL generated by your database framework? There are frameworks like DbUnit that allow you to create real in-memory database and execute real SQL. But its very hard to use(not developer-friendly so to speak), because you need to first prepare test data(and it should not be shared between tests). P.S. I don't mean mocking database or framework's database methods, but tests that make you 99% sure that your SQL is working even after some hardcore refactoring.


title: Am I programming too slow?

text: I've only been a year in the industry and I've had some problems making estimates for specific tasks. Before you close this, yes, I've already read this: http://programmers.stackexchange.com/questions/648/how-to-respond-when- you-are-asked-for-an-estimate and that's about the same problem I'm having. But I'm looking for a more specific gauge of experiences, something quantifiable or probably other programmer's average performances which I should aim for and base my estimates. The answers range from weeks, and I was looking more for an answer on the level of a task assigned for a day or so. (Note that this doesn't include submitting for QA or documentations, just the actual development time from writing tests if I used TDD, to making the page, before having it submitted to testing) My current rate right now is as follows (on ASP.NET webforms):   * Right now, I'm able to develop a simple data entry page with a grid listing (no complex logic, just Creating and Reading) on an already built architecture, given one full day's (8 hours) time.    * Adding complex functionality, and Update and Delete pages add another full day to the task.   * If I have to start the page from scratch (no solution, no existing website) it takes me another full day.   * (Not always) but if I encounter something new or haven't done yet it takes me another full day. Whenever I make an estimate that's longer than the expected I feel that others think that I'm lagging a lot behind everyone else. I'm just concerned as there have been expectations that when it's just one page it should take me no more than a full day. Yes, there definitely is more room for improvement. There always is. I have a lot to learn. But I would like to know if my current rate is way too slow, just average, or average for someone no longer than a year in the industry.


title: Where to put external libraries in a Qt project?

text: I create many small Qt Creator projects (.pro file based, not CMake) and sometimes need to use external libraries in them. Up until now I used to have a project structure like below:               project folder     |- project.pro     |- (project .cpp and .h files, possibly in subfolders)     |- lib        |- include        |  |- library1        |  |  |- (all library1 header files)        |  |- library2        |     |- ...        |- win32        |  |- library1.dll        |  |- library2.a        |  |- ...        |- unix           |- library1.so           |- library2.a           |- ...      The whole `lib` folder (with binaries) was included in my repository (git). This approach was okay when using small libraries, but since I started using some large libraries, I put them into separate repositories (per library) and used git submodules. Still, that solution is imperfect, since I'd use up a lot of additional space after updating my libraries and generally putting them in a repository is considered a bad idea. I was thinking about a solution where you could have a system variable for manually installed libraries or have it defined in qmake, but that would require additional work and reading documentation to configure the project. Another approach would be to simply download/compile libraries and put them into an ignored (in git) `lib` folder, but then we'd end up with duplicate libraries everywhere (and a problem to update them to newer versions across projects). How can I organize my Qt project to minimize amount of work and documentation reading needed to set it up and to maximize its maintainability?


title: How does the experience of any tester count?

text: A developer learns a lot of stuffs at work. For eg. Lets think of a Java or C++ developer, as years pass by he learns a lot about the technology, design patterns, new frameworks and etc ... This I think adds his work experience a good score to his profile, but               What makes a testers work experience important ?      I'm into Web Application testing an intern in a product based company for the past four and a half months. At my office employees who are two or three years ahead of me don't do the work in any way different than I do, They don look like they have learned anything great from their from work experience. _Is this the fate of a tester or is this happening only at my office ?_. I would love to hear answers from any of my fellow testers who have walked the path of testing :)


title: Translating views in MVC

text: What is the best practice, when it comes to views' translation in MVC design pattern, in multilingual website:   1. Always have only one view file and translate its particular strings with a framework translation function.   2. Always have as many views as website supports, directly translated, one for each language, and let framework internals load particular language-specific view file for language currently selected by user. Which of these two options should I use (if there isn't any third one) and why?


title: Working with Javascript classes the right way

text: Comparable questions have surely been asked before but I'd like to hear some words about my specific way of implementing Javascript classes. Let me first start with a Javascript example taken from a real-life application I've been working on recently. **Example**               PageControl= new function() {       var self= this;            // example additional control bound to page control       var grid= new GridControl();            self.initialise= function() {         // initialise form fields, controls etc.       };            // example function       self.load= function(id) {         // reloads form with new data       };            $(document).ready(function() {         self.initialise();       });     };      Each page has its own PageControl instance with specific tasks solely relevant for the given page. **Question:** I'm not looking for alternative ways of how to implement it, I'd just want to know if the above example is bad or wrong code. The above structure has worked great so far, even if I work with sub controls like `PageControl.grid.reload();` but I don't want to stick to error-prone code.


title: DTO - service layer - statelessness best practices interfering with each other

text: I am designing a REST API coupled with a service layer that takes DTOs as input and produces them as output. This works fine for most service calls where the DTO is used to access an underlying library (an embedded OLAP server) that does the work. There is one service, however, where something seems wrong. The service is responsible for creating, manipulating, and optionally storing objects that represent reports (think excel reports). It does this through the underlying library, which does not expose reports as a resource. Since the reports don't represent a server-side resource unless they are persisted (persistence being my own implementation, not a concept in the library), the service needs to take a report object that holds all the information necessary to construct a report from scratch to be stateless. I decided that the report service methods should take a ReportDTO, manipulate it, and return the modified version. (This would include operations such as swapping the row and column axes, sorting an axis, and filtering an axis.) My thinking was that since I have all the information available in the ReportDTO necessary to perform all these operations, I might as well perform them on the DTO and return a modified version rather than duplicate the DTO as a domain object. That is not to say the server doesn't interface with any model. Indeed, the server-side code involves validating the report using a third party library (i.e., the validation model is not my own -- i don't have a domain model for the report itself, just DTOs), saving the report if the user so chooses, and executing the report against a database to obtain fresh data. So there is work to be done besides manipulating DTOs, it's just that it's not work tied to a domain model I needed to design myself, but rather one provided to me. After I implemented the aforementioned operations, I realized something. The operations are business logic operations, are they not? A DTO should not have this. I then had numerous other thoughts: "Okay, that's fine, I'll do the operations in the service layer... Oh, wait. The service layer should only coordinate domain objects that contain business logic, not have business logic itself. Alright, I'll make the ReportDTO a bonafide domain object. Crap, now I am exposing my domain objects from the service layer. This is an API, I should really stick with DTOs as the input and output for the service layer so that changes in my domain model (or changes in the 3rd party domain model I utilize) do not affect the contract with service clients. Fine, I'll have a Report and a ReportDTO.... that have exactly the same members because the ReportDTO already has all the necessary information to manipulate a report (just not execute, validate, or save it) due to the transient report decision I made for the sake of a RESTful API." Clearly I have countered my every proposed solution. So, what the heck do I do? I don't want to make reports stateful because I really don't see them as a resource until they are actually saved. If I make them stateful I'll need to manage a map or cache of them in my service and deal with multiple clients trying to give their report the same name, implement security to ensure that a user can only see his own reports, etc. All these problems go away with a stateless approach. The side effects, however, are the aforementioned issues. Did I go wrong somewhere? Please help me tackle this design issue before it becomes a permanent part of my API. Thanks.


title: Does Git have a "safe mode" to prevent rewriting history?

text: When you're kind of fresh with Git (and DVCS in general), and you start exploring history-rewriting changes, you're safe if the repository is only local, but you might run into problems if you work with remotes and try to push such changes. A feature that I'd expect is the ability to enable a "safe mode" which would basically stop me from doing whatever I shouldn't do... And what do I mean by that? I mean history-rewriting changes for things already pushed to an origin. I can't define it precisely, but this would include such cases as:   * `commit --amend` when HEAD has been already pushed   * `rebase` of a non-local branch   * `reset` of a branch that has been pushed These are examples of situations which will will probably make the next `push` fail (because it wouldn't be fast-forward, IIRC). I've made some of that by accident and had to re-create the branch on the remote. And I still was lucky to do this fast enough so that nobody pulled the history I've rewritten. I believe it's possible to identify this type of changes and, on demand, prevent the user from making them. Is there perhaps an option for that? If there isn't, do you think it's worthwhile to attempt to create it? Would you try to define precisely how to identify such a "dangerous change"?


title: Significant amount of the time, I can't think of a reason to have an object instead of a static class. Do objects have more benefits than I think?

text: I understand the concept of an object, and as a Java programmer I feel the OO paradigm comes rather naturally to me in practice. However recently I found myself thinking: Wait a second, what are actually the practical benefits of using an object over using a static class (with proper encapsulation and OO practices)? I could think of two benefits of using an object (both are significant and powerful):   1. Polymorphism: allows you to swap functionality dynamically and flexibly during runtime. Also allows to add new functionality 'parts' and alternatives to the system easily. For example if there's a `Car` class designed to work with `Engine` objects, and you want to add a new Engine to the system that the Car can use, you can create a new `Engine` subclass and simply pass an object of this class into the `Car` object, without having to change anything about `Car`. And you can decide to do so during runtime.   2. Being able to 'pass functionality around': you can pass an object around the system dynamically. **But are there any more advantages to objects over static classes?** Often when I add new 'parts' to a system, I do so by creating a new class and instantiating objects from it. **But recently when I stopped and thought about it, I realized that a static class would do just the same as an object, in a lot of the places where I normally use an object.** For example, I'm working on adding a save/load-file mechanism to my app. With an object, the calling line of code will look like this: **`Thing thing = fileLoader.load(file);`** With a static class, it would look like this: **`Thing thing = FileLoader.load(file);`** **What's the difference?** Fairly often I just can't think of a reason to instantiate an object when a plain-old static-class would act just the same. But in OO systems, static classes are fairly rare. So I must be missing something. **Are there any more advantages to objects other from the two that I listed?** Please explain. **EDIT:** To clarify. I do find objects very useful when swapping functionality, or passing data around. For example I wrote an app that makes up melodies. `MelodyGenerator` had several subclasses that create melodies differently, and objects of these classes were interchangable (Strategy pattern). The melodies were objects too, since it's useful to pass them around. So were the Chords and Scales. **But what about 'static' parts of the system - that aren't going to be passed around? For example - a 'save file' mechanism. Why should I implement it in an object, and not a static class?**


title: How to price code reviews to encourage good behavior?

text: I work for a company that has a hosted .net internet application with many clients. Those clients often want to write customizations for our application. We have APIs to hook into the app, but the customizations themselves are written in .net. This is a shared, secure hosting environment and we have to code review these customizations before we can deploy them in our datacenter to ensure that they don't degrade performance, crash our servers, or open any security vulnerabilities. We charge for these code reviews. The current pricing model is simply a function of the number of lines of code. I think this is a bad idea for a variety of reasons, but primarily because, if we are interested in verifying that the code works as expected, we should be incentivizing good, readable code, not compaction. I would like to propose a pricing model that incorporates some, or all of the following as inputs:   * Lines of code   * Cyclomatic complexity   * Avg function length   * # of functions Are there any other metrics I should incorporate, or other ideas for how we can reasonably create pricing for code reviews that encourages safe and understandable code?


title: Multiple Dispatch vs. Function Overloading

text: I'm trying to understand the difference (if any) between the two. According to the Wikipedia page for Multiple Dispatch it is synonymous with Function Overloading, but then later on goes on to say: > In a language with only single dispatch, such as Java […] which seems like a contradiction, since Java does support function overloading. So which is it? Is Multiple Dispatch different from Function Overloading, or is the article wrong in claiming that Java does not support Multible Dispatch?


title: Emphasizing the importance of TDD to customers

text: The importance of TDD needs to be propagated but there's always a gap in the project timeline and time needed for developing a TDD project. Customers usually do not understand the importance of code maintenance or TDD and want the project to be finished as soon as possible. The result would be a Test After Development which would be very basic minimal tests to please the coverage tools and let the project analyzers have a great Graph. Do projects developed using TDD take longer, or is that just an unfounded fear?


title: How to visualise Git commits on a video like a process?

text: There is a nice video which shows the development more like a process here. How can I visualise my own projects similar to this? Is there an open-source software to create this kind of visualisation? I think they would be quite useful to explain things to new developers before they start programming and perhaps I can also see the bigger picture.


title: Question about state and domain objects

text: Suppose I create a domain object called UserAdministration, if i have a method called CreateUser how would i pass state to this method, would I create properties on the UserAdministration object and have a CreateUser method or would i pass all the info for CreateUser method in a poco? Also how do I identify my domain objects?


title: I need some pointer tasks/challenges

text: I struggle with learning. I have to practice, and keep practicing, in order for something to stick. I don't do much C++ (once every month maybe) so I am constantly going over the same stuff. I need some tasks to do so I can really understand pointers and their uses in the real world, rather than reading scenarios. I've created my own link list, but I want more advanced stuff like using pointer arithmetic and pointers and functions. If anyone could provide some real world tasks to deepen my knowledge and experience with pointers I would be thankful. I'm ok with data types because of my Java experience. Look forward to some challenges (not too hard mind).


title: Styling compound AND / OR if statements

text: How do you style complex compound AND / OR if statements for maximum readability? How do you indent and where do you place the line breaks? My particular situation is something like the following. It's definitely better than smashing everything into one line, but still looks messy.               if (         (             x == y             && a != b             && p.isGood()              && (                 i + u == b                 || q >= a             )         )         || k.isSomething()         || m > n     ) {         doSomething();     }


title: Which code is better for branch prediction optimization?

text: Given branch prediction, and also the effect of compiler optimizations, which code tends to offer superior performance? Note that bRareExceptionPresent represents an uncommon condition. It is not the normal path of logic.               /* MOST COMMON path must branch around exception if */          bool SomeFunction(bool bRareExceptionPresent)     {       // abort before function       if(bRareExceptionPresent)       {          return false;       }           .. function primary body ..           return true;     }          /* MOST COMMON path does NOT branch */          bool SomeFunction(bool bRareExceptionPresent)     {       if(!bRareExceptionPresent)       {         .. function primary body ..       }       else       {         return false;       }       return true;     }


title: How are design-by-contract and property-based testing (QuickCheck) related?

text: Is their only similarity the fact that they are **not** xUnit (or more precisely, not based on enumerating specific test cases), or is it deeper than that? Property-based testing (using QuickCheck, ScalaCheck, etc) seem well-suited to a functional programming style where side-effects are avoided. On the other hand, Design by Contract (as implemented in Eiffel) is more suited to OOP languages: you can express post-conditions about the _effects_ of methods, not just their return values. But both of them involve testing assertions that are true in general (rather than assertions that should be true for a specific test case). And both can be tested using randomly generated inputs (with QuickCheck this is the _only_ way, whereas with Eiffel I believe it is an optional feature of the AutoTest tool). Is there an umbrella term to encompass both approaches? Or am I imagining a relationship that doesn't really exist.


title: Permissions/right model/pattern for .NET application

text: I need to implement flexible AND simple (if such thing exist) and at the same time utilize built-on means if possible So far I have MembershipProvider and RoleProviders implemented. This is cool but where do I go next? I feel like I need to add term "Priviledge" and than hardcode those inside application. Users will configure roles to add Privilidges to Roles and assign Roles to users. Does that sound like a good model? Should I think about adding priviledges at User level on top of adding them to Roles? I might but I envision problems with setup (confusing) and following support. If I don't do that and some specific users will need lesser priviledges - admin will have to create another role, etc.. Any silver bullet for system like this? And why Microsoft didn't go further then just Membership and Role providers? Another idea: Leave Roles as "priviledge" holder and hardcode them. Then I can code to those roles inside app using all available markups/attributes, etc - all Microsoft. Add new entity "Group" and create relationship like this   * Users    * UserGroups    * Groups    * RoleGroups   * Roles This way I can collect Roles into groups and assign those groups to Users. Sounds great and matches other software patterns. But then I can't really implement things inside RoleProvider like:   * AddUsersToRoles   * RemoveUsersFromRoles And some things do not really make sense anymore because they will be hard- coded   * DeleteRole    * CreateRole


title: Gathering application architecture

text: Suppose there is system for gathering info about system activities. There is a client part with an interface and there are agent parts that are installed on each machine. I estimate that there could be max 20 computers now. Later could be more like 50. My solutions:   1. Agent stores data into local database e.g. sqlite. There is also a service which can be used by a client to query data. So if a client wants to display data for 50 computers, he sends a query to 50 computers. I'am on that solution now but maybe it's totally wrong.   2. Agent stores data into local database (I don't known good one for that). There is also server (main database) and local databases are synchronized with the server. In this case, a client connects to the main database to display data.   3. Agent sends data in realtime to main database. So same as point 2, but there is no sync.   4. Like in point 3, but agent buffers data in local database and sends it in small chunks to main database. What is the best approach?


title: How do you plan your asynchronous code?

text: I created a library that is a invoker for a web service somewhere else. The library exposes asynchronous methods, since web service calls are a good candidate for that matter. At the beginning everything was just fine, I had methods with easy to understand operations in a CRUD fashion, since the library is a kind of repository. But then business logic started to become complex, and some of the procedures involves the chaining of many of these asynchronous operations, sometimes with different paths depending on the result value, etc.. etc.. Suddenly, everything is very messy, to stop the execution in a break point it is not very helpful, to find out what is going on or where in the process timeline have you stopped become a pain... Development becomes less quick, less agile, and to catch those bugs that happens once in a 1000 times becomes a hell. From the technical point, a repository that exposes asynchronous methods looked like a good idea, because some persistence layers could have delays, and you can use the async approach to do the most of your hardware. But from the functional point of view, things became very complex, and considering those procedures where a dozen of different calls were needed... I don't know the real value of the improvement. After read about TPL for a while, it looked like a good idea for managing tasks, but in the moment you have to combine them and start to reuse existing functionality, things become very messy. I have had a good experience using it for very concrete scenarios, but bad experience using them broadly. How do you work asynchronously? Do you use it always? Or just for long running processes?


title: Interview assignment: how long is reasonable?

text: So I'm hiring for a senior developer/team lead role for an ASP.NET MVC3 project. This is a big deal position for our team as this person will lead one of our two main products--a product that hasn't seen much developer love in a while. So I need to ensure that my candidates do smart things with controllers, views, view models, DALs, unit tests, etc. I use some trivial programming challenges during interviews but I want to give the folks who have trouble in whiteboard coding a chance to shine. The best assignment I can think of: implementing a trivial log in page, is probably more than an hour of work and even if I cap it at 2 hours, it is unlikely to be 100% finished. Is this fair? I'm trying to strike a balance between keeping the assignment reasonable and giving the applicant a chance to show off the wide range of skills being a tech lead requires.


title: Type dependencies vs directory structure

text: Something I've been wondering about recently is how to organize types in directories/namespaces w.r.t. their dependencies. One method I've seen, which I believe is the recommendation for both Haskell and .NET (though I can't find the references for this at the moment), is:               Type     Type/ATypeThatUsesType     Type/AnotherTypeThatUsesType      My natural inclination, however, is to do the opposite:               Type     Type/ATypeUponWhichTypeDepends     Type/AnotherTypeUponWhichTypeDepends      **Questions:**   * Is my inclination bass-ackwards?   * Are there any major benefits/pitfalls of one over the other?   * Is it just something that depends on the application, e.g. whether you're building a library vs doing normal coding?


title: Tester/Doer pattern: Assume the caller conforms to the pattern or be defensive and repeat the check?

text: Assume a simple class that implements the Tester/Doer pattern:               public class FooCommandHandler : ICommandHandler     {         public bool CanHandle(object command)         {             return command is FooCommand;         }              public void Handle(object command)         {             var fooCommand = (FooCommand)command;             // Do something with fooCommand         }     }      Now, if someone doesn't conform to the pattern and calls `Handle` without verifying the command via `CanHandle`, the code in `Handle` throws an exception. However, depending on the actual implementation of `Handle` this can be a whole range of different exceptions. The following implementation would check `CanHandle` again in `Handle` and throw a _descriptive_ exception:               public void Handle(object command)     {         if(!CanHandle(command))             throw new TesterDoerPatternUsageViolationException("Please call CanHandle first");              // actual implementation of handling the command.     }      This has the advantage that the exception is very descriptive.   It has the disadvantage that `CanHandle` is called twice for "good" clients. Is there a consensus on which variation should be used?


title: Have you read "Free Software Programmed in Haskell"? What did you think?

text: Does anyone know anything about this book? There are no reviews and it doesn't look like it's still in print or something?


title: Scripting custom drawing in Delphi application with IF/THEN/ELSE statements?

text: I'm building a Delphi application which displays a blueprint of a building, including doors, windows, wiring, lighting, outlets, switches, etc. I have implemented a very lightweight script of my own to call drawing commands to the canvas, which is loaded from a database. For example, one command is `ELP 1110,1110,1290,1290,3,8388608` which draws an ellipse, parameters are 1110x1110 to 1290x1290 with pen width of 3 and the color `8388608` converted from an integer to a `TColor`. What I'm now doing is implementing objects with common drawing routines, and I'd like to use my scripting engine, but this calls for `IF/THEN/ELSE` statements and such. For example, when I'm drawing a light, if the light is turned on, I'd like to draw it yellow, but if it's off, I'd like to draw it gray. My current scripting engine has no recognition of such statements. It just accepts simple drawing commands which correspond with `TCanvas` methods. Here's the procedure I've developed (incomplete) for executing a drawing command on a canvas:               function DrawCommand(const Cmd: String; var Canvas: TCanvas): Boolean;     type       TSingleArray = array of Single;     var       Br: TBrush;       Pn: TPen;       X: Integer;       P: Integer;       L: String;       Inst: String;       T: String;       Nums: TSingleArray;     begin       Result:= False;       Br:= Canvas.Brush;       Pn:= Canvas.Pen;       if Assigned(Canvas) then begin         if Length(Cmd) > 5 then begin           L:= UpperCase(Cmd);           if Pos(' ', L)> 0 then begin             Inst:= Copy(L, 1, Pos(' ', L) - 1);             Delete(L, 1, Pos(' ', L));             L:= L + ',';             SetLength(Nums, 0);             X:= 0;             while Pos(',', L) > 0 do begin               P:= Pos(',', L);               T:= Copy(L, 1, P - 1);               Delete(L, 1, P);               SetLength(Nums, X + 1);               Nums[X]:= StrToFloatDef(T, 0);               Inc(X);             end;             Br.Style:= bsClear;             Pn.Style:= psSolid;             Pn.Color:= clBlack;             if Inst = 'LIN' then begin               Pn.Width:= Trunc(Nums[4]);               if Length(Nums) > 5 then begin                 Br.Style:= bsSolid;                 Br.Color:= Trunc(Nums[5]);               end;               Canvas.MoveTo(Trunc(Nums[0]), Trunc(Nums[1]));               Canvas.LineTo(Trunc(Nums[2]), Trunc(Nums[3]));               Result:= True;             end else             if Inst = 'ELP' then begin               Pn.Width:= Trunc(Nums[4]);               if Length(Nums) > 5 then begin                 Br.Style:= bsSolid;                 Br.Color:= Trunc(Nums[5]);               end;               Canvas.Ellipse(Trunc(Nums[0]),Trunc(Nums[1]),Trunc(Nums[2]),Trunc(Nums[3]));               Result:= True;             end else             if Inst = 'ARC' then begin               Pn.Width:= Trunc(Nums[8]);               Canvas.Arc(Trunc(Nums[0]),Trunc(Nums[1]),Trunc(Nums[2]),Trunc(Nums[3]),                 Trunc(Nums[4]),Trunc(Nums[5]),Trunc(Nums[6]),Trunc(Nums[7]));               Result:= True;             end else             if Inst = 'TXT' then begin               Canvas.Font.Size:= Trunc(Nums[2]);               Br.Style:= bsClear;               Pn.Style:= psSolid;               T:= Cmd;               Delete(T, 1, Pos(' ', T));               Delete(T, 1, Pos(',', T));               Delete(T, 1, Pos(',', T));               Delete(T, 1, Pos(',', T));               Canvas.TextOut(Trunc(Nums[0]), Trunc(Nums[1]), T);               Result:= True;             end;           end else begin             //No space found, not a valid command           end;         end;       end;     end;      What I'd like to know is what's a good lightweight third-party scripting engine I could use to accomplish this? I would hate to implement parsing of `IF`, `THEN`, `ELSE`, `END`, `IFELSE`, `IFEND`, and all those necessary commands. I need simply the ability to tell the scripting engine if certain properties meet certain conditions, it needs to draw the object a certain way. The light example above is only one scenario, but the same solution needs to also be applicable to other scenarios, such as a door being open or closed, locked or unlocked, and draw it a different way accordingly. This needs to be implemented in the object script drawing level. I can't hard-code any of these scripting/drawing rules, the drawing needs to be controlled based on the current state of the object, and I may also wish to draw a light a certain shade or darkness depending on how dimmed the light is.


title: How to approach web app development?

text: I have been going through Flask and it seems that now I have a decent understanding to go ahead and build a web application. However I want to know how would I approach the problem. For eg: I decide to build a blogging application. The first thing I do is write down all the things that come to my mind, from user registrations to posting data on the blog to publishing it on the site But after that I just get into coding. I know that is not the right approach. I have heard of UML diagrams, workflow diagrams and stuff. It would be great if someone could just outline the steps they would follow for building a large application and then I could go ahead and learn more about them.For eg,it could be something like the below:-   1. Collect requirements   2. Draw UML diagrams   3. Draw workflow diagrams   4. Start coding Please suggest an exhaustive list so that I can make my approach much more systematic. Thanks


title: Opinion and help of the following job interview questions

text: I'm not familiar with job interview and software development terminology. So my questions are: what's your opinion of the following job interview questions and what is the best way to respond, especially the last question he asked? The new employer offered me a job consisting in building very rich interactive web apps in Paris. The questions on which I like to know your opinions are: 1) What kind of salary do you expect? 2) Are you ok to work in a Startup? (What does it means?) 3) Do you know about iterative development processes? (What does it means? maybe working with many developers.) 4) Lean methodology? (What does it means?) 5) We are building a strong web culture, how can you help? Thanks for your help.


title: Design question about a concurrent forking server

text: I'm in the early stages of designing a client/server application. The clients will be batch programs that read a file of customer contact data (name, address, email address, phone no's) and pass these components to the server, which will add them (if not already present) to corresponding mySQL tables and return id's for each component. In order to boost performance, the server will have spawned four "manager" servers, each tasked with looking up and possibly adding a new row, and will pass the four components via IPC to those managers so that they can work concurrently. In other words   * One "master server" that does nothing but listen for a connection from a batch job, and fork/exec a "slave" process,    * Four "managers" that read from a socket, do a table lookup and possibly add a row, and write back an id,   * One "slave" process for each connected client, spawned by the master when a new connection arrives from a client, which converses with the batch job: receiving a customer contact record, sending components to each of the managers, waiting for all of the managers to respond with the id's they've computed, and sending a summary record back to the client before looping back to receive the next record. (The processing is a bit more involved than I've described- there are actually _eight_ managers, and the results from the first four need to be completely gathered before invoking the next three managers, which in turn must all complete before calling the final manager. But that's just a simple process with several sequential stages, each of which involves farming out concurrent work and waiting for it all to finish.) In discussing this with another member of the team, I was asked "why have the master server and the slave servers? why not have the client make separate connections directly with those manager processes?" I haven't got a really good objection: each client _could_ essentially implement the slave logic directly and create eight simultaneous connections to the manager servers. I have a feeling that's not the best approach - that somehow it might be important to have some centralized control to robustly deal with failures and errors, or to accumulate statistics about the server as a whole. But I've no prior experience building a full-scale, production-worthy client/server app. I'd be very interested in hearing the opinions of those with prior experience building apps of this nature. **UPDATE 1:** One advantage: If the client process abruptly crashed or was canceled, the slave process would stay alive, could detect that the client had gone away, would have complete knowledge of the job state, and could ensure data integrity by completing (or backing out) the current unit of work. It could bring an orderly end to a failure.


title: Does multiple inheritance violate Single Responsibility Principle?

text: If you have a class which inherits from two distinct classes, does not this mean that your subclass automatically does (at least) 2 things, one from each superclass? I believe there is no difference if you have multiple interface inheritance. Edit: To be clear, I believe that if subclassing multiple classes violates SRP, then implementing multiple (non-marker or basic interface (e.g. Comparable)) interfaces violates SRP too.


title: Developing software for a company outside a company

text: I work for an IT company as a developer. We are currently working on a large software project, a multi-vendor automatic database clustering solution. We've upheld good coding standards and as a result our code is highly modular and reusable. Many of the modules we've developed could be of great benefit to the open-source community. There are quite a few developers on our team that contribute to various open- source projects but so far we have not been successful with persuading the employer to consider open-sourcing some of the modules. A few of us decided that we'd like to contribute code to open-source community while at the same time develop code for the company. Since our employer is not sympathetic towards this cause, contributing code we write during work hours is probably not an option. We have decided to take an alternate approach, write code during our spare time that we can use for both the company and open-source community. We would like to know what are the caveats of this approach, pottential legal issues and whether someone has a similar experience so we could elaborate our plan further before putting it on the table at work.


title: How should I be keeping track of php script version/changes?

text: How should I be keeping track of a php script's versions/changes when it pertains to a single script in one file? Should I have a separate changelog, and if so (1) what should it be named, (2) how should the contents of the log be formatted, and (3) how should the log be associated with the php script/file? Or, should I include the changes in a comment at the top of the php file? Currently, I have the following comments at the top of the file: `               /**      * @author    John Doe <contact@John Doe.com>      * @version   1.0      * @copyright Copyright (c) 2010, John Doe      */      ` Thanks in advance for your response!


title: Mingling DB transactions and logging from a design perspective

text: Say we have a view page where users perform actions in multiple steps, some of these actions would involve DB operations with transactions (the snippets are in pseudo-code like from):               View 1:         Step 1:             ...              Step 2:             ...             Call ActionX              Step 3:             ...              ActionX: # can be called from different points in the view         ...         Begin Transaction         DB ops         End Transaction      Say we want to log the user progress in the view (or save some states) in a persistent manner in the DB, so that if the program/app is interrupted we can re-establish the state to the last user action inside a view:               View1:         Step 1:             ...             Logger.log('view1-step1-done')              Step 2:             ...             Call ActionX             Logger.log('view1-step2-done')              Step 3:             ...             Logger.log('view1-step3-done')      Now ideally, we would want to have the persistent logging and the DB based transactional actions to be both done in the same DB transaction, because we don't want to create an inconsistent state where an action is performed but is not reflected in the log state, or vice versa. The question is: how to achieve the said goal with minimum inter-dependency and SOC. Some suggestions for example:               View 1:         Step 1:             ...              Step 2:             ...             Begin Transaction             Call ActionX    # begin/end transaction statements will be removed from ActionX             Logger.log('view1-step3-done')             End Transaction              Step 3:             ...      Don't like this because the handling of transactions belongs naturally in the action itself. Or, another one:               View 1:         Step 1:             ...              Step 2:             ...             Call ActionX (logMsg='view1-step3-done')               Step 3:             ...          ActionX (logMsg):          ...         Begin Transaction         DB ops         Logger.log(logMsg)         End Transaction      Don't like this one either. The log message handling doesn't belong in the actions.


title: Why fewer IRQLs in 64-bit, even though an APIC has more interrupt lines?

text: As x86 computers shifted from 32-bit to 64-bit, they also shifted from using 8259-style Programmable Interrupt Controllers with 8 interrupt lines. (Or two multiplexed PICs for a total of 15 interrupt lines.) Then, if you were to install 32-bit Windows for an operating system, Windows would implement 32 software IRQLs (Interrupt Request Levels) with IRQLs 3 through 26 (or so) being reserved for devices. Then the x64 platform came along. You need a machine with an APIC, which has 256 interrupt lines, in order to install 64-bit Windows on it. However, 64-bit Windows only implements 16 IRQLs. So my question is, does anyone know why 64-bit Windows would implement fewer IRQLs than its 32-bit counterpart even though it has many more hardware interrupt lines at its disposal?


title: Support / Maintenance documentation for development team

text: I'm working in the Development dept (around 40 developers) for a large E-Commerce company. We've grown quickly but have not evolved very well in the field of documenting our work. We work with an Agile / Scrum-like methodology with our development and testing but documentation seems to be neglected. We need to be able to make documentation that would aid a developer who hasnt worked on our project before or was new to the company. We also have to create more high level information for our support department to explain any extra config settings and fixes of known issues that may arise, if any. Currently we put this in a badly put together wiki, based on an old Sharepoint / TFS site. Can anyone suggest some ideal links or advice on improving the documentation standard? What works in other companies? Has anyone got avice on developing documentation as part of an agile process? Many thanks, ben


title: Should debug code be left in place, always, or added only when debugging and removed when the bug has been found?

text: I, for one, only add debug code (such as print statements) when I'm trying to locate a bug. And once I've found it, I remove the debug code (and add a test case which specifically tests for that bug). I feel that it's cluttering the real code and therefore has no place there unless I'm debugging. How do you do it? Do you leave the debug code in place, or remove it when obsolete (which may be difficult to judge when that is)?


title: What should plugins use: hooks, events or something else?

text: Consider an app that allows plugins to react to its program flow. I know 2 ways to achieve this: **hooks** and **events** **1\. Hooks** Use calls to empty functions inside the main program flow. These functions can be overriden by plugins. For example, Drupal CMS implements hooks which are available to modules and themes. Here's an example of how hook is implemented in a file_copy function.               function file_copy(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {         // ... [File copying routine]              // Inform modules that the file has been copied.         module_invoke_all('file_copy', $file, $source);              return $file;         // ...     }      A module can implement a `modulename_file_copy($file, $source)` function which will be called by the `module_invoke_all` in `file_copy`. After this function finishes, the `file_copy` will resume execution. **2\. Events** Have the app dispatch events, which can be listened to by the plugins. After receiving an event that it's been subscribed to, a plugin will intercept the program flow and perform neccessary operations. For example, a jQuery gallery plugin Fotorama implements several events. As an example, here's a part of its `show` method that fires the `fotorama:show` event.                 that.show = function (options) {         // ... [show the new frame]              // [fire the event]         options.reset || triggerEvent('show', {           user: options.user,           time: time         });              // ... [do lots of other stuff with navigation bars, etc.]       };      A script can listen to this event and do something when it fires:               $('.fotorama').on(       'fotorama:show',       function (e, fotorama, extra) {         console.log(e.type + (extra.user ? ' after user’s touch' : ''));         console.log('transition duration: ' + extra.time);       }     );      **QUESTION**   1. Are there other mainstream ways to implement such plugin behaviour?   2. If not, when should one use hooks, and when should one use events? Considering the ultimate goal is to make the code **more maintanable and readable, from both the app and the plugin developer's perspective?**


title: What are important things to remember when reengineering a legacy application?

text: About to embark on the initial phases of a project to rewrite a legacy application from the ground up (existing business rules will change somewhat, and be extended to incorporate a large number of new requirements that the existing infrastructure cannot handle). I am looking for items that are important to remember when working to reengineer an existing application.


title: From programmer to programmers coach

text: Coming from a "standalone" programmer job, which methods or tools do you use when the time has come to have to drive a team of programmers as project manager (but still coding with the crew) to explain, prepare and distribute the work to be done by the team ? So a big project is coming, you're chosen as Lead Programmer, what do you use as method and tools to have the job done by the team ?


title: Does Agile force developers to spend more time actually working?

text: Looking at common Agile practices it seems to me that they (intentionally or unintentionally?) force developers to spend more time actually working as opposed to reading blogs/articles, chatting, coffee breaks and just plain procrastinating. In particular: 1) Pair programming - the biggest work-forcer, just because it is inconvenient to do all that procrastination when there are two of you sitting together. 2) Short stories - when you have a HUGE chunk of work that must be done in e.g. a month, it is pretty common to slack off in the first three weeks and switch to OMG DEADLINE mode for the last one. And with the little chunks (that must be done in a day or less) it is exact opposite - you feel that time is tight, there is no space for maneuvering, and you will be held accountable for the task pretty soon, so you start working immediately. 3) Team communication and cohesion - when you underperform in a slow, distanced and silent environment it may feel ok, but when at the end of the day at Scrum meeting everyone boasts what they have accomplished and you have nothing to say you may actually feel ashamed. 4) Testing and feedback - again, it prevents you from keeping tasks "99% ready" (when it's actually around 20%) until the deadline suddenly happens. Do you feel that under Agile you work more than under "conventional" methodologies? Is this pressure compensated by the more comfortable environment and by the feeling of actually getting right things done quickly?


title: How does BASIC locate an out-of-order NEXT statement when the loop body is skipped

text: Set the WABAC machine, Sherman. This question is about BASIC in general, and Microsoft's BASIC-80 in particular. Old school basic. With line numbers. How do (or, rather, did) old-school BASIC interpreters handle FOR...NEXT loops when the loop body was not executed, and the NEXT statement appeared out of order? # An out-of-order NEXT statement from the before time: Here's a subroutine from the game Awari out of David H. Ahl's "101 Basic Computer Games":               200 K=M:GOSUB 600     205 E=0:IF K>6 THEN K=K-7     210 C=C+1:IF C<9 THEN F(N)=F(N)*6+K     215 FOR I=0 TO 5:IF B(I)<>0 THEN 230     220 NEXT I     225 RETURN     230 FOR I=7 TO 12:IF B(I)<>0 THEN E=1:RETURN     235 GOTO 220      and here it is with everything except the flow control redacted:               200 GOSUB 600     215 FOR I=0 TO 5:IF ... THEN 230     220 NEXT I     225 RETURN     230 FOR I=7 TO 12:IF ... THEN RETURN     235 GOTO 220      Does that bring back not-so-fond memories? Can you hear Dijkstra rolling over in his grave? Here are the interesting part of what's happening in this fragment:   * The second FOR loop, since it uses the same loop variable, replaces the first FOR loop   * The two FOR loops share the same NEXT statement   * _The second FOR loop's NEXT statement comes before it, in source order, but after it, in execution order_ You might suppose, then, that the interpreter, having started a FOR loop, simply runs statements until it happens across the NEXT loop. The order of the statement in the source does not matter in this case. But let's see what the basic80 manual has to say about FOR loops: # The basic-80 manual says "moo..." > The body of the loop is skipped if the initial value of the loop times the > sign of the step exceeds the final value times the sign of the step. So, the loop body can be skipped entirely. We have evidence, in the form of published programs, that at least some versions of BASIC were dynamically locating their NEXT statements. This is easy enough to do when the loop body is being executed. However, in the case where the body of the FOR statement should be skipped, as BASIC-80 permits, how did BASIC locate the NEXT statement, given that it might be _before_ the FOR statement in source order?   * Did the version of BASIC used in "101 Basic Computer Games" always execute the loop body at least once?   * Did BASIC-80 require a FOR loop's NEXT statement to occur after the FOR statement, in source order? PS: Yes, I'm writing a BASIC interpreter for old school BASIC. It's a sickness.


title: Which programming designs leads to more problems?

text: As a fresh programmer, one of the first thing for me to learn was to learn language and its syntax. Now my next training issue is to design my code heirarchy in such a way it is simple to maintain over time. One example I just encountered is below. It is in VBA for Excel but the concept extends to other languages too. As someone with very little experience, it seems to me that the 2nd option is much clearer and I should use that style. However, I know sometimes that to a beginner programmer what seems like a relatively benign choice can end up hurting their development in the long run. Are either of these two styles the better? I am not talking about personal 'stylistic' choices, I am talking about which one leads to more problems down the line, likely through over-complicating things.               For ws in Worksheets         remove duplicates         append remaining data to separate workbook     Next ws      versus               For ws in Worksheets         remove duplicates     Next ws          For ws in Worksheets         append remaining data to separate workbook     Next ws      Thankyou! EDIT: By the way, it is not important if the less-readable design style is faster. A small increase in performance is not worth a loss of readability for my purposes at the moment.


title: Challenging Job after Graduate Studies

text: I worked with an M.N.C developing web applications in Java/J2EE related technologies(includes JSF,struts,hibernate etc.) now I quit my job to pursue Graduate Studies in the U.S.A. So I am a student in the middle of my Graduate studies. I had enough of developing mere CRUD applications in J2EE now I want to work in something exciting. The problem is I can't say what exactly but I can give you an examples. Say developing new JDK libraries or writing a kernel for some O.S. or something like that. So I have five questions here.   1. Is it true that people in R & D often use C++ because of higher performance in that case should I consider switching my platform to C/C++?   2. How should I use my time I have one year to graduate to prepare myself for Jobs Interviews for such positions? (e.g. Reading books on Algorithms etc.)    3. How do I know about these jobs and how do I apply to those Jobs?   4. Is it the right time for me to think about Jobs?   5. Am I over ambitious because I am not in a Ivy League, just a normal school? (My GPA is not so high unfortunately).


title: How To Handle Login For An Unofficial API?

text: I am building a tool to access some data on a site (Fitocracy) and I would like to turn it into an unofficial partial API, as no official API exists. If you are not logged in, you cannot get access to any data, so my tool uses Ruby's mechanize to log in (with my account) and scrape some data from a page. How should I handle this when I turn it into an API? I am worried that people won't feel comfortable sending their login credentials through an unofficial API and I don't want to just circumvent the login to the site by giving everybody access through a dummy account.


title: Extreme Programming - documenting implementation?

text: In extreme programming methodology, what artifacts/ can be used to document the implementation? I have used an activity diagram to document the design steps for each activity. I have read that for XP, the implementation chapter is the code itself. I am developing an android application which consists of the GUI and java coding.


title: What methods of requirements elicitation are suitable when I do not have direct access to the user base?

text: I am working on an application to create invoices. There are some features that are required based on the type of the application and are common to all invoice applications. However, we still need to determine what unique needs the user base might have. We do not have direct access to the users to obtain requirements or user stories. What techniques are most suitable for eliciting high-quality requirements from users when direct or frequent access is not possible?


title: How would one go about reading memory from a process? Is it different by OS?

text: As an experienced web-developer, but a novice "low level" programmer, this stuff is sort of voodoo to me still. I'm curious about how one would even begin to go about finding a memory block, and then reading it (for example, reading the timer in a game of mines)? Is this different by OS / OS version? I've spent quite a bit of time Googling and unfortunately, other than some vague mentions of memory readers and `ReadProcessMemory` in Windows with C/C++, there's not a whole lot out there. Would be very happy if someone could shed some light on this subject so that I could get off on the right foot with respect to memory reading.


title: Why do we keep using CSV?

text: Why do we keep using CSV? I recently made a shift to working the health domain and despite the wonderful work in data transfer standards, all data transfer is in **CSV** , both for reporting to external organisations, and for data migrations when implementing new systems. Unfortunately the use of CSV is the cause of the endless repetition of the same stupid errors, with the same waste of developer time. (bad escaping, failing to handle null fields etc.) I know we can do better, and anything between JSON and XML (depending on the instance) would be fine. (Most of the time this is data going from one MS SQLserver 2005 to another!) I feel as if each time I see this happening I am literally watching one developer waste anothers time. So why do we keep shafting each other? When will we stop?


title: How do I support interfaces for different devices in the same input scenario?

text: I asked this question on SO but someone pointed out that I would be better off here. He's most likely right. So here I go! So I just wanted an opinion. I have 2 different ways to approach the problem. Okay so I have a system that I wanna design toward the future. I have some types of objects wich takes as parameters an object implementing an Interface wich can itself contain another object Implementing another interface and so on. In this way i have               A(InterfaceB B)->B(InterfaceC C)->C(InterfaceD D) ... Until i get to a point where the object does not contain another one. Every interfaces implement a common interface. So I have               Parent->InterfaceB   ---   Parent->InterfaceC   ---   Parent->InterfaceD But InterfaceD does not necessarily implement InterfaceB. Because an interface does not have only one implemention, I have multiple possible trees.               A(InterfaceB B)->B(InterfaceC C)->C(InterfaceD D)->... and               A(InterfaceB B)->B(InterfaceC Y)->Y(InterfaceZ Z)->... So my question is this : If i want to manage the possible trees, Am I better off using reflection to generate the possible trees on startup? Or would I be better off to hold the different trees in a xml file that I would parse on startup? I have to keep in mind that those Interface types and their implementations will keep coming on. So every time I add a new type, it has to be managed. I know both solution will work. My question is more like this : What would be the best approach to orient the system toward the future. To add some context to the situation, here's an example of a case All those interfaces expose an adaptor. Each adaptor may need another one to do its task. For instance, I have an adaptor wich parse some data. But then this data has to be communicated with a remote target. To do this it can use ethernet, serial port, etc... So I could have a generic parser wich takes a generic communicator. That's one of the different possibilities. If you need some clarifications dont hesitate!


title: Generate complex (non-convex) polyhedron UV mapping

text: I need to find an approach to the problem of generating texture maps for non- convex polyhedrons without using a design tool like Maya. Specifically, I am mapping simulation results data onto a 3D surface, and I need to write code which generates the maps. One generic approach uses a gradient color brush as an overall texture to just map colors, but if the facets in the polyhedron are very narrow or the mapped (u,v) coordinates are very far apart on the same facet, the image gets noisy. Another approach employs Phong or Gouraud Shading, but those features are missing in some 3D libraries which favor texturing over specifying colors at each vertex. So, I'm looking for a way to get a good texture map generated. If it helps in identifying a correct algorithm, all of the surfaces entirely enclose a 3-D space, there is no facet normal data, and I'll be able to identify a "parting line" which segregates one part of the surface from the other, as one might in order to create a mold for the shape.


title: Detect Order Changes in a List

text: Let's say you have a list of values that are   1. a   2. b    3. c   4. d   5. e The order on the list might be changed.   1. a    2. c   3. d   4. **b**   5. e How would you detect this change? We needed something like this when we were building a revision history page for our online form building tool. We found a quick and dirty solution but I am looking for a more elegant solution for this. Here is what the revision descriptions look like: ![jotform revisions page](http://i.stack.imgur.com/QKuTx.png) Here is the tough part: **Elements can be removed/added from/to anywhere on the list.** So, the algorithm should be able to ignore those changes.