Potentially justifiable use case for const_cast or bad design?

I'm designing a data structure in C++, and I want to expose an interface to the user to traverse the structure in some order. Instead of creating several different types of enumerators, I want to keep it simple and provide a single enumerator, while maintaining const-correctness. My design is summarised as follows:               class DataStructureNode; // The basic building block of the structure          class DataStructureEnumerator     {     public:              friend class DataStructure;              DataStructureEnumerator GetNext() { ... }         DataStructureEnumerator GetPrevious() { ... }          private:              const DataStructureNode* m_Node;         ...     };          class DataStructure     {     public:              DataStructureEnumerator GetEnumerator() { ... }              DataStructureNode* GetNodeFromEnumerator(const DataStructureEnumerator& e)         {             // Let's assume this function also ensures the node belongs to this structure             return const_cast<DataStructureEnumerator&>(e).m_Node; // <--- Ooo! const_cast!         }              const DataStructureNode* GetNodeFromEnumerator(const DataStructureEnumerator& e) const         {             // Let's assume this function also ensures the node belongs to this structure             return e.m_Node;         }     };      This design has the benefit that there is only one type of enumerator that handles both mutable and immutable structures. Of course, the alternative (and the conventional) design in C++ is to have two (or more) enumerator classes, such as `DataStructureEnumerator` and `DataStructureConstEnumerator`. The conventional design comes with added code- bloat, more templates, and an uglier interface (in my opinion!), but it's the norm in C++ communities. I'm interested in hearing opinions of the community on this design. Are there any potential pitfalls that I'm missing with my design?


Dynamic programming in Bin packing

**Problem:** Given a list L of objects of possible sizes from set S={1,2,4,8} and unlimited supply of bins of sizes 16 each and we have to use minimum possible numbers of bins to pack all objects of L.   I am also searching for an optimal (or near optimal) solution using dynamic programming or otherwise in the following scenarios when   1. L is not given offline, instead we are asked to fit objects one by one without knowing future requests(1-D online vector bin packing).   2. sizes can be from SXS and bins are of capacity (16,16) each. (2-D vector bin packing). **Assumption:** Optimal packing means the best possible packing from all possible packing i.e the packing with the minimum numbers of bins used.   Actually generalized vector bin packing is NP-hard, but I think due standard sizes from finite set, more efficient and better solutions may exist. **My approach:** Clearly, 1-D offline can packed in <=optimal+1 using clever pairing of objects .   But I am stuck for the other 2 aspects asked above.   I know about First Fit,Best Fit, First Fit Decreasing algorithms but I am searching for this problem specific solution.


Automating database deployment using a CMS

My team are developing Umbraco websites and looking to improve the automation of our database deployment. Currently we have automated builds and deployments of our source code using Kiln and Team City, but cannot work out how to handle the database deployment. The challenge is applying changes made in the development environment, while keeping new database content that has been added in the live environment via the CMS. Currently our changes are deployed using courier manually, but we aim to convert this into a '1 click deployment' which is what we desire for running our automated tests and ease of deployment. How can we automate this without wiping new content added in the CMS?


Can you be Agile without doing TDD (test driven development)?

Is is possible to correctly call yourself (or your team) "Agile" if you don't do TDD (Test-Driven Development)?


Approach for packing 2D shapes while minimizing total enclosing area

Not sure on my tags for this question, but in short .... I need to solve a problem of packing industrial parts into crates while minimizing total containing area. These parts are motors, or pumps, or custom- made components, and they have quite unusual shapes. For some, it may be possible to assume that a part === rectangular cuboid, but some are not so simple, i.e. they assume a shape more of that of a hammer or letter T. With those, (assuming 2D shape), by alternating direction of top & bottom, one can pack more objects into the same space, than if all tops were in the same direction. Crude example below with letter "T"-shaped parts:               ***** xxxxx      ***** x        *****       *** ooo       *     x    vs    *   x    vs    * x   vs   * x o       *     x          * xxxxx        * x        * x o                                       xxxxx       xxx      Right now we are solving the problem by something like this:   1. using CAD software, make actual models of how things fit in crate boxes    2. make estimates of actual crate dimensions & write them into Excel file (1) is crazy amount of work and as the result we have just a limited amount of possible entries in (2), the Excel file. The good things is that programming this is relatively easy. Given a combination of products to go into crates, we do a lookup, and if entry exists in the Excel (or Database), we bring it out. If it doesn't, we say "sorry, no data!". I don't necessarily want to go full force on making up some crazy algorithm that given geometrical part description can align, rotate, and figure out best part packing into a crate, given its shape, but maybe I do.. **Question** Well, here is my question: assuming that I can represent my parts as 2D (to be determined how), and that some parts look like letter T, and some parts look like rectangles, which algorithm can I use to give me a good estimate on the dimensions of the encompassing area, while ensuring that the parts are packed in a minimal possible area, to minimize crating/shipping costs? Are there approximation algorithms? Seeing how this can get complex, is there an existing library I could use? **My thought / Approach** My naive approach would be to define a way to describe position of parts, and place the first part, compute total enclosing area & dimensions. Then place 2nd part in 0 degree orientation, repeat, place it at 180 degree orientation, repeat (for my case I don't think 90 degree rotations will be meaningful due to long lengths of parts). Proceed using brute force "tacking on" other parts to the enclosing area until all parts are processed. I may have to shift some parts a tad (see 3rd pictorial example above with letters T). This adds a layer of 2D complexity rather than 1D. I am not sure how to approach this. One idea I have is genetic algorithms, but I think those will take up too much processing power and time. I will need to look out for shape collisions, as well as adding extra padding space, since we are talking about real parts with irregularities rather than perfect imaginary blocks. I'm afraid this can get geometrically messy fairly fast, and I'd rather keep things simple, if I can. But what if the best (practical) solution is to pack things into different crate boxes rather than just one? This can get a bit more tricky. There is human element involved as well, i.e. like parts can go into same box and are thus a constraint to be considered. Some parts that are not the same are sometimes grouped together for shipping and can be considered as a common grouped item. Sometimes customers want things shipped their way, which adds human element to constraints. so there will have to be some customization.


How do programmers handle several versions of a same program?

A lot of apps, for instance, have a free version and pro version. Do programmers, when a new update is released, remove lines of code that shouldn't be available in the free version? As for Visual Studio. Or demos. Or a lot of things actually.


Developing an internet-enabled application as a Kiosk on Windows 7

I am finalizing development of a desktop Java application that communicates with an outside web server, and now I need to start seriously considering deployment. This application will run on a large touchscreen all-in-one workstation running Windows 7. It will be located in a public-area and thus must be LOCKED-DOWN Hanibal Lecter style. Early in the project nobody really concerned themselves with this fact just assuming that we can buy some magical software for Windows 7 that will automatically take care of all this, however I am finding now that this looks to be a LOT more complicated than my manager ever thought. I need to: \- Lock down the standard hot-keys (ALT+TAB, ALT+CTRL+DEL, etc...)   * Prevent the user from opening ANY programs other than the kiosk application and its spawned executables   * Prevent the user from closing the application   * Start the kiosk application on startup (this can be done without kiosk software)   * Auto-login to Windows on reboot (Windows Updates, power failure, bratty kid pressing the power button, etc...)   * Administrator passcode escape sequence for routine maintenance by desktop support professionals. To my dismay I am having a really hard time finding software that contains the whole package and am finding numerous swaths of competing information on the best way to do this. I am not necessarily looking for free or open source software and am willing to pay for software that can help me achieve this. Have any of you ever wrote kiosk software before and if so what approaches have you taken to do this?


Remake old web forms application in asp.net mvc

I've inherited the code maintenance of a complex web site for a customer that continuously requests enhancements for it. This application took years to develop and I'm facing increased difficulties to enhance it. It's organized but at the same time the .net code is mixed with ajax, javascripts and old school html that it takes me days to figure out how some pages work. First off, I not new to asp.net but I'm not familiar with the new MVC stuff but from what I've read it seems to be a step in a better direction. The current code is all in one big dll. The application code is divided into multiple folders representing the different departments and each department has it's own pages for handling general stuff like employee management, reports, budget and also their own information. For example, even though each department uses a different webpage for employee information handling, they want different fields and so it was simpler to create different pages than to use a single page that adapts to each department. But it is really a nightmare to maintain right now and I would like to create a parallel project where I could start a fresh project, create a better structure and from there start migrating the old code to this new environment and refactor it as I go. The idea is to migrate the old application to a new web site that has a similar look while maintaining both operating until everything is running in the new site. It may sound insane but it really is used extensively for hundreds of people everyday and it bugs me that I have to modify crappy code to make it work. How would you go about this issue? Thanks [edit] If found this link Things You Should Never Do on another post, very much to the point of my question.


How should I design a wizard for generating requirements and documentation

I'm currently working in an industry where extensive documentation is required, but the apps I'm writing are all pretty much cookie cutter at a high level. What I'd like to do is build an app that asks a series of questions regarding business rules and marketing requirements to generate a requirements spec. For example, there might be a question set that asks "Does the user need to enter their age?" and a follow-up question of "What is the minimum age requirement?" If the inputs are "yes" and "18", then this app will generate requirements that look something like this: "The registration form shall include an age selector" "The registration form shall throw an error if the selected age is less than 18" Later on down the line, I'd like to extend this to do additional things like generate test cases and even code, but the idea is the same: generate some output based on rules determined by answering a set of questions. Are there any patterns I could research to better design the architecture of such an application? Is this something that I should be modeling as a finite state machine?


What are some things to be aware of when getting ready to hand a project off?

I'm current the sole developer/architect of a fairly large web application (ASP.NET MVC stack, roughly 150K+ lines of code) and the end of development is on the horizon. As such, I'm starting to think about what needs to be done for the hand off of the project and I want to make sure I do the right thing for anyone that has to maintain the project in the future. What are some things to be aware of when getting ready to hand a project off to another developer or team of developers of maintenance?


Where can I find better designed nginx documentation?

Actually I have a sub-question here:"Is Nginx official documentation opensourced?" Nginx is a good software, but I found its official documentation(http://nginx.org/en/docs/ really hard to read, because lack of design. Especially compare with documentations on this site (readthedocs.org). So I decided to move it to readthedocs.org little by little if it's opensourced. And I'm so confused that as the 2nd biggest web-server software on world, aren't there anyone else like me feel its documentation hard to read? Maybe there are many and I just don't know them. If you know any other site which have a better designed nginx documentation, please tell me, so I won't need to do the rebuild task.


What is the required background to apply Machine Learning to Finance?

I'm interested in machine learning in relations to the stock market (predicting future values of stocks etc). What topics would I need to learn - e.g. what branch of AI to look into etc? and what libraries/tools do I need?


Avoid malicious code while dynamically loading classes with ClassLoader

## Background One of the advantages of decoupled components in systems is that you can extend the system without having to touch the existing code. Sometimes you don't even have to recompile the old code because you can dynamically load classes from disk like this:               clazz = Demo.class.getClassLoader().loadClass("full.package.name.to.SomeClass");      That allows for a kind of plug-in architecture of sorts (give or take). ## Question How do you prevent malicious code from running when dynamically loading a class from disk using `ClassLoader` ?


Programming style: Reoccuring error checks

Hey, I have a question about programming style, because in my current code I am using a bigger function which calls some smaller functions and all of these need to be error-checked. So something like this:                void bigFunction() {           /* some computations */           if(smallFunction1() == -1) {                free(mem1);                free(mem2);                fclose(file);                unlink(filename);                return -1;           }           if(smallFunction2() == -1) {                free(mem1);                free(mem2);                fclose(file);                unlink(filename);                return -1;           }             if(smallFunction3() == -1) {                free(mem1);                free(mem2);                fclose(file);                unlink(filename);                return -1;           }           /* more computations and stuff in biggerFunction */      }      I think you can clearly see my problem: The code after one of these functions fails is always the same, and I feel like repeating this coder again and again will make my code more and more unreadable. How to deal with this problem? gotos came into my mind, but in my programming courses in university I was told never use gotos (though I forget the reason why...)


Project problems from a Java beginner

A week ago I asked the question; First big project, how to get started. Make menus, save to harddrive etc. I tried to do everything without doing a GUI with Swing but I realized that for every view I wanted to present to the user I had to make a new class. Right now I have 3 menu classes (the mainMenu, computerCategoryMenu,laptopCategoryMenu) I stopped because I would need to make another 6 menu classes and then another 6 if the user registered and another 6 for the administrator of the site. It doesn't look right to me. Furthermore everything looks too static for me. I don't know how to make the administrator add or delete products. Should I store all my products in a hashmap and then get them to show in different menus? Do you think that doing a GUI with Swing will make things much easier?


Tiling Problem Solutions for Various Size "Dominoes"

I've got an interesting tiling problem, I have a large square image (size 128k so 131072 squares) with dimensons 256x512... I want to fill this image with certain grain types (a 1x1 tile, a 1x2 strip, a 2x1 strip, and 2x2 square) and have no overlap, no holes, and no extension past the image boundary. Given some probability for each of these grain types, a list of the number required to be placed is generated for each. Obviously an iterative/brute force method doesn't work well here if we just randomly place the pieces, instead a certain algorithm is required. 1) all 2x2 square grains are randomly placed until exhaustion. 2) 1x2 and 2x1 grains are randomly placed alternatively until exhaustion 3) the remaining 1x1 tiles are placed to fill in all holes. It turns out this algorithm works pretty well for some cases and has no problem filling the entire image, however as you might guess, increasing the probability (and thus number) of 1x2 and 2x1 grains eventually causes the placement to stall (since there are too many holes created by the strips and not all them can be placed). My approach to this solution has been as follows: 1) Create a mini-image of size 8x8 or 16x16. 2) Fill this image randomly and following the algorithm specified above so that the desired probability of the entire image is realized in the mini-image. 3) Create N of these mini-images and then randomly successively place them in the large image. Unfortunately there are some downfalls to this simplification. 1) given the small size of the mini-images, nailing an exact probability for the entire image is not possible. Example if I want p(2x1)=P(1x2)=0.4, the mini image may only give 0.41 as the closes probability. 2) The mini-images create a pseudo boundary where no overlaps occur which isn't really descriptive of the model this is being used for. 3) There is only a fixed number of mini-images so i'm not sure how random this really is. I'm really just looking to brainstorm about possible solutions to this. My main concern is really to nail down closer probabilities, now one might suggest I just increase the mini-image size. Well I have, and it turns out that in certain cases(p(1x2)=p(2x1)=0.5) the mini-image 16x16 isn't even iteratively solvable.. So it's pretty obvious how difficult it is to randomly solve this for anything greater than 8x8 sizes.. So I'd love to hear some ideas. Thanks


Undefined behaviour in Java

I was reading this question on SO which discusses some common undefined behavior in C++, and I wondered: does Java also have undefined behaviour? If that is the case, then what are some common causes of undefined behaviour in Java? If not, then which features of Java make it free from such behaviours and why haven't the latest versions of C and C++ been implemented with these properties?


HP openview servicedesk: looking for api information ?

Good day folks. I am very confused in this situation. I need to implement system which will be based on HP open view service desk 4.5 api. But this system are reached the end of supporting period. On oficial site no information available **I am looking an information about this API(articles, samples etc)**. Now i have only web-api.jar and javadoc. Methods in javadoc is bad documented. If you have any info, please share it with me. Thanks. **Second question: there are methods for api(with huge amount of methods) understanding if it not documented or information is not available?** PS:If it question is not belong here i will delete it.


Could Apple and Microsoft allow the GPLv3 on their locked-down devices?

It seems that both Apple and Microsoft prohibit GPLv3-licensed software in the app stores for their locked-down devices (i.e. iOS, Windows Phone and the Metro part of Windows). I have heard various explanations for this. However: Would they even be able to allow this license in their app stores if they wanted to, or does the GPL's anti-tivoization clause already prohibit this?


Studies on breakdown of various costs associated with a Software project

I am looking for links and advice on studies done on the breakdown of costs associated with Software development. In particular I am looking on what percentage of effort is testing vs programming, and how it changed with team sizes, duration of project and similar factors.


In what practical ways is it good to remember the memory/pointers model?

A variable refers to a value. A variable is also stored in a memory address. People say that it's good to have this memory model in mind. Is that true? What is some sample code that shows this as beneficial in practice? You dont have to use programming, you can use a real-world analogy if you like. edit: they keep removing the helpful answer i summed up here -- no idea why


Is it possible to refactor inheritance to composition when virtual methods are called inside the base class?

Let's say I have a class called Country and two subclasses called AI and Player. The Country class has a number of virtual methods to allow player- specific or AI-specific behavior. I want to make it possible for the player to switch countries during a game. To this end, I am refactoring the inheritance relation to composition. Then I will be able to switch out a Player's internal instance of Country for another at any time. But this brings up a bit of a problem: When an _external_ object attempts to call one of these virtual methods on a Player, it is delegated correctly to the Country method after any appropriate processing has been done. But when an _internal_ Country method calls one of the virtual methods, the code in the Player or AI version no longer has a chance to run. So now I'm left with updating every one of those methods to make sure both versions are called, which in itself is not a trivial task (infinite loops, anyone?). This seems much harder than it ought to be. I've done similar refactorings before and never run into this issue. Why? Am I missing some blindingly obvious observation? * * * **Edit** for a concrete example now that I have access to the code again:               class Country     {     public:         virtual void AddMoney(float money)         {             _vMoney += money;         }         void TakeLoan()         {             float loan = ...;             AddMoney(loan); // <-- does not route through AI or Player implementation         }     }                    class AI  // : public Country     {     private:         Country *pCountry;          public:         virtual void AddMoney(float x)         {             pCountry->AddMoney(x); // formerly Country::AddMoney(x)             AllocateMoney(x);         }     }


What can I expect when moving from University to a real programming job?

I'm about to move into my final year at university, and it's finally kicked in that in just over a year from now, I'll be doing my best to secure a job. Yet I still have no clue about the level of proficiency expected of graduates trying to make their way into the programming industry. I've read that they'll weed out the non-programmers with some fizzbuzz style questions, but after that, what sort of people am I likely to be up against? And what skills would be worth studying to push myself ahead of the competition? I'm currently trying to get comfortable with inheritance / polymorphism, currently just with my own code, the next task I've set myself is gaining confidence in extending existing code. I've studied PHP, Javascript(+JQuery), Actionscript (and probably some others I can't think of off the top of my head) as hobbies, Java at university, and currently pushing my way through C# (in an attempt to kill two large birds with one stone). Is this panicking undergraduate headed in the right direction? D=


How do I trust an off site application

I need to implement something similar to a license server. This will have to be installed off site at the customers' location and needs to communicate with other applications at the customers' site (the applications that use the licenses) and an application running in our hosting center (for reporting and getting license information). My question is how to set this up in a way I can trust that:   1. The license server is really our application and not something that just simulates it; and   2. There is no "man in the middle" (i.e. a proxy or something that alters the traffic). The first thing I thought of was to use with client certificates and that would solve at least 2. However, what I'm worried about is that someone just decompiles (this is build in .NET) the license server, alters some logic and recompiles it. This would be hard to detect from both connecting applications. This doesn't have to be absolutely secure since we have a limited number of customers whom we have a trust relationship with. However, I do want to make it more difficult than a simple decompile/recompile of the license server. I primarily want to protect against an employee or nephew of the boss trying to be smart.


Good serialization solution for communication between Python AND Haskell programs?

I found this: http://msgpack.org/ But.. I've never used it, so I don't know what whether it is much good. Anybody has proposals? Basic requirements:   * serialize as many data structures used typically in both languages as possible, have no problem with nesting   * as reliable/unbuggy as possible   * high performance is nice to have, but not critical   * as simple as possible to use, but not simpler


Should a domain expert make class diagrams?

The **domain expert** in our team uses UML class diagrams to model the **domain model**. As a result, the class diagrams are more of **technical models rather than domain models** (it serves of some sort of technical specifications for developpers because they don't have to do any conception, they just have to implement the model). In the end, the domain expert ends up doing the job of the architect/technical expert right? Is it normal for a domain expert (not a developer or technical profile) to do class diagrams? If not, what kind of modeling should he be using?


I have a previous invention (software / framework) that I plan to use on my new job. What happens to my copyright if I improve it during the job?

I have filled that standard form where you list your previous inventions before starting your new job so the employer is legally aware you have the copyright over them. But if I want to use this invention (software code / framework) in my new job, would they have any copyright claims on it if for example I change / improve something on my code while working for them? I have heard something like a shared ownership. Something like: you would own what was done before and employer would own any improvements you did on it while employed. That kind of sucks and take away any incentive you would have to do improvements on your product since _once improved, the improvement is gone_. :( Has anyone gone through this situation before and could share some ideas so I can protect my code?


Choosing a open source licence for embedded system library

I'm writing a few libraries that I want to release as open source projects, but I want to find a licence that means I'll receive the credit when it is used in a project. Im not fussed about anything else, if people want to profit off of it then thats fine. So what licence is most appropriate? The only factor for me is that I receive the credit for producing the library if it is ever used.


Composite repository with plugins for multitenant app

Im working on an app that has flexible storage configuration. For example:               public class Repo1:IRepository     {         public void DoSomething(int tenantId, string someKey)         {           ...         }     }      This repo can be combined in Aggreagate or Composite repositories. Also there are connectors to external aplications:               public class Connector1:IConnector     {         public void DoSomething(string someKey)         {           ...         }     }      Connectors are not aware of tenant they are working in, because each tenant has uniquie combination of connectors configured for it. Currently I wrap connectors in special repo implementation:               public class ConnectorRepo:IRepository     {         public void DoSomething(int tenantId, string someKey)         {             var tenantConnectors = ConnectorProvider.GetConnectors(tenantId);             foreach(var connector in tenantConnectors)             {                 connector.DoSomething(someKey);             }          }     }      Basicaly connector and repo are sharing same method signatures, except repo methods have tenantId parameter. I am thinking of making to repository contracts with and without tenantId, and wrap repos without multitenanct support(ex connectors) with tenant aware facades, but such high level abstraction feels fragile to me. Would be very gratefull for any ideas and suggestions.


Is MSDN / Azure Active Directory information available in different formats?

I'd like to read the documentation of Azure Active Directory on my kindle (or similar device), but don't want to use "Print to Kindle" for each and every page. Is the Microsoft documentation for this technology available in other formats? (.chm, PDF, etc). If an alternative format is available, then I can adapt that to my needs. http://msdn.microsoft.com/en-us/library/jj673460.aspx


Understanding dependency injection

I'm reading about dependency injection (DI). To me, it is a very complicated thing to do, as I was reading it was referencing inversion of control (IoC) as well and such I felt I was going to be in for a journey. This is my understanding: Instead of creating a model in the class which also consumes it, you pass (inject) the model (already filled with interesting properties) to where it is needed (to a new class which could take it as a parameter in the constructor). To me, this is just passing an argument. I must have miss understood the point? Maybe it becomes more obvious with bigger projects? My understanding is non-DI (using pseudo code):               public void Start()     {         MyClass class = new MyClass();     }          ...          public MyClass()     {         this.MyInterface = new MyInterface();      }      And DI would be               public void Start()     {         MyInterface myInterface = new MyInterface();         MyClass class = new MyClass(myInterface);     }          ...          public MyClass(MyInterface myInterface)     {         this.MyInterface = myInterface;      }      Could some one shed some light as I'm sure I'm in a muddle here.


How do I create a mature SW design before the implementation itself? And how do I cope with changes?

I am doing a project in my university where, for the first time in my life, I have to create a system architecture/design and I will be the head of a group of 4 students that are in the beginning of the course. Basically, I will be able to do everything: I have almost complete independence to choose what exactly the software should do (goals, features, etc), than I have to design it. Because it is a university project, I do have a lot of time to think about the software concept and design it. My plans are to create a draft of the idea and refine it with the professor. Once we do have a concrete idea, I want to start the SW design itself. And this is the point where my questions arrives: I know that creating a design that contemplates everything and will not change during development is impossible, because of that, I am sure the design will be changed once the implementation begins. However, I want to present a mature design, based in logical decisions and good practices, but, of course, I won't be able to develop the SW to identify the traps I am falling into (this will be the student's task). What tricks do you use to create a mature design and to avoid traps before starting implementing? How do you approach and "study" the software proposal to find inconsistencies or points needing clarification? How do you do to include the changes to your design, without ruining it? (Many of my designs start very nicely, but at the end they are ruined by the changes).


Is Java still king of cross-platform compatibility? Is the answer still Swing?

So basically, my company is looking to create an app that can be distributed on Linux, Mac OS X, and Windows. We are hoping for a cross platform solution. I have experience working with Java Swing years ago and thought it was reasonable, but not great. It assuredly did however work on all platforms just fine. Is Java and Swing still the end all be all of code once run everywhere, or are there other options for desktop apps?


Diagramming messages on a service bus

I'm looking for a way to clearly diagram how multiple applications communicate via a service bus. The best I've come up with so far is a sequence diagram, but I really don't like that. Sequence diagrams necessarily relate some sort of sequence, and that's really not what I want. Furthermore, since every service communicates with the service bus and sequence diagrams place each service on a separate column, as the number of services increases, you end up with a lot of overlapping arrows. For example, given 4 services `FOO`, `BAR`, `BAZ`, and `QUX`:   * `FOO` publishes messages of type _publish_ and _regen_.   * `BAR` publishes messages of type _requeue_.   * `BAZ` subscribes to messages of type _publish_ , _regen_ , and _requeue_ , and publishes messages of type _transmit_.   * `QUX` subscribes to messages of type _transmit_.   * Any service can publish any message type at any time (there is no implied sequence). What kind of diagram should I use to clearly and unambiguously represent this information? Here's the best I've come up with so far:   ![Sequence diagram](http://i.stack.imgur.com/Dhhqg.png)


study materials for Mysql certification?

I'm preparing for MySQL certification, nowadays officially titled:               Oracle Certified Professional, MySQL 5.0 Developer certification      After looking through MySQL forum it looks like most people recommended this book:               http://www.amazon.com/MySQL-5-0-Certification-Study-Guide/dp/0672328127/ref=sr_1_1?ie=UTF8&qid=1299972594&sr=8-1       Which as far as I learned was the official preparation source at the time when MySQL was controlled by MySQL AB and Sun. Now, however - Oracle officially doesn't recommend this book. To be precise, I don't know what they recommend. I could only find this "value package": http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=532 Can someone who got MySQL certification confirm that this book is what they have used? Also, if there is any other moderately priced study materials out there - please let me know. **Update** I passed second one Monday March 28th. I have to say second exam was more complicated. So I have two exams now and waiting for my package from Oracle. Took me approximately 2.5 week total to prepare for both exams. With 0.5 weeks for 1st and 2 weeks for 2nd. Also - to everyone who wants to take it: read the book thoroughly and go through all questions on the CD that comes with that book! This helps immensely. Questions on the exam are very similar to those on the CD.


Metric by which to hold developers accountable

I asked a question on lines of code per hour and got torn a new one. So my matured follow-up question is this: If not lines of code, then what is a good metric by which to measure (by the hour/day/unit-of-time) the effectiveness of remote programmers?


How do you manage a team of software developers?

I am reading the book "Cracking the Sales Management Code", and the book says that sales people can be more or less managed ("measure") by measuring whether they are consistently improving on their Sales Objectives, such as the ability to get new sales, close sales cycle length, deal win/deal lost ratio, hitting sales quota and so on. And I wonder, whether is it possible to manage ( or to measure) software developers in this way? Now I am fully aware that managing people by numbers is a very tricky thing to do; it is very possible for the managers to set the wrong metric, and hence result in the mismanaging of the software developers. But still, I wonder whether this there any books/literature that explores this issue? **Note: When I say I want to "measure" my developers, I don't mean that I want to use the numbers to penalize them or I want to "rank" them. My purpose is simple, I want to have the numbers ( the meaningful numbers) so that I can help them improve their software development skills ( in whatever sense).**


Annual Review: what hard data should a developer bring?

Many companies have annual reviews and/or performance appraisals for their employees. I've heard that it's generally a good idea to muster up some hard data to analyze and bring to the review. The better the data, the better the chances to help support a promotion or raise. What I mean by hard data, are _tangible numbers_ \-- something that can be _measured_ and/or _calculated_. Obviously data that a developer would have access to. Something _intangible_ would be how beautiful the code a developer has written. I think this would be very hard to measure, nor would upper management care for it. My question is: For a software developer, **what kind of hard data should be analyzed and brought to a review to help highlight good work that was done?** An example I've been given in the past: The support tickets produced by each project a developer was involved in. Are the numbers low? Are the rate per month getting lower? Etc.


How to tell whether your programmers are under-performing?

I am a team lead with 5+ developers. I have a developer (let's call him **A** ) who is a good programmer, who writes good clean, easy to understand code. However he is somewhat difficult to manage, and sometimes I wonder whether he is really under-performing or not.   1. Our company requires the developers to indicate the work progress in the bug tracker we use, not so much as to monitor the programmers but to keep the stakeholders apprised of the progress. The thing is, **A** only updates a task progress when it is done ( maybe 3 weeks after it is first worked on) and this leaves everyone wondering what is going on in the middle of the development week. He wouldn't change his habit despite repeated probing. ( It's OK, developers hate paperwork, I do, too)   2. Recent 2-3 months he on leave quite often due to various events-- either he is sick, or have to attend a lot of personal events etc. ( It's OK, bad things happen in a string. It's just a coincidence)   3. We define sprints, or roadmaps for each month. And in the beginning of the sprint, we will discuss the amount of work each of the developers have to do in a sprint and the **developers get to set the amount of time they need for each task**. He usually won't be able to complete all of them. (It's OK, the developers are regularly missing deadlines not due to their fault).   4. I am based in Singapore. Not sure if that matters. Yeah, Asians are known to be reticent, but does that matter? If only one or two of the above events happen, I won't feel that **A** is under-performing, but they all happen together. So I have the _feeling_ that **A** is under-performing and maybe-- God forbid--- slacking off. This is just a feeling based on my years of experience as programmer. But I could be wrong. It is notoriously hard to measure the work of a programmer, given that not all two tasks are alike, and there lacks a standard objective to measure the commitment of a programmer to your company. It is downright impossible to tell whether the programmer is doing his job or slacking off. All you can do, is to trust them-- yeah, trusting and giving them autonomy is the best way for programmers to work, I know that, _so don't start a lecture on why you need to trust your programmers, thank you every much_ \-- but if they abuse your trust, can you know? ## Outcome: I've a straight talk with him regarding my perception on his performance. He was indignant when I suggested that I had the feeling that he wasn't performing at his best level. He felt that this was a completely unfair feeling. I then replied that this was my feeling and I didn't know whether my feeling was right or not. He would have none of this and ended the discussion immediately. Before he left he said that he "would try to give more to the company" in a very cold tone. I was taken aback by his reaction. I am sure that I offended him in some ways. Not too sure whether that was the right thing to do for me to be so frank with him, though. * * * **My question is: How can you tell whether your programmers are under- performing? Surely there are experience team leads who know better than me on this?** * * * ## Extra notes:   1. I hate micromanaging. So all that we have for our software process is Sprint ( where tasks get prioritized and assigned, and at the end of the month, a review of the amount of work done). Developers would require to update the tasks as they go along everyday.    2. There is no standup meeting, or anything of the sort. Mainly because we have the freedom to work from home and everyone cherishes this freedom.    3. Although I am the one who sets the deadline, but the developers will provide the estimate for each tasks and I will decide-- based on the estimate-- the tasks that go into a particular sprint. If they can't finish the tasks at the end of the sprint, I will push them to the next. So theoretically one can just do only 1 or 2 tasks during the whole sprint and then push the remaining 99 tasks to the next sprint and still he will be fine as long as justifies this-- in the form of daily work progress updates


What is an example of a good SMART objective for a programmer?

Following on from this question, I wondered if folk might be able to suggest some samples of what might be considered a "good" objective in a periodic review cycle for a programmer? Let's define SMART from the most popular definitions in the Wikipedia entry:   * Specific   * Measurable   * Attainable   * Relevant   * Time-bound


How to measure team productivity in Agile project environment?

Are there any techniques other than velocity? What are pros and cons of using those from your experience?


How to measure team productivity?

The upper management at our company has laid out a goal for our software team to be “15% more productive” over the next year. Measuring productivity in a software development environment is very subjective, but we are still required to come up with a set of metrics. What sorts of data can we capture that would measure our team’s productivity?


KPI's for Programmers

Do you know any Key Performance Indicators for Developers? What should be measured and monitored?


How can one measure contributions to a project?

Has anyone ever come across this problem? When you have a team of developers working on a project, how can you measure their contributions to said project? Is there a "formal" way of doing it? Number of commits? Number of bug fixes? Lines committed? Or maybe on a ticket basis? I'm trying to think of a workflow where a group of developers can work seamlessly interchanging tasks and at the end of the month, getting paid for they contributions (or merit if you will). I hope this question is not entirely out of place here, if it is, feel free to close it.


How should developer performance be measured?

In many companies there is a formal procedure of reviewing employees' work. For example, a salesperson can stay she'll sell one million units at the beginning of the year. When she comes up for review a year later, she says she's sold two million units. Thus, her manager decides to promote her. But what should developer say? I'll fix a million bugs, I'll write a hundred unit tests? I can't imagine many things that can be measured here, especially If you don't have a roadmap for year and if you working on maintenance. What types of solid performance metrics work for programmers? Or are performance measurements not applicable for developers at all?


How long should I wait to autosave user input?

I have a table where a User can edit data by simply choose a field, then edit its value. I want to fire an update function to automatically save the data to a MySQL database. However, I think that it would be inefficient to fire that function on literally every change, e.g every single keypress. How long should I wait to save my input?


Should developers accept overtime/weekend work/denied bonus payments?

I assume there are many developers in a situation like this:   * you are an employed software architect/engineer   * you are good at your job   * your company needs more good developers than they can find   * there are many options to get a new job or get self-employed   * work is not your first priority (you enjoy family/free time) Aren't we stupid when we still accept overtime/weekend work/denied bonus payments?   I would think employers would need to give in, if we demand better working conditions. What do you think would happen when we all demand better working conditions?


Using module level declared global "singletons" in python

Ok, I know that using singletons is generally a bad practice, but if I do it (for db connection, logging et al.) am I allowed to go (in respect of clean design) with a module defined variable that is initialized during the startup. eg.:               if __name__ == '__main__':         datasources.database.db = DB(dbpath)      where db is declared here, at the top level of a module:               db = None          class DB(object):         def __init__(self, path):              ....      What could be a reasonable compromise between passing the db for each object that uses it in the "true OO way" and having the global?


Tablets Running IDEs

I am new to the tablet market, but i am trying to learn more. Are any current tablets capable of running programming software such as Visual Studio? I understand they'd have to come up with some kind of streamlined version, but I can imagine the programmers out there excited about the possibility. Does anything like that already exist, or are there rumors of it being available in the near future?


Questioning one of the arguments for dependency injection: Why is creating an object graph hard?

Dependency injection frameworks like Google Guice give the following motivation for their usage (source): > To construct an object, you first build its dependencies. But to build each > dependency, you need its dependencies, and so on. So when you build an > object, you really need to build an object graph. > > Building object graphs by hand is labour intensive (...) and makes testing > difficult. But I don't buy this argument: Even without dependency injection, I can write classes which are both easy to instantiate and convenient to test. E.g. the example from the Guice motivation page could be rewritten in the following way:               class BillingService     {         private final CreditCardProcessor processor;         private final TransactionLog transactionLog;              // constructor for tests, taking all collaborators as parameters         BillingService(CreditCardProcessor processor, TransactionLog transactionLog)         {             this.processor = processor;             this.transactionLog = transactionLog;         }              // constructor for production, calling the (productive) constructors of the collaborators         public BillingService()         {             this(new PaypalCreditCardProcessor(), new DatabaseTransactionLog());         }              public Receipt chargeOrder(PizzaOrder order, CreditCard creditCard)         {             ...         }     }      So there may be other arguments for dependency injection ( **which are out of scope for this question**!), but easy creation of testable object graphs is not one of them, is it?


Whats the greatest most impressive programing feat you ever witnessed?

Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of? You can define impressive by:   1. The scope of the task at hand _e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined._   2. Speed _e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including its own C compiler and shell command line tools_   3. Complexity _e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon._   4. Quality _e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all._ Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat. So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for. Bonus questions:   1. Was the herculean task a one-of, or did the individual regularly amazed people?   2. How do you explain such impressive performance?   3. How was the programmer recognized for such awesome work?


Programming Practice/Test Contest?

My situation: I'm on a programming team, and this year, we want to weed out the weak link by making a competition to get the best coder from our group of candidates. Focus is on IEEExtreme-like contests. What I've done: I've been trying already for 2 weeks to get a practice or test site, like UVa or codechef. The plan after I find one: Send them (the candidates) a list of direct links to the problems (making them the "contest's problem list) get them to email me their correct answers' code at the time the judge says they have solved it and accept the fastest one into the team. Issues: We had practiced on UVa already (on programming challenges too), so our former teammate (which will be in the candidate group) already has an advantage if we used it. Codechef has all it's answers public, and since it shows the latest ones it will be extremely hard to verify if the answer was copied. And I've found other sites, like SPOJ, but they share at least some problems with codechef, making them inherit the issue of Codechef So, what alternatives do you think there are? Any site that may work? Any place to get all stuff to set up a Mooshak or similar contest (as in the stuff to get the problems, instructions to set up the server itself are easy to google)? Any other idea?


Which is best programming style to start learning to programm POP or OOP?

If somebody has to start learning to program, where should he/she start? Should he start to write procedure-oriented programs or jump to OOP?


Why can't Java/C# implement RAII?

Question: Why can't Java/C# implement RAII? Clarification: I am aware the garbage collector is not deterministic. So with the current language features it is not possible for an object's Dispose() method to be called automatically on scope exit. But could such a deterministic feature be added? My understanding: I feel an implementation of RAII must satisfy two requirements:   1\. The lifetime of a resource must be bound to a scope.   2\. Implicit. The freeing of the resource must happen without an explicit statement by the programmer. Analogous to a garbage collector freeing memory without an explicit statement. The "implicitness" only needs to occur at point of use of the class. The class library creator must of course explicitly implement a destructor or Dispose() method. Java/C# satisfy point 1. In C# a resource implementing IDisposable can be bound to a "using" scope:               void test()     {         using(Resource r = new Resource())         {             r.foo();         }//resource released on scope exit     }      This does not satisfy point 2. The programmer must explicitly tie the object to a special "using" scope. Programmers can (and do) forget to explicitly tie the resource to a scope, creating a leak. In fact the "using" blocks are converted to try-finally-dispose() code by the compiler. It has the same explicit nature of the try-finally-dispose() pattern. Without an implicit release, the hook to a scope is syntactic sugar.               void test()     {         //Programmer forgot (or was not aware of the need) to explicitly         //bind Resource to a scope.         Resource r = new Resource();          r.foo();     }//resource leaked!!!      I think it is worth creating a language feature in Java/C# allowing special objects that are hooked to the stack via a smart-pointer. The feature would allow you to flag a class as scope-bound, so that it always is created with a hook to the stack. There could be options for different types of smart pointers.               class Resource - ScopeBound     {         /* class details */              void Dispose()         {             //free resource         }     }          void test()     {         //class Resource was flagged as ScopeBound so the tie to the stack is implicit.         Resource r = new Resource(); //r is a smart-pointer         r.foo();     }//resource released on scope exit.      I think implicitness is "worth it". Just as the implicitness of garbage collection is "worth it". Explicit using blocks are refreshing on the eyes, but offer no semantic advantage over try-finally-dispose(). Is it impractical to implement such a feature into the Java/C# languages? Could it be introduced without breaking old code?


Separation of Concern/Single Responsibilty Principle

I've just been reading through the SOLID principles, and this is one I have real difficulty with when designing software. I am relatively new (4 months professionally) at coding. The idea is simply to encapsulate classes into ones that perform a single task. For example, what if you have a class that creates and populates a Treeview and configures it to your specification. You then want data retrieved from a database when the user clicks on the nodes. Would you say this is two separate concerns?   1. Populate and configure the treeview    2. Obtain data from the database? Also, in the same app. You have a datagridview that is also populated with dynamic data. Would you therefore put that data retrieval in the same class as the treeview data retrieval or would that be yet another completely seperate class? Thanks.


Modifying an open source application

What is the general workflow when I want to add a feature to an open source application I didn't originally write? How do I get to know the code? How do I find the spot that needs to be changed or added? How do I actually make the change without breaking anything else? How do I test that everything is still working?   What are the general guidelines on such a project?


Extracting models into a external dependency

About 9 months ago, I asked a question about creating a service layer for my application. Unfortunately, in the ensuing time, no progress in that area was made, primarily due to time constraints. As such, I am now re-evaluating this idea, and have another which might be a stopgap with a quicker development time. I work with a large monolithic application that really is made up of two distinct applications (except for the fact that they do, and must, share data). This doesn't sit right with me, and I would like to try to start breaking them apart into separate entities, for a variety of reasons. For example, the test suite is huge (and therefore very slow), and changing something in one "subapp" shouldn't affect the other anyhow. Scalability is another consideration, as one "subapp" receives significantly more traffic than the other. When I approached this idea last year, I was thinking about separating all the data out into its own layer, that the subapps could query, but as mentioned this seems to be more of a commitment than I could sell at the moment. Instead, what I am thinking now would be to extract the models (or at least the shared models) into a gem (or, I suppose a Rails Engine) that is required by each subapp. The upside would be that each subapp could be developed independently, tested independently, and scaled independently. Also, once in place, it might be easier to rip out an external "model provider" and replace it with proper SOA (as at that time, everything will already be split up at least), than making the jump straight from monolithic application. The downsides I can think of center around ease-of-use. New code would require touching multiple repositories, and keeping mental context might be difficult. Similarly, my developers who are less experienced with design might have trouble finding the code they need, or keeping the separation intact. Of course, these can be mitigated with proper tools and code review, and the same downsides likely apply for SOA. Can anyone weigh in on if they think this is a good or bad idea? Is it worth taking the effort for what is clearly an "intermediary" step, rather than trying to find time to do it "properly" (whenever that will be). Are there any other downsides (or upsides) that I am not considering?


Tool that turns truth table into smallest possible if / else block

Is there any application or tool that will take a truth table and turn it into a compacted if block? For instance, lets say I have this truth table where A and B are conditions and x, y and z are possible actions:               A B | x y z     -------------     0 0 | 0 0 1     0 1 | 0 0 1     1 0 | 0 1 0     1 1 | 1 0 0      This application could produce this if block:               if(A)     {         if(B)         {             do(x)         }         else         {             do(y)         }     }     else     {         do(z)     }      This is an easy sample, but I frequently have several conditions that combined in different ways should produce different outputs and it gets hard to figure out the most compacted and elegant way to represent their logic in an if block.


How to indicate to a web server the language of a resource

I'm writing an HTTP API to a publishing server, and I want resources with representations in multiple languages. A user whose client GETs a resource which has Korean, Japanese and Trad. Chinese representations, and sends `Accept-Language: en, ja;q=0.7` should get the Japanese. One resource, identified by one URI, will therefore have a number of different language representations. This seems to me like a totally orthodox use of content negotiation and multiple resource representations. But when each translator comes to provide these alternate language representations to the server, what's the correct way to instruct the server which language to store the representation under? I'm having the translators PUT the representation in its entirety to the same URI, but I can't find out how to do this elegantly. `Content-Language` is a response header, and none of the request headers seem to fit the bill. It seems my options are   1. Invent a new request header   2. Supply additional metadata in a multipart/related document   3. Provide language as a parameter to the `Content-Type` of the request, like `Content-Type: text/html;language=en` I don't want to get into the business of extending HTTP, and I don't feel great about bundling extra metadata into the representation. Neither approach seems friendly to HTTP caches either. So option 3 seems like the best way that I can think of, but even then it's decidedly non-standard to put my own specific parameters on a very well established content type. Is there any by-the-book way of achieving this?


GPL code allowing non-GPL local copies of nondistributed code

I have come across a book that claims that alterations and augmentations to GPL works can be kept close-source as long as these are not redistributed into the wild. Therefore, customizations of websites deriving from GPL packages need not be released under the GPL and developers can earn profit on them by offering their services to their clients while keeping their GPL-based code closed source at the same time. (cf. Chapter 17 of WordPress Plugin Development by Wrox Press). I've never realized this, but essentially, by putting restrictions on redistributable code the GPL says nothing about what can and cannot be done with code which is kept private in terms of the licensing model. Have I understood this correctly?


In general, should an organization adopt a single methodology or decide on a per-project basis?

I work for a company that, in my opinion, should be doing all of it's web development work in a fully agile manner. We have vague, competing ideas about the product at any given time. And we have strict deadlines. So, in the web arena it seems to make sense to operate in as agile a manner as possible. However, I could conceive of projects on the business apps side -- or even a complex sub-project on the web side (integrating with a pre-existent 3rd party app?) that, at least for the sake of argument, isn't at all changeable in scope. The scope of the integration piece would, for all intents and purposes, be fully specifiable up-front with zero chance for change. In general, is it acceptable to take project X in an organization that is normally attempting to achieve agility and work through it in a waterfall manner? Does it somehow compromise the agility of the organization on a whole? If the organization is truly trying to be agile, should the "rigid" project still be "managed" in an agile manner?


How do VMs implement function calling?

I'm reading a compiler textbook that compiles to some form of assembly. Since I don't know this assembly language I decided to invent my own simple "assembly language" and implement a basic "virtual machine" which will execute these instructions. Currently I'm thinking how I can implement function decleration and function calling in the language and VM. I had the following idea, please tell me what you think: Function declerations would look like simple labels. At the end of a function there's an `end` statement. The 'main program' is a function by itself. For examle:               main:     // some logic     CALL funcA     // more logic     END     funcA:     // .. some logic     END      However the difference between `call <function>` and `goto <label>` is this: `goto` simply sets the 'instruction pointer' (the register that holds the number of the next line to be executed) to the line number of the label. `call` does what `goto` does, but _before jumping_ it pushes the current line number (plus 1) onto a stack. When `end` is reached, the VM pops the top of the stack and jumps to this line number. If there is nothing in the stack, the program terminates. So for example, for the code above this is what happens:               main: // this is where the VM starts     // some logic     CALL funcA // push onto the stack the number 4 (3+1), and jump to the label funcA     // more logic .. this is where we return to from funcA     END // pop the top of the stack and jump to this line number. nothing -> terminate     funcA:     // .. some logic     END // pop the top of the stack (the number 4), and jump to this line number      What do you think of this approach?


std::shared_ptr as a last resort?

I was just watching the "Going Native 2012" streams and I noticed the discussion about `std::shared_ptr`. I was a bit surprised to hear Bjarne's somewhat negative view on `std::shared_ptr` and his comment that it should be used as a "last resort" when an object's life-time is uncertain (which I believe, according to him, should infrequently be the case). Would anyone care to explain this in a bit more depth? How can we program without `std::shared_ptr` and still manage object life-times in a **safe** way?


Should a git commit message mention the file that was modified?

In the first line of a git commit message I have a habit of mentioning the file that modified if a change doesn't span multiple files, for example:               Add [somefunc] to [somefile]       Is this a good thing to do or is it unnecessary?


Small Basic vs Microsoft Small Basic

Are **Small Basic** ( **SB** ) and **Microsoft Small Basic** ( **MSB** ) related or is this a confusion based upon similar names? I have read that **SB** is written in C and is GPL. The oldest date on SourceForge is 2004 but the facebook group states its over 10years old. **MSB** is written in .NET 3.5 by Microsoft DevLabs. Wikipedia states it originated in 2008. They seem completely unrelated. Is this another Microsoft "Embrace, Extend, and Extinguish" tactic? I have read that **MSB** does not allow distribution: > The license is presented when you install the software. Small Basic includes > a command line compiler that can be used as part of the product. You may > install and use any number of copies of the software on your premises to > test how it runs with your programs, distribution is not allowed. Please > review the license terms for additional use rights/restrictions. Thank you. -MSB Forums


Unit of Work pattern

I have gone through many articles and I am still confused whether to use the Unit of Work pattern or not. I use generic repositories (Repository Pattern) but if my understanding of the UOW pattern is correct, most persistence tools today offer a unit of work pattern already implemented (DbContext, ObjectContext, DbSet). I want to know if, in such cases, we should not try to implement the UOW pattern altogether? or I did see in one of the articles (sorry can't reference it since I missed it somewhere) that they had wrapped the DbContext inside an UOW class and I was left wondering what reason they might have of doing so.


Who retains ownership when custom software is commissioned?

A local business owner wants to hire me (contract) to build custom software for his business and employees. It will likely be a small web app that I'll host on AWS. Who retains IP rights to the system? Do I maintain ownership of the source code and grant him a perpetual license to use it or does the client typically acquire rights? I **know** the agreement can be made to accommodate either strategy but was wondering what industry norms were here.


Should my code be DRY or readable if it can't be both?

I'm writing Ruby code for a simple encryption exercise and have frequently run across this dilemma (the exercise is a solitaire cipher if you must know). It is a question of whether I should pad out my logic with descriptive variables and single step statements that make the function readable instead of a concise, even dense statements that eliminate repetition and/or minimizes opportunities for errors. My most recent example: My program takes input, and because of rigid format guidelines, it can easily determine if input should be encrypted or decrypted. To simplify, once the encryption key and message are converted/generated to be compatible, it's a matter of subtracting the key from the encrypted message or adding the key to an unencrypted message, to get the desired output(think of the key as encryption, message + encryption = code; code - encryption = message). The DRY position says to me that I should convert my encrypted message differently from my unencrypted message so that the function which takes encryption key and applies it to the message never needs to distinguish. I've found that this means I need some nested if statements in the function but the logic appears to be solid. This code, however, is not easily readable. This would require some commenting to be clear. I could, on the other hand, write two different functions that are called based on a flag that is set when the application determines encryption or decryption. This would be simpler to read but would duplicate the high level function of applying the encryption key to a message (causing it to be encrypted or decrypted). Should I lean toward readable code, or concise code? Or have I missed another way to get this functionality and satisfy both principles? Is it a position along a scale in which one must consider the purpose of the project and make the best decisions to serve that purpose? So far, I tend to emphasize concise, DRY code over readable code.


Transforming A Physical Algorithm into a Computerized One

I have realized that its possible to create algorithms that operate physically to solve problems much more efficiently than in a computer itself. Consider the following: Finding the shortest path between 2 points in a connected graph. If one were to physically create the graph with the edge weights correspond to length of physical connectors and the nodes something corresponding ex: wooden balls and yarn both labeled, then it is possible to generate the graph from data in O(N) time and then determining the shortest path between 2 nodes would simply involve grabbing both those nodes and pulling them so a straight line forms between them (or multiple straight lines!) and the rest hanging. That straight line(s) would be the shortest path for obvious reasons. How exactly does one take this physical method of solving the problem and implement it in a computer?


Should software patents be legal?

A really big issue that a lot of people have problems with is software patents. According to Wikipedia, some of the big issues with software patents include:   * Where the boundary between patentable and non-patentable software should lie   * Whether the inventive step and non-obviousness requirement is applied too loosely to software   * Whether patents covering software discourage, rather than encourage, innovation One famous example of questionable software patents is Amazon's patent on 1-Click checkout which was initially granted by the USPTO in 1999, re-examined in 2007 and finally revised in 2010 due to much debate regarding its validity. The idea of simplifying a user's buying experience by reducing the number of actions required to complete a transaction seems like common sense to just about anyone, so why should patents like these be legitimate? As a professional or a hobbyist, how do you feel about software patents? Do they crush innovation by locking down [often] common-sense ideas, or are they a necessity of success and profitability?


What's the business in developing a programming language?

I was wondering if there's a big, direct revenue in releasing a programming language such as Java or C#? Selling IDE's, licensing your brand for books or gaining enterprise prestige seem bit of a marginal benefit to my eyes compared with the effort that undoubtedly the development took (I could be wrong though, of course).


Quick OOAD Question

Given the following set of classes:               Camera, Photo, Photoshoot, Subject.      How would they interact to model the following sentence? _The next subject is called and has their photo taken._ I want to see if there is a preferred solution. **Edit:** Sorry I should have said in C#.


flow control solutions in Node.js - use async.waterfall?

Looking at node.js, and avoiding nesting callbacks. I found Async.js, can someone show me how can I rewrite this code using the async.waterfall method?               // db is a mongodb instance     db.open(function(err, client){         client.createCollection("docs", function(err, col) {              client.collection("docs", function(err, col) {                  for (var i = 0; i < 100; i++) {                      col.insert({c:i}, function() {});                  }                  console.log('Insert done OK.');              });         });     });      What problems does this naive solution with inner functions have, over the async method?               db.open(openAndInsert);          function openAndInsert(err, client) {         var myCollection = "docs";              client.createCollection(myCollection, openCollection);              function openCollection(err, col) {             client.collection(myCollection, insertIntoCollection);         }              function insertIntoCollection(err, col) {             for (var idx = 0; idx < 100; idx += 1) {                 col.insert({c:idx}, function () {});             }             console.log('Insert done OK.');         }     }      The three levels of nesting in the original code seem like a code smell, but I'm not sure either my home rolled or the async solution are universally better. Would anyone prefer just leaving the nested functions as is? If so, how deep would the nesting have to be before going using some type of flow control?


What is the best value to use for id in an ActiveRecord pattern (PHP). auto-increment is out of the question. I would like to generate an id value that I can use to create a new record, but will be unique. random values have a chance of creating collision. querying to get the last id used, and then incrementing that value has the chance that another record will be created at approximately the same time with the same id value. what do most use in this situation? what is the best thing to use for this situation?


Dividing a packet protocol into layers

I work on embedded systems, so frequently, I am required to implement protocols. When I do this I like to make nice clean layers. However, this become difficult where the fields used by different layers are shared. I like to think of the layers as offering a number of services following the spirit of OSI model: **Framing**   1\. start byte / sequence (SOF)   2\. length of packet / message   3\. message integrity (CRC, xor checksum) **Network**   4\. Source / Destination **Application**   5\. Command / Response Type (how to interpret payload). (I realize this is not the ISO model, but you get the point I hope.) Sometimes the protocol exists on a point to point link (RS232 or tcp socket) so there is no concept of source and destination. I would typically have a software layer for each of: Framing, Network and Application. The layer is typically a state machine processing bytes, or frames or packets. At the top, there is a hook point for the application specific functionality. Typically as a packet moves up the stack and the layers are stripped off, I simply pass a pointer to the next inner scope. First pointer to SOF, then pointer to network fields and finally a pointer to the application payload. As the fields are parsed they are added to a structure specific to the layer producing it. (A structure with a name like: Frame, Packet, Message / Command / Response) Each structure has a pointer to the packet buffer. At the top I can deallocate the structure by calling free on each layer until at the bottom a pointer is available to free. (or return to a pool) The question is how can I cleanly handle cases where the fields have dual use or are bit fields in a byte. (upper nibble is payload length, lower nibble is packet type, etc...) An example of this is a simple packet format like this:   `<SOF> <CMD> <command specific payload> <CRC>` In this case the length of the packet is implied by the command code. So the CMD field (a single byte in this case) is shared between the framing and application layers. I think in this case the framing layer has a lookup table for command to length and passes a pointer to the CMD field up to the application layer for handling in a structure.


Is event sourcing ready for prime time?

Event Sourcing was popularized by LMAX as a means to provide speed, performance scalability, transparent persistence and transparent live mirroring. Before being rebranded as Event Sourcing, this type of architectural pattern was known as System Prevalence but yet I was never familiar with this pattern before the LMAX team went public. Has this pattern proved itself in numerous production systems and therefore even conservative individuals should feel empowered to embrace this pattern or is event sourcing / system prevalence an exotic pattern that is best left for the fearless?


Need advice on design in Ruby On Rails

For personal educational purposes I am making a site for a conference. One of the object that exist in a conference is a session, which has different states and in each state it has slightly different attributes:   1. When submitted it has a speaker (`User` in the system), Title and abstract.    2. When under review it has reviews and comments (in addition to the basic data)    3. When accepted it has a defined time-slot but no reviewers anymore. I feel that it is not the best thing to add a "status" attributes and start adding many `if` statements...   So I thought it would be better to have different classes for each state each with it's own validations and behaviors. What do you think about this design? Do you have a better idea?


Can a C# developer turned VB developer ever return to C# later in their career without a significant penalty?

**Background** : IT Recruitment in UK has absolutely exploded over the last five years and I get quite a few calls from recuiters each week with positions. One recruiter offered to put me forward for a great looking position at a great salary in the area I wanted, so I had a phone interview which went very well and genuinely expect the face-to-face interview to go well. Unfortunately, as I do have to sift through quite a few wildly inappropriate positions I either confused two job descriptions or simply didn't read it properly. Anyway it turns out that the job is a VB.NET developer and I am a C#/Java developer. While I'm confident I can do the job, I'm concerned that accepting it might hinder me later in my career if I ever wanted to return to C#. I'm also concerned that many of my peers are quite snobbish about VB and am not sure how popular that position is. **Actual Question(s)** : As as C# developer (with 4 years exp), considering accepting a position as a VB developer, in 5 years will I be able to take another position back in C# (or Java) without having to return to my current level of seniority? Also, if anyone's actually made this transfer - was working in VB disappointing or did it feel limiting?


Is pure oop necessary

Please don't direct me to this post: http://stackoverflow.com/questions/1551/how-to-think-in-oo. I have read it and still have no answer. I have programmed c++ for years and was taught that everything should be oop in design. i have recently started java and find it to very restricting in the way it makes everything a member or method of a class. Though I agree reusable classed improve code but does everything need to be a class. as an example in a simple space invader game there would be classes for the aliens, the ships and the bullets but there are things like the score and timer that are single instants. I feel these work better as globals rather than a class that will only be used once. I am starting to question whether I am an oop programmer and if I want to be one for that matter. I am not really looking for an clear answer as this in not really a question, I am just wondering if I am doing it all wrong or just differently. Thanks EDIT: Showing my ignorance here but what the hell ... what difference does it make putting all the global stuff into a global class apart from access and duplicity(multiplayer)? Is there an efficiency or memory angle I am not seeing?


JSON vs Foreign Keys

I'm developing an enterprise website, and I have to define some sections like this:   * I have many sections and each section have many (or one) sub-pages.    * The number of sub-pages vary per section.   * Each sub-page should not be longer than 2500 characters Also, I have to use a relational database (MySQL). I'm in doubt which would be the better in terms of design and/or performance:   1. To store a `JSON` array, with all sub-pages as object, as a single column of the `Sections` table;   2. To create a table `Sub-pages` which references it's parent section by a `Foreign Key`.


Is Entity Framework ready for production?

I'm looking into Entity Framework for a new project that I'm going to be taking on and as part of my research into it I'm asking some industry professionals if it's stable and ready for 'real world' implementation. In the running is:   * EF   * NHibernate   * DevExpress XPO I already have a great deal of experience with XPO, but I'm not particularly happy with it.


API Class with intensive network requests

I'm working an API which works as "intermediary" between a REST API and the developer. In this way, when the programmer do something like this:               User user = client.getUser(nickname);      it will execute a network request to download from the service the data about the user and then the programmer can use the data by doing things like               user.getLocation();     user.getDisplayName();      and so on. Now there are some methods like `getFollowers()` which execute another network request and i could do it in two ways:   1. Download **all** the data in the `getUser` method (and not only the most important) but in this way the request time could be very long since it should execute the request to various urls   2. Download the data when the user calls the method, it looks like the best way and to improve it i could cache the result so the next call to `getFollowers` returns immediately with the data already download instead of execute again the request. What is the best way? And i should let methods like `getUser` and `getFollowers` stop the code execution until the data is ready or i should implement a callback so when the data is ready the callback gets fired? (this looks like Javascript)


How is Node.js different from other server-side frameworks?

I've noticed that Node.js has become very popular, and I've seen several instances of people doing small-scale projects in it. I've also looked at pros and cons lists to get an idea of what Node.js can do, but I'm still not clear on how it differs from other, more mature server-side tech like PHP, Perl, or Ruby on Rails. What, specifically, differentiates Node.js from the current alternatives, and why?


How to discover a class in PHP dynamically much like a plug-in architecture

I'm encountering a common issue in PHP (and most other languages) at the moment, where systems I'm designing need to be updated in multiple places to add new features, whereas I would like to have a core, where I can add new features, plugin's etc without having to touch the core code. An example would be a a navigation menu, where the menu loads it's items from directory or namespace X. My aim is so once I or another developer adds a new file, extends a MenuItem class, whichever it needs to be, the class loading the menu would discover this new file and display it, without ever having to touch the core menu loading code. The best I have come up with so far is:               function get_menu_items() {         $menu_items = array();         $raw_files = scandir(DOCUMENT_ROOT . '/menu/menu_items');         foreach($raw_files as $file){             require_once($file);             $class_name = substr($file, 0, -4); // cut away the '.php'             $menu_items []= new $class_name();         }         return $menu_items;     }      But the above feels wrong as I shouldn't be checking a directory for existence of files for features! I imagine this is a common design pattern like wordpress would use for plugin discovery? I've been searching for a while but not been able to better the above! Any help would be greatly appreciated!!


What is the point of using DTO (Data Transfer Objects)?

What is the point of using DTO and is it an out dated concept? I use POJOs in the view layer to transfer and persist data. Can these POJOs be considered as an alternative to DTOs?


How to "read" rails apps?

I've just finished the first rails tutorial and now want to learn something about how other developers use it. So is it possible to "read" rails web applications to learn about its architecture and design?


Queue of jobs in a different states and with different services around

I need to design a 'queue' of jobs (in a a very much UI oriented application) that can be run by a user and I need some other thoughts to pick optimal approach from ground up. My jobs can be in a different states (imported, sent from elswhere, created by user, even to be just simulated with their imported recorded progress - following a whola different workflow), etc. Therefore they can also pass thru the different states of their lifecycle, like being created, running, paused, validated or edited by a user (in case of invalid job parameters), imported or even in the process of being deleted (at least for logging or auditing). Because of this, all jobs have to have their state at each point of time and they need to be managed somehow by a common logic. There are also domain and application rules, that only one can be running/stopped/params edited in a time state, etc... My main question is, whether to implement some kind of monolithic singleton controller for all states where it can answer state guards of each one of them (can/cant transition to other state) for all states and can call actions (other services) upon them, or whether to implement state machines inside of the jobs themselves and somehow call the services and related conditional logic from themselves (delete me/ edit me and so on). I also need to tie this tightly to the UI, so that I have a list of tasks with the states visible for the user but I also have the separation of the concerns (job itself as a domain object of parameters - not states, UI). This is just a brief description of my main problem, so I might update the requirements as suggestion or more questions that I forgot to address arrive.


write my own or choose a framework for link sharing website

I'm a PHP programmer and I've done any projects based on PHP and MySQL without using any framework so far. Now I'm going to create a big link sharing system (excel- able,modular,fast,theme based,secure etc.). But I have no experience to use any frameworks before. I need to know which is better to me.Choose a framework (easy to use and learn it fast) or still do my method?


Should I refactor a F class from code climate?

According to code climate, a class is `F`, aka the worst mark you could be granted. I did submit a pull request to rearrange it here Which has been refused because the new code is supposedly too abstract. I'm utterly convinced a `F` has a real meaning and should be fixed, above all when it's one of the main class of a project. What's your point of view?


Do the benefits of Resin/Quercus outweigh the overhead?

Lately, I've been looking more and more into Resin + Quercus as a technology to develop an application of mine. The reason I started looking into it was that this application has high reporting needs, a lot of which cannot (or realistically, should not) be created in real-time. Java would offer a nice backend to queue and generate reports. Also, with Quercus I would be able to develop my data models in Hibernate, and use them "from PHP", thus effectively stretching these models across front and back-end. This same concept would also apply to any front/back-end common business logic, which could be developed in Java libraries. Now, the downside is that whichever front-end (PHP) MVC Framework I choose (my goal was Symfony 2), it is unlikely to work without some heavy modification, if it can work at all. Quercus is a pretty close implementation of PHP, and is supposed to be compatible with PHP5.3, so namespaces and closures SHOULDN'T be a problem, but when I tried to run an existing Symfony 1.4 app, I failed miserably. So, my question to you is, do you think the benefits of Resin + Quercus outweigh the overhead of using a not-so-perfect/stable implementation of PHP? If this were your application, and your goal was and end-product, rather than educational purposes, what would you decide?


Suggestions on switching from lamp based web design-development to game design-development

I have around 2.5 years of experience as a web developer cum designer working mainly on the LAMP platform. Now, I want to try out game development (of the likes of First Person Shooter games like Call of Duty (COD)). It is one of my dreams to some day succeed in making a profitable, popular, commercial game of this type. However, I have never done any kind of business nor even freelancing yet even in the web domain. Okay, first things first, I am just starting and I don't yet have any idea about the technologies, languages, engines (game engines) etc involved in that. I would like this question to be a complete guide for people with similar interests. **Best resources for getting hold really fast** What would be the best approach to get the basic hold of the domain really fast? Any resource(s) for programmers coming from other domains/experienced in other domains would be the ideal ones for me. E.g., if anybody would ask me some good resource for quickly learning PHP/Mysql, I would suggest books like "How to do everything with PHP & MySql" - ![How to do everything with PHP & MySql](http://i.stack.imgur.com/8KDz4.jpg) because -   * it introduces all the basics of the domain (not the advanced things which can be later learnt by practice and also a lot by searching in stackoverflow questions)    * it contains some very nice working projects in the end, which help in applying the skills learnt in the chapters of the book. This is the best way for self learners, I feel. I would appreciate some similar resource which connects all concepts together to get the bigger picture. I have read about C, C++, C#, JAVA being used in game programming but not sure which language to go for (I have previously learnt a little of C and JAVA). I have also read about game engines but there would be various other concepts. **Commonly accepted ways of learning**   Should 3D games like these be tried after 2D games? Are there some commonly accepted ways of learning such kind of games? Like in web development, we should go for frameworks after practising well with basic language, AJAX after getting properly done with simple page-reload processing etc. Apart from these, any useful tips (like language choices etc.) would be much appreciated. Like it is highly recommended to contribute to open source web projects for getting recognition, are there similar open source game projects? Thanks,   Sandeepan


Is this an example of recursion?

I am implementing inheritance of something called Contexts. Each Context holds a link to its parent context. If that Context is the root Context, its parent is null. In order to walk up the inheritance tree and get the data from each Context, I want to do this (in pseudocode)               private Hashtable getDataAsMap() {         Hashtable map  =  this.parent != null  ?                                 this.parent.getDataAsMap()  :                                 new Hashtable();              // add my data              return map;          }      Is this recursion? I'm calling the same method, but on a different object. Does that still count? If not, what would you call it?


CQRS applicability when some commands need to block the UI

I am working on an app which I would dearly love to transition from a fairly traditional layered architecture to CQRS, for a number of reasons, not least fo which is that having a robust event log will make adding a couple of feature requests I can see barrelling towards me trivial to accomodate. Now, I have a conceptual problem: of around 40 commands the user can initiate, there are three which the user _needs_ to be sure have successfully completed before the UI lets them do anything else. Everything else fits into the "submit a request, query for success later" model, except for these three commands. How is this handled in CQRS-land? Do I separate the three blocking commands to effectively a third service, so I have Commands, Queries, and BlockingCommands? Do I have a two-stage event processor with an in-request blocking first stage which only gets used for the blocking commands? Does the existence of these three commands mean that the whole idea of applying CQRS is invalid? Should I just pretend they _aren't_ blocking and poll for success in the UI? I'm sure this must come up on other projects, how is it usually handled?


Is it important to know C/C++ for Android development?

Is it possible to use only Java (without C++ /NDK) for building good, fast, beautiful Android apps (including 3D development)? When I look for Android developer position requirements (vacancies), I see that knowledge of C/C++/NDK is very important. Some companies even require to build their test tasks using only C++ (OpenGL).


log4net - roll my own singleton, use LogImpl, etC?

Reposting here... hopefully the better place to seek opinions on the matter. :) Writing my own log4net wrapper class using C#. I want to create a lib such that I can reference it from any project/assembly in a given solution with a minimum of effort. ie: include the reference, maybe throw in a using statement and then make calls like MyLogger.Debug(blahblah); with perhaps a property (MyLogger) being set from a "main" method somewhere. From reading the docs, I'm not sure if I should be writing my own or using LogImpl? The latter seems to include all of what I'd want to put in my own wrapper, so, why reinvent the wheel? But, there is also a note in the help that says thast an instance member of type logimpl is not thread safe whereas a static member is... OTOH, if I make my own, I'd be looking at a singleton class I can create once and use throughout my solution (by passing the singleton ref to objects which require it) but I gotta rewrite all those Debug, Error, etc sections. So... not sure what approach to take. What would you folks suggest as a beginning?


Standardised Programming Techniques / Procedures

I don't know if this is a question, or a start of a conversation or even a completely irrelevant topic. Why isn't programming more standardised? Im really new to this and I find it hellish difficult to find the answer to even basic questions. Things like--   * How do I add validation to multiple texboxes in asp.net c# without using individual validation controls?   * How do I add the input of a texbox to an ongoing array? I'm talking about fundamental things that get used all the time. I would expect answers like "oh yeah, see jones' validation method (link) or peters' textbox to array function (link). I just thought there would be standard techniques, like in chess, for doing things that are similar. I hope this makes sense and someone can point me in the right direction if there ARE directories of standard programming technniques.


Can I sell forked GPL code?

I know that it is possible to sell GPL code, but I wanted to know if it was possible to sell GPL code that has been forked and modified. The forked and modified code will still be available to use, modify, and redistribute.


self referencing tables, good or bad?

Representing geographical locations within an application, the design of the underlying data model suggests two clear options (or maybe more?). One table with a self referencing parent_id column uk - london (london parent id = UK id) or two tables, with a one to many relationship using a foreign key. My preference is for one self-refercing table as it easily allows to extend into as many sub regions as required. IN general do people veer away from self referencing tables, or are they A-OK ?


Non-English-based programming languages

The University of Antioquia in Colombia teaches its introductory programming courses in Lexico, a Spanish-based, object-oriented .NET language. The intent is to teach programming concepts in the students' native language before introducing English-based mainstream languages. There are many other Non-English-based programming languages and there is even a related question in Stack Overflow. I have several questions regarding these languages:   * Has anyone on this site learned to program using a non-English-based language? If so, how difficult was the transition to the first English-based language?   * Is there any research-based evidence that non-English speakers learn programming faster/better using languages with keywords in their native language instead of English-based languages?


Is using non-standard single-line comments fine in C?

I noticed Visual C++ 2010 (my current environment) and XCode both allow non- standard single-line comments in my C programs. Since these are both my target platforms, I assume it's fine to use it? VC++ 2010 doesn't support C99, so I'm limited to C89, though I know C99 added support.