title: Database connection - should they be passed as parameter?

text: We have a system whereby the database connection is get once using a common method, and being pass throughout the relevant class to be used. There are doubts that passing the database connection as a parameter to different classes would cause problem, so i'm checking here to see whether this is actually viable, and are there any better patterns to do it? I know there are some ORM tools to do the persistence but we can't go into that, yet.. Any feedback is welcomed, thanks.


title: Time management and self improvement

text: I hope I can open a discussion on this topic as this is not a specific problem. It's a topic I hope to get some ideas on how people in similar situation as mine manage their time. OK, I'm a single developer on a software project for the last 6-8 months. The project I'm working on uses several technologies, mainly .net stuff: WPF, WF, NHibernate, WCF, MySql and other third party SDKs relevant for the project nature. My experience and knowledge vary, for example I have a lot of experience in WPF but much less in WCF. I work full time on the project and im curios on how other programmers which need to multi task in many areas manage their time. I'm a very applied type of person and prefer to code instead of doing research. I feel that doing research "might" slow down the progress of the project while I recognize that research and learning more in areas which I'm not so strong will ultimately make me more productive. How would you split up your daily time in productive coding time and time to and experiment, read blogs, go through tutorials etc. I would say that Im coding about 90%+ of my day and devoting some but very little time in research and acquiring new knowledge. * * * Thanks for your replies. I think I will adopt a gradual transition to Dominics block parts. I kinda knew that coding was taking up way to much of my time but it feels good having a first version of the project completed and ready. With a few months of focused hard work behind me I hope to get more time to experiment and expand my knowlegde. Now I only hope my boss will cut me some slack and stop pressuring me for features...


title: Is it possible to implement an infinite IEnumerable without using yield with only C# code?

text: # Motivation The main idea is to explore and understand the limits of how far one can go with the basic LINQ primitives (Select, SelectMany, Concat, etc.). These primitives can all be considered functional operations on a theoretical sequence type. Taking examples from Haskell:   * `Select` 'lifts' a function into the sequence (like `fmap` in Haskell)   * `Concat` is composition   * `Aggregate` is the sequence type's catamorphism (fold)   * `SelectMany` 'extracts' information from the sequence (the Monad bind, `>>=` operation)   * etc. (and I'm sure there are better abstractions for the above) So the question is whether or not the basic sequence (Enumerable) operations in C# are enough to construct an infinite sequence. More concretely it is the following problem: # Problem I'm curious to know if there's a way to implement something equivalent to the following, but without using `yield`:               IEnumerable<T> Infinite<T>()     {         while (true) { yield return default(T); }     }      Is it possible to do sue using the built-in LINQ operators only? The short answer is that theoretically yes, but practically not because of how Linq is implemented (causing stack overflows). That's why here are less restrictive rules: # Rules Alternatively a less restrictive question would go by the rules   1. You can't use the `yield` keyword directly   2. Use only C# itself directly - no IL code, no constructing dynamic assemblies etc.   3. You can only use the basic .NET lib (only `mscorlib.dll`, `System.Core.dll`? not sure what else to include). However if you find a solution with some of the other .NET assemblies (WPF?!), I'm also interested.   4. Don't implement IEnumerable or IEnumerator. # Notes An example theoretically correct definition is:               IEnumerable<int> infinite = null;     infinite = new int[1].SelectMany(x => new int[1].Concat(infinite));      This is " **correct** " but hits a StackOverflowException after 14399 iterations through the enumerable (not quite infinite). I'm thinking there might be no way to do this due to the C#'s compiler lack of tail recursion optimization. A proof would be nice :)


title: Android DB With Some Multi-Language Data

text: I have a SQLite Database in my Android app with a "Question" table, among others. That table contains "default" or "pre-loaded" data (in this case the questions asked by the app). Some of its columns are "technical" or "internal" data to be used behind the scenes - like the number of points the question is worth, the type of user that may answer it, etc. - while others are textual data that are presented to the user (e.g. Title, Description, etc.). Now, I intend to let my app be internationalization-friendly (translatable) so I'm thinking that:   * Instead of following what seems to be the 'standard approaches' for multi-language DB design - either creating different columns for the translatable attributes (e.g. name_en, name_es, ...) or a separate table where each row represents a translation of the base object;   * ...I could simply keep the values for those translatable attributes in my `R.Strings` resource and have my DatabaseHelper class fetch the text from there, by building the resource name based, for instance, in the question's ID (e.g. q1_name, q2_name, q1_description, ...). This way I could have several R.strings and the DB helper would read from the right one. I'm a bit unsure about this approach and I'm curious if this is a bad practice and/or I'm missing any potential drawback.


title: The model to sell apps on App Store is better with a paid only version?

text: Rob Napier, the author of iOS 5 Programming Pushing the Limits, mentioned there are several models of selling apps on the App Store:   1. Write an app and sell it   2. Publish a free and a full version   3. Ad supported by third party or by iAd   4. In App purchase Surprisingly, the author said that the most workable model is (1) in terms of sales. I would think that (2) with fairly limiting ability for the free version can bring more sales, as people without trying, might not plunge down $0.99 or $1.99 for something they haven't tried? I for one, might not have purchased Angry Birds if I didn't try their free version first. Also, I think it also depends on the situation: for example, if the app is an alarm clock, and there are already 5 alarm clocks in App Store that are free, then your app that is $0.99 might not be that eagerly purchased (or they may end up never trying your app). But if yours is also free, and users really like it out of all the other ones, then they may think, $0.99 is nothing to get a good alarm clock, and gladly pay you the $0.99 in exchange for a full version of the alarm clock, for something that they can't get with the free version. (such as the full version can let you choose a song from your Music Library for the alarm). Could (1) work only if the user definitely want it and have no substitute? How might it work the best?


title: International two-part date formats

text: Do people outside of the USA use two-part date abbreviations for the current year? For instance, representing the last day of May, you might see someone enter `5/31` into a date field. Do international users do something similar? In a country that ordinarily uses dd/MM/yyyy would they use `31/5` or some such?


title: Design pattern advice required for sending xml files to different destinations

text: I am using an Export Module, now I want to extend it for different connections. I have a database which contains products Its Description, Review, Images etc. I use the serialize function to save it as XML file. After saving it as XML, in admin pannel I have possibility to select how this XML file will be exported. for example throught ftp, http, local, webservice, email etc. user has the possibility to select one or more connections to export the files. Each connection like ftp, http has it own settings in Database e.g ftp domain, username, password. what will be the best way to write these connection classes (by implementing Interface or using Abstract class or some Manager) and how to pass them to the export component as one exoprt may have on to many connections.


title: 1h coding test for recruitement interview, is it a common practice

text: I received an email for a web company position I applied to. They are asking me to provide a 1h time slot, so that they can make me pass a coding test. They'll send the test, start the time, and 1h after, I'll have to provide them what I came up with. This will be on Python and Javascript. I'm a developer since 18 months only, as I was a Unix SA for 15 years before this. Is it a common practice? How to prepare and is there any tests examples on the net? I cannot find any. Thanks


title: Is it possible to build software that interprets video in real time?

text: Say you had a live video stream of a popular boardwalk that had thousands of pedestrians walk down it each day. Could software be written to count the number of people that walk by a camera and collect data on things like how many of them were wearing red clothing or how many were over 6' tall? I'm thinking the software would be a layer between the camera and the people. But I have no idea if that is even possible. If something like this already exists, I wasn't able to find it but please share if it does. Thanks!


title: Licensing open source controls iOS

text: I am confused about using licensed open source control in my comercial iOS application. Do I have to include any license in my code or i can just add open source control and push app to app store? For example have look on following https://www.cocoacontrols.com/controls/klnoteviewcontroller It has two lincenses. I can download it for free using Apache 2.0 License but I am not sure if I can use it my paid iOS application. Please advice


As title: Why is aggregation function bad idea for RESTful? Although I know CRUD is good for RESTful. For example, the resource is ' _employee_ ', and client needs to retrive sum of total ' _salary_ ' of all employees. Shouldn't RESTful service provide such sum function? Further question: if aggregation function is bad for RESTful, how can a client get sum of total salary? To retrieve all 'employee' records and sum up itself?


title: Which is Preferable: FirstName LastName or Forename Surname etc

text: It seems there are many different ways to represent the same information:               FirstName, MiddleName, LastName     Forename, MiddleName, Surname     GivenName, MiddleName, FamilyName      Which one is preferable? It depends??


title: Implementing search over large data set, PHP or Mysql stored procedure?

text: I'm building an Online Food Ordering System with PHP and MYSQL, One of the feature of the application is to allow users to search for the restaurants by typing the area name. I would like to know using PHP for search will be more efficient or using Stored Procedure or using any third party tool. Efficient in the sense when it is to be searched among large set of data which one will be the fastest?


title: "Pythonic" equivalent term for code written in modern C++ style?

text: There's a lot of good idioms promoted in modern C++. These include RAII and elegant use of boost or STL or a `std::algorithm` to solve a given problem. Just like you can write C in any language, you can certainly write C in C++. However you can write really good modern C++ code with the right subset of features. When someone does something really cool with an STL or boost construct I always get the urge to call it "pythonic" in the sense that its the canocical elegant way to do something. Is there a term like how "pythonic" is used in python to refer to C++ code written in the modern style with modern idioms?


title: How to give the sense of a team that is fragmented based on projects?

text: The software engineering team of which I am part of is approximately 7 strong located in adjacent cubicles. 3 of us work on the same project but the rest are working on their own on different projects. In some cases one guy will be on his own on a project for nearly 1-2 yrs. There is no overlap in the projects that are being done as well. Currently I am one of those 3 guys working in the same project. So I have people to talk and discuss the problems and also to do some peer programming and reviewing. But everybody in the team have also been on a project just by themselves for about 2 yrs. It gives a very aloof feeling as you get further along the project. I was wondering if any of you guys were part of such a team and what did you guys do to have a healthy team spirit. Any thoughts/ideas are welcome. Thanks for your time. Cheers.


title: Can a random number generator ever produce different output given identical seeds?

text: The title sums it up. I'm interested to know if there exists an algorithm capable of producing variable output given identical input without relying on other sources for randomness such as DateTime.Now or a number generated from a light sensor etc. In addition, the algorithm can not be run in sequence, just two distinct, unrelated runs that produce different output.


title: Is there anyone who has used Python/Ruby and PHP for a long time and still prefer PHP?

text: I am usually fascinated by articles defending PHP and the arguments being used. Quite often authors of these types of articles don't mention what experience they have with other languages. Personally I find it hard to imagine that somebody would know either Python or Ruby, and PHP at a high level and still prefer PHP. So if anyone fits this description, I would be interested in hearing why you prefer PHP to either of these languages.


title: Do you think we will ever settle on a "standard" platform?

text: The recent explosion of phone platforms has depressed me (slightly), and made me wonder if we will ever reach any kind of standard for presentation? I don't mean language or IDE. Different languages have different strengths and I can see that there may always be a need for disparity, although I do note that languages are merging somewhat in functionality, with traditional imperitive languages like C++ now supporting things like lambdas. What I'm really talking about is a common presentation mechanism. Before smart phones and tablets came along, the web seemed to be finally becoming a reasonable platform for presenting an application that was globally accessible, not just geographically, but by platform too. Sure there are still (sometimes infuriating) implementation differences and quirks, but if you wrote a decent site you knew it could be accessed on anything from a PC to a phone to a C64 running the right software. "Write Once Run Anywhere" seemed to finally be becoming a reality. However, in the last few years we've seen an explosion of mobile operating systems, and the ubiquitous "app". A good site is no longer enough, you need a native "app", and of course we have a sudden massive disparity in OS, language, and APIs needed to write them as each battles for supremecy. It's kind of weird how the cycle of popularity goes. Mainframes with terminals - thin client. PC - thick client. Web browser - thin client. Phone app - thick(ish) client. I just wonder if you think there will ever be a global standard for clients, or whether the "shiny and different" cycle will always continue along with the battle of the tech du jour.


title: agile / scrum and functional specs

text: I work in a small team of four devs, one domain expert and one manager. We are looking to move to using scrum to try and formalise our processes. From what I understand of agile, it seems to be close(ish) to what we are doing anyway. We have a brief document with the overall features our product will have. As we come to code each feature, we sit down and thrash it out verbally, relying on our domain expert for what the customer will want. We then code it, and it gets tested in vague ways by the other devs / domain expert. Improvements get suggested and implemented. At our last ISO 9001 audit we were (deservedly) reprimanded for lack of any traceability. The auditor wanted some way of seeing we had records of what the product would do, and then testing to prove that it did it. We are looking to scrum to give us a process for this, along with other benefits, but my reading up so far has not answered my question of where detailed functional requirements are recorded / tested? My understanding of agile / scrum is far from complete, so please correct me if I have misunderstandings. As an example, let's say we have a user story that says: "As a customer, I need to be able to select a system state of A, B or C". It has an acceptance test that says "I should be able to select state A, B, or C, and the system will change to that state" Come the sprint where this gets implemented, we sit around and decide that we will build a widget with A, B and C radio buttons, and a "Apply" button. Then we code it. When this widget is tested, the following problems are found: 1. Selecting B sometimes doesn't uncheck the previous radio button. 2. Sometimes option C is unavailable on the system, and so should be greyed out. 3. When first opened, the initial selection does not match the current system state. My question is how and where is this recorded? There is no detailed functional spec saying "There will be a widget with three radio buttons. When the widget is created, the current radio selection should match the system state" blah blah. Given the lack of this document how are we supposed to prove that the system does or does not do what it's supposed to to an auditor?


title: What is "the right way" to do search on a website?

text: I'm talking the kind of search that auto-suggests your query as you type, the way Google does, the way Wikipedia does, the way Stack Exchange suggests other questions as you type the title, etc. And Wikipedia used to have an _awful_ search implementation, for those of us who remember. It had no auto-suggest, was shut down by the slightest typo or misspelling, and rarely gave pertinent results. As an amateur web programmer, I'm trying to figure out how I would implement an effective and high-performing search-and-auto-suggest as Wikipedia now has, and as SE has, and as so many other websites have. How can you obtain that kind of incredibly fast performance and flexibility? Does everyone just wing it, or are there principles, guidelines, helpful libraries, or other such resources to help you get it done right in the style of the "Internet of the Future"?


title: Is it recommended to use SQL Server as database for massively scalable applications?

text: Let's say you are planning to create a website of the scale of Facebook (If I am going to cite a website's name then why not Facebook?!). Is it recommended to use SQL Server as your database for such applications? I am asking this question because many colleagues of mine say that SQL server should not be used such applications. They prefer Oracle or MySQL instead.


title: Would a professional, self taught programmer benefit from reading an algorithms book?

text: I'm a 100% self taught, professional programmer (I've worked at a few web startups and made a few independent games). I've read quite a few of the "essential" books (Clean Code, The Pragmatic Programmer, Code Complete, SICP, K&R). I'm considering reading Introduction to Algorithms. I've asked a few colleagues if reading it will improve my programming skills, and I got _very_ mixed answers. A few said yes, a few said no, and a one said "only if you spend a lot of time implementing these algorithms" (I don't). So, I figured I'd ask Stack Exchange. Is it worth the time to read about algorithms if you're a professional programmer who seldom needs to use complex algorithms? For what it's worth, I have a strong mathematical background (have a 2 year degree in Mathematics; took Linear Algebra, Differential Equations, Calc I-III).


title: secure photos on server

text: I would like to hear advice from the more experienced developers. The project is now in the design stage. It's mobile application and a simple web application. Content is pictures, comments, personal correspondence. Pictures can be quite personal. Need a very serious attitude to security. The question is simple: **where to store photos and how to secure it?** I think it's will be in the following way:   1. User make some photo. Via SSL the application sends photo to the server.   2. The server recieve photo, encrypt it and store somewhere.  Also, via app the user can see all own photos.   1. Request to server for photos.   2. Server decrypt stored photos and send via SSL to client. I need some technical advices: where to save images, I know that database is quite slow for this case, which algorithms use for encrypt/decrypt, what about cache. It will be highload project and performance is very important. Mobile application is planned on cross-platform framework like phoneGap, Titanium. On the server is .NET. But it is planned. I also consider full stack frameworks for javascript.


title: Using a standard localised data cryptography pattern with an ASP.NET MVC3 application

text: I have been given the task to rejuvenate an existing Human Resources application from Access into ASP.NET. This is a strictly internal application, and I have no problems developing it within our standard ASP.NET environment. It does however pose it's own problems, both technically and ethically. The HR app will be responsible for storing employee pay data, for which it is not appropriate for me, the developer, to see. It's essentially three fields (salary band, actual salary, comments) and four other values, calculated on the front end. I'd like to go down the cryptography route to encrypt said data - cryptography with the .NET Framework is very easy to implement. I could "roll my own", which as we all know is a bad idea. However I was wondering if there was a _more better_ way of doing it. Here are some points:   1. For starters, we're all attached to the same domain.   2. I've heard and read about Certificates, can they be useful here? (x.509?)   3. The data will be stored in our local SQL Server, obviously the actual data here needs to be encrypted, so can SQL Server help me? Certificates again?   4. If a user doesn't have the appropriate certificate, can the data just be null? (You can't see this matey!)   5. This encryption problem doesn't have any relevance to usage of the system via a permissions model.


title: Most common "Y2K-style" bugs today?

text: I don't specifically mean date-related issues like 2038, but more generally, bugs that fit the pattern:   * A generation ago, programmers tended to write code that ass-u-me-d X, which was reasonable at the time.   * But circumstances have changed, and now X is a common source of problems that need to be fixed. For example:   * X = "Memory is too expensive to justify storing all 4 digits of the year. Don't worry about 2000; that's a long way off." (broken by Y2K)   * X = "Who needs `size_t`? We can just use `unsigned int`." (broken by 64-bit systems)


title: Designing application flow

text: I am creating a web application in java where I need to mock the following flow. When user trigger a certain process (add product to cart), I need to pass through following steps   1. Need to see in HTTP Session if user is logged in.   2. Check HTTP Session if shopping cart is there   3. If user exist in HTTP Session and his/her cart do not exist in HTTP Session   4. Get user cart from the database.   5. add item to cart and save it to HTTP session and update cart in DB.   6. If cart does not exist in DB, create new cart and and save in it HTTP Session. Though I missed a lot of use cases here (do not want question length to increase a lot), but most of the flow will be same as I described in above steps. My flow will start from the `Controller` and will go towards `Service` Layer and than ends up in the `DAO` layer. Since there will be a lot of use cases where I need to check HTTP session and based on that need to call `Service` layer, I was planning to add a `Facade` layer which should be responsible to do this for me like checking `Session` and interacting with `Service` layer. Please suggest if this is a valid approach or any other best approach can be implemented here? One more point where I am confused is how to handle `HTTP session` in facade layer? do I need to pass HTTP session object each time I call my `Facade` or any other approach can be used here?


title: What is your opinion of C++ Frequently Questioned Answers?

text: Do you think that the criticisms in Frequently Questioned Answers are accurate?


title: How do you keep track of what classes and functions your team has written?

text: When working on code, I face many of the same challenges that my teammates do, and I have written some helpful functions and classes, and so have they. If there is good communication, I'll hear about some great thing someone put together, and six months later when I need it I may remember it and call that function, saving myself time. If I don't remember it, or never knew about it, I will probably re-invent the wheel. Is there a particular practice of documenting these kinds of things? How do you make them easy to find? If your team has no such documentation, how do you find out if your wheel already exists? **EDIT:** All but one of the answers so far deals with an ideal situation, so let me sum up those solutions: documentation & communication; wikis, stand-up meetings, etc. Those are all great things, but they rely on programmers having the time (and skills) to write up the documentation and attend the meetings and take notes and remember everything. The most popular answer so far (Caleb's) is the only one that could be used by a programmer who is incapable of documentation and meetings, and does only one thing: programming. Programming is what a programmer does, and yes, a great programmer can write up documentation, unit tests, etc., but let's face it - most of us prefer programming to documenting. His solution is one where the programmer recognizes re-usable code and pulls it out to its own class or repository or whatever, and _by the fact that it is isolated,_ it becomes find-able and eases the learning curve for using it.... and this was accomplished by programming. In a way I see it like this: I've just written three functions, and it occurs to me that someone else should know about them. I could document them, write them up, announce them at a meeting, etc. - which I can do, but it's not my strength - or .... I can extract them to a class, name it well, make them function like a black box, and stick it where other class files go. Then a short email announcing it is easy. Other developers can scan the code and understand it better than they could an isolated function used in code they don't fully understand - that context is removed. I like this because it means having a set of well-named class files, with well-named methods, is a good solution that is accomplished by good programming. It does not require meetings, and it softens the need for detailed documentation. Are there any more ideas in this vein ... for isolated and time-pressed developers?


title: What C++ coding standard do you use?

text: For some time now, I've been unable to settle on a coding standard and use it concistently between projects. When starting a new project, I tend to change some things around (add a space there, remove a space there, add a line break there, an extra indent there, change naming conventions, etc.). So I figured that I might provide a piece of sample code, in C++, and ask you to rewrite it to fit _your_ standard of coding. Inspiration is always good, I say. ^^ So here goes:               #ifndef _DERIVED_CLASS_H__     #define _DERIVED_CLASS_H__          /**      * This is an example file used for sampling code layout.      *      * @author Firstname Surname      */                    #include <stdio>     #include <string>     #include <list>     #include "BaseClass.h"     #include "Stuff.h"                    /**      * The DerivedClass is completely useless. It represents uselessness in all its      * entirety.      */     class DerivedClass : public BaseClass {              ////////////////////////////////////////////////////////////         //   CONSTRUCTORS / DESTRUCTORS         ////////////////////////////////////////////////////////////          public:              /**          * Constructs a useless object with default settings.          *          * @param value          *        Is never used.          * @throws Exception          *         If something goes awry.          */         DerivedClass (const int value)          : uselessSize_ (0) {}              /**          * Constructs a copy of a given useless object.          *           * @param object          *        Object to copy.          * @throws OutOfMemoryException          *         If necessary data cannot be allocated.          */         DerivedClass (const DerivedClass& object) {}              /**          * Destroys this useless object.          */         ~DerivedClass ();                        ////////////////////////////////////////////////////////////         //   PUBLIC METHODS         ////////////////////////////////////////////////////////////          public:              /**          * Clones a given useless object.          *          * @param object          *        Object to copy.          * @return This useless object.          */         DerivedClass& operator= (const DerivedClass& object) {             stuff_ = object.stuff_;             uselessSize_ = object.uselessSize_;                 }              /**          * Does absolutely nothing.          *          * @param useless          *        Pointer to useless data.          */         void doNothing (const int* useless) {             if (useless == NULL) {                 return;             }             else {                 int womba = *useless;                      switch (womba) {                     case 0:                         cout << "This is output 0";                         break;                          case 1:                         cout << "This is output 1";                         break;                          case 2:                         cout << "This is output 2";                         break;                          default:                         cout << "This is default output";                         break;                 }             }         }              /**          * Does even less.          */         void doEvenLess () {             int mySecret = getSecret ();             int gather = 0;             for (int i = 0; i < mySecret; i++) {                 gather += 2;             }         }                        ////////////////////////////////////////////////////////////         //   PRIVATE METHODS         ////////////////////////////////////////////////////////////          private:              /**          * Gets the secret value of this useless object.          *          * @return A secret value.          */         int getSecret () const {             if ((RANDOM == 42) && (stuff_.size() > 0) || (1000000000000000000 > 0)                 && true) {                      return 420;             }             else if (RANDOM == -1) {                 return ((5 * 2) + (4 - 1)) / 2;             }                  int timer = 100;             bool stopThisMadness = false;             while (!stopThisMadness) {                 do {                     timer--;                 } while (timer > 0);                      stopThisMadness = true;             }         }                        ////////////////////////////////////////////////////////////         //   FIELDS         ////////////////////////////////////////////////////////////          private:              /**          * Don't know what this is used for.          */         static const int RANDOM = 42;              /**          * List of lists of stuff.          */         std::list <Stuff> stuff_;              /**          * Specifies the size of this object's uselessness.          */         size_t uselessSize_;          };                    #endif


title: Java Generics - how to strike a balance between expressiveness and simplicity

text: I'm developing some code that utilizes generics, and one of my guiding principles was to make it usable for future scenarios, and not just today's. However, several coworkers have expressed that I may have traded off readability for the sake of extensibility. I wanted to gather some feedback about possible ways to resolve this. To be specific, here is an interface that defines a transform - you start with a source collection of items, and you apply the transform to each element, storing the results in a destination collection. Additionally, I want to be able to return the destination collection to the caller, and rather than forcing them to use a Collection reference, I want them to be able to use whatever collection type they actually provided for the destination collection. Finally, I make it possible for the type of items in the destination collection to be different from the type of items in the source collection, because maybe that's what the transform does. In my code, for instance, several source items make up one destination item after the transform. This yields the following interface:               interface Transform<Src, Dst> {         <DstColl extends Collection<? super Dst>> DstColl transform(                     Collection<? extends Src> sourceCollection,                     DstColl                   destinationCollection);     }      I tried to be all nice and apply Josh Bloch's PECS principle (producer extends, consumer super) to make sure the interface is usable with super- and sub-types where appropriate. The end result is somewhat of a monstrosity. Now, it would have been nice if I could extend this interface and specialize it somehow. For example, if I don't really care about playing nice with subtypes of the source items and supertypes of the destination items, I could have:               interface SimpleTransform<Src, Dst> {         <DstColl extends Collection<Dst>> DstColl transform(                       Collection<Src> sourceCollection,                       DstColl         destinationCollection);     }      But there is no way to do that in Java. I want to make implementations of this interface something that others would actually consider doing, as opposed to running in fear. I've considered several options:   * Don't return the destination collection. Seems weird given that you do a transform but get nothing back.   * Have an abstract class that implements this interface, but then translates the parameters to something easier to use and calls another method "translateImpl()" which has the simpler signature and thus presents less of a cognitive burden for implementers. But then it's weird to have to write an abstract class just to make an interface user-friendly.   * Forgo extensibility and just have the simpler interface. Possibly couple that with not returning the destination collection. But then that limits my options in the future. What do you think? Am I missing an approach I could use?


title: Why do code generators always use fully-qualified identifiers?

text: When you look at the code for the Winforms Designer, you see things like this:               this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", ... etc.      instead of               using System.Drawing;     label1.Font = new Font("Microsoft Sans Serif", ... etc.      The same is true of tools like Linq to XSD, XSD2Code and, I suspect, of Linq to SQL. These tools generate hoards of code with extremely long fully- qualified names. Wouldn't it be easier to generate the appropriate `using` statements, and ditch the long names? Or is there some technical reason for this that I'm missing? * * * **Note:** For those folks that are baffled by the notion that I might want these classes to actually be readable by a human, note that this is exactly my goal. I have an XSD with about 300 classes in it, I don't want to write them all by hand, and yes, I'd like them to look like ordinary code written by humans.


title: What is good practice when inheriting static classes isn't possible/allowed

text: I am developing a project in C# and due to a design decision it is not possible to have a static class inherit another static class. But I have, in my opinion, a case where this would make sense. I have a music player which is able to play music from many different music sources: local files, YouTube, SoundCloud, Jamendo, etc. I have currently one static class for each of these sources with static methods such as retrieving the top tracks, searching for tracks, etc. Naturally, a lot of code is shared among all these classes so I wanted to refactor and put all common code into a more generic MusicSource class. But C# doesn't allow me to do that. What would be the best practice here? I want to get rid of all my redundant code and make it easier to create new music sources.


title: Help needed with class design and structure

text: This question is mostly about the best way to approach this problem. Any input is appreciated. ### The Problem In my application i need to send some data to a number of different destinations (we will call them receivers from now on) using different protocols (http post, ftp, soap services). Each of the different receivers respond differently and some processing needs to be done on each response to work out what happened. This response processing can become quite complex. My application also needs to do take different actions based on the receiver. ### My Solution My plan is to create a separate class for each receiver that implements an interface and use Factory design pattern to decide which class to load based on the receiver. Each receiver has a unique name (which is stored in the database for other reasons) which i plan to use to decide which receiver to load. I'll pass this to the factory constructor. Currently i plan to have my interface implement these methods   * prepareData()    * sendData()    * handleResult() I'd also like a wrapper for these function such as process() which would just return a boolean based on wether the send sent. I'm not sure where i would fit this in though. Thanks


title: How to develop line-of-business tablet apps as a .NET developer?

text: My company has a lot of experience in .NET development, and one of our products in an ERP system. Recently, a customer asked us if we could provide a tablet interface to that system, i.e., a software that allows the customer to view product information and create orders on a tablet. Of course, we are not thrilled about the idea of investing a lot of time and money into learning Objective-C, purchasing Mac development workstations, paying fees to Apple, etc. just for this one project (we _might_ be able to sell the app to a few additional customers afterwards, but the market is very small, since it would only be useful for existing customers of our ERP system). So, what should we do? As far as I can see, we have the following options:   * Write a " **plain old Windows application** " (WPF) and run it on a Windows 7 tablet, such as the Samsung Slate or Acer Iconia. Drawbacks: Heavy, expensive devices with short running time (as compared to "real" tablets).   * Wait for **Windows 8 ARM-based tablets** and write a Metro (WinRT) app. Drawbacks: Wait for at least one year; it's unclear whether Windows 8 ARM will support installation of custom B2B apps without going through the app store.   * Use **mono for Android** and write a .NET app for Android. Drawbacks: Yet another UI library (different from WPF and Silverlight); some providers disallow sideloading of apps. So far, options 1 and 3 seem to be the most realistic. Did I miss any obvious drawbacks or advantages? Is there another option that I haven't considered yet? Have you been in a similar situation and (successfully) chosen one particular option?


title: Is it plausible to use a filesystem-based configuration format rather than an INI file?

text: After having had endless issues with INI-style configuration files and parsing them correctly (let along getting binary data right), a crazy idea crossed my mind recently: What if an INI file like               # settings.ini     [Windows]     DirectorySeparator='\\'     PathSeparator=';'          [Linux]     DirectorySeparator='/'     PathSeparator=':'      Would rather be stored in the file system; each group is a directory, each key/value pair is a file, so               settings/Windows/DirectorySeparator (contains just `\`)     settings/Windows/PathSeparator      (contains just ';')     ... you get the idea ...      Disadvantages:   * Possibly slow due to IO work, but maybe file system caches help?   * Running low of inodes on some file systems?   * Group/Key names may only consists of characters which are also valid for directory/filenames, may be rather restrictive depending on the FS. Advantages:   * Arbitrarily deeply nested groups   * No worries about escaping, binary data is easy. Just have each file contain the raw data.   * Automatic locking, access control and whatever the filesystem provides   * Easy to access with most programming languages, even by hand I'm very tempted to try this in my next project, I wonder whether anybody else has experience with this approach already?


title: Choose C++ or Java for applications requiring huge amounts of RAM?

text: I'm thinking of scientific applications that are mostly processor-bound and heavy on heap usage (at least several gigabytes). Any other time of the year I would happily go with C++, but in this case I wonder if the fragmentation natural to the C++ memory manager can be a serious issue versus the advantage of Java's compacting collectors. Can anybody point to real-world examples related to this?


title: Approach to statically analyze a Python code base

text: What approach should I use to statically analyze a Python code base? In particular, I am looking for ways to:   * extract and display the class hierarchy,   * extract and display class relationships,   * include a cross-reference of all functions, modules and variables The specific application that I am dealing with is not well documented which is why I am looking to automate the process.


title: Why must the burden of proof rest with the caller and not the method of the class that is being called?

text: Michael Perry states in his Pluralsight course on Provable Code (transcript subscription only) that: > [T]he burden of proof rests with the caller In a code contract, why must the burden of proof rest with the caller and not the method of the class that is being called? Is this a preferred convention or does it have a more solid basis? At the moment it just like a dogma to me as the class being called could make its own safety checks, which would reduce calling code duplication.


title: How To Build An iPhone App With A Web Server?

text: I have an iPhone app out that stores data on the device. I want to create an app with user accounts like Instagram, Path, Foursquare, Gowalla, etc. What would you recommend for the quickest and easiest way to get an app of this nature (social, iPhone) going? I'm deciding between RoR or PHP still. Will the final stack come down to: iPhone --> RestKit --> RoR/PHP --> MYSQL? I have a solid background in iOS development, but not the rest.


title: Google App Engine, what are the advantages and limitations?

text: First, does anyone know a specific advantage of Google App Engine for Python Apps? Is there some advantage over Heruko or Appfog? And about the database API? Now, what about the limitations? Are there any factors that make you think twice about using GAE?


title: Why is the Unit of Work pattern considered fast and efficient when working with an ORM?

text: In working with Doctrine 2 I came across the following paragraph. > In fact, since Doctrine is aware of all your managed entities, when you call > theflush() method, it calculates an overall changeset and executes the most > efficient query/queries possible. For example, if you persist a total of 100 > Product objects and then subsequently call flush(), Doctrine will create a > single prepared statement and re-use it for each insert. This pattern is > called Unit of Work, and it's used because it's fast and efficient I am not up to speed on relational databases and ORM theory so I was wondering why is the Unit Of Work pattern  considered fast and efficient?


title: Orthogonal design for product pricing and production planning with a NoSQL database

text: I am in the process of developing extensible software for the company I am working with for product pricing and production planning. **The Present Scenario** There are basically two types of products: manufactured and traded (simple buy and sell with no conversion). Manufactured can be regular or made-to-order with made-to-order mostly being a deviant of the regular model. There is only a finite number of products (around 2000) but each product has got multiple attributes such as size, color, shade and more. Presently, there is software for order management with inventory and a decent accounting package. Costing and pricing is now done on an arbitary basis via sampling a few models and adding overhead and margin percentages. **Required**   * To calculate product cost per unit   * Convert them into a valid pricing model (pricing may differ upon quantity and other factors),   * Calculate exact cost and profitability per product,   * Proactively plan production for regular models and made-to-order units, based on existing order management system and inventory **Proposed Design** I have proposed the following design.   * Store product information for each unique product in document-style based on the 5M's of production (Man, Material, Machines, Methods and Money)   * A separate module of each of the four M's - Men, Machine, Material and Methods in terms of Money with primitive building blocks for each module that can be merged and combined into a compound block    * Store metadata and result set required along with each document   * A separate layer to parse metadata, act upon data based on metadata and return result set as defined (similar to a DSL with both metadata and result set redefined at runtime)   * A separate pricing model that works on the cost of the product   * A separate production planning module that works on the data of the order management system and the product information   * Using MapReduce to aggregate data and analyze it   * Technologies: MongoDB, Python, Django, and NumPy All data to be stored in JSON format with all business logic written to parse a JSON file (technically, in my case a Python dictionary) and produce output based on keys and values. **So why am I here?** The present software company has recommended a traditional out-of-the-box RDBMS system that could be customized. The main problem I find with the system is the duplication of data for products with varying attributes, lack of analytical tools, tight coupling with products and prices and too many joins for complex queries, but it is recommended for better robustness and better aggregate analysis and the XXXX always told market runs this approach. Since the entire software is not to be used in real-time and most of the real-time sytem links to unique products only.   * Does my proposed design is truly orthogonal?   * Does loose-coupling product, cost and pricing work?   * What is the general approach for this kind of problem?   * Do MapReduce provide a better way to analyze data for this kind of problems (along with NumPy) than the traditional SQL approach Basically I work with numbers, and I am thinking of a generic model which I could extend in the future.


title: Which is the most permissive open-source license?

text: Which is the most permissive open-source license available? "Permissive" would be defined as "the minimal requirements about how the software can be redistributed".


title: Need advise for porting linux script to Win command line

text: I am creating app(script) that is used similar to RSS reader for specific webpage that doesn't have RSS. So my app downloads that html page in defined intervals, checks new items and parses them into messages that are sent over network. But my app prototype is written in Bash (Linux is my primary OS), and I was asked that this app will be needed on Windows also - luckily WinXP 32bit only. So I am deciding how rewrite it easily and without testing various scripting languages and technologies. Currently my app is working with Bash, and calls for unix utilities like sed, wget and curl. I checked that these utilities are for win32 also. So my question is about Windows commandline capabilities compared to linux bash. Does wincmd have similar capabilities like bash? In e.g. manipulating strings, cycles or something that might be a problem? I also found Cygwin, but don't know if it works reliable and this is important in this case of app.


title: Performance vs. Laziness: Why use setters from within a class?

text: I notice that web related code uses setter methods to set class fields instead of setting them directly since they are in scope. I find this to be a bit odd. Using setters is certainly safer, but if unit tests are implemented then bugs will be found. And it's not worth the extra stack call, imo. Does any production code do this or is this just what you see in sample code online? Edit: I have to make clear that I'm only talking about the case whereby the setter consists solely of a single assignment expression and nothing more.


title: Web design standards

text: While designing web pages using php, are there standards that should be followed? For example suppose there are two pages. First page looks like this:               <body>     <div>     <?php include 'page2.php';?>      `page2.php` file looks like this:               <?php print 'some text';?>     </div>     </body>      Is such designing a standard practice? Does it affect search engine results?


title: Will experience suffice for a Computer Science degree

text: I am debating on a career in programming. The problem for me is that I don't think college is right for me. I am planning on joining the Air Force as a Computer Systems Programmer will they will train me and I will gain some college credits. From what I can understand there is a large amount of people taking a major in Computer Science because they hear computers make money. Most drop out but some do graduate but find they don't really know anything about programming. Ive always heard the issue being that these students often get good grades but don't push themselves to learn beyond the course. I'm a very self motivated learner and I am having a blast learning C++ as well as I love computers and have since before I could even read or write. So learning the actual trade isn't the issue. I could go to college for free or nearly free. I will most likely enlist for 6 years. But when (or if I decide to make a career out of it) I get out of the military will I be able to find a job with 6 years of experience in lieu of a degree. I would assume i would because said employer would know if I could do the work rather then having to deal with some college kid who there not even sure if he knows how to program.


title: Is it a priority for a web developer to be familiar with the source code of a web browser?

text: How important is it for a developer that deals with web applications (let's say writing html and js) to download a browser's source code (like Chromium) and learn how the engine works (renderer, javascript vm, network processing, etc.)?


title: Using requirements for a completed company project as a basis for a personal learning project

text: Background: I want to learn, try out new frameworks, tools, languages, but I'm terrible at coming up with something to build. The company I work for recently completed work on building a piece of software for internal use. I was not involved in the project at all. The software is purely internal, we do not sell it on. The results are not what people hoped for. Is it acceptable for me to build my own solution in my own time but use the requirement documentation for the companies project? Are there pitfalls I should watch out for with this approach, things I can do to mitigate those risks? Alternatively I could build it the way I think it should be done without referencing those docs. Is this the better approach as it definitely frees me to do what I like with the code afterwards?


title: Design pattern for polymorphic behaviour while allowing library separation

text: Let's say I have a hierarchy of `Item` classes: `Rectangle, Circle, Triangle`. I want to be able to draw them, so my first possibility is add a virtual `Draw()` method to each:               class Item {     public:        virtual ~Item();        virtual void Draw() =0;      };      However, I want to split the drawing functionality to a separate Draw library while the Core library contains only the basic representations. There's a couple of possibilities I can think of: 1 - A `DrawManager` that takes a list of `Item`s and has to use `dynamic_cast<>` to work out what to do:               class DrawManager {       void draw(ItemList& items) {         FOREACH(Item* item, items) {            if (dynamic_cast<Rectangle*>(item)) {               drawRectangle();            } else if (dynamic_cast<Circle*>(item)) {               drawCircle();            } ....         }       }     };      This isn't ideal as it relies on RTTI and forces one class to be aware of all items in the hierarchy. 2 - The other approach is to defer drawing responsibility to an `ItemDrawer` hierarchy (`RectangleDrawer`, etc):               class Item {        virtual Drawer* GetDrawer() =0;     }          class Rectangle : public Item {     public:        virtual Drawer* GetDrawer() {return new RectangleDrawer(this); }     }      This achieves the separation of concerns between the base representation of the Items and the code for drawing. The problem though is that the Item classes are dependent on the drawing classes. How can I separate out this drawing code into a separate library? Is the solution for the Items to return a factory class of some description? However, how can this be defined so that the Core library isn't dependent on the Draw library?


title: How to find a 'good' seed page for a web crawler?

text: I started building a web crawler and read somewhere that it's a very hard problem to find a good seed page for the crawler. Can anyone explain me if there is any pre-defined procedure/ guidlines of finding a good seed page? or how you say that a particular page is a good seed page?


title: Keeping binary search tree balanced

text: I am educating myself on algorithms and data structures. For that, I am doing a simple program that would read lines like this:               bdhj 168.24     dahf 42.88     dhfa 128.92      First column represents an account name (and it needn't have to be 4 characters), and second represents value to add (or remove if value is negative) to that account. I have a huge test data that I could profile different algorithms. I tried keeping this information in linked list and dynamic arrays and some mixture of that two so far. Although dynamic arrays were good at allowing binary search, inserting elements requires a call to memmove (since I am inserting sorted) and it takes a lot of time. I want to try binary search trees for this program, however, I don't have any idea how to keep search tree balanced. I tried google search, but couldn't find any explanations about a algorithm I could use, or any pointers at all. Could you give pointers and/or sources that I could check?


title: Changing __class__ in a factory?

text: I'm parsing a set of XML files of different kinds (these kinds are known in advance). These are my requirements:   * I want an object to represent each XML document (object-xml mapping)   * I'd rather have a different class for each kind, so that identifying the type of the XML file is equivalent to looking at the class of the instance   * I don't know the kind in advance   * I want some specific behaviour for each object But for the sake of simplicity, let's consider, I just need to open different numbers, of two know kinds:   * even number   * odd number In term of design pattern, I use a variation of the _factory design pattern_ , where the afctory is in the `__init__` of the top level class, and I set the correct implementaion by a changing `__class__` dynamically               class Number():         def __init__(self, val):             # common implementation (in case of XML, I do the recursion of xml imports)             self.value = val                  # This is also the point where I discover the type of my object             # Hence, the constuctor is also a factory of the appropriate type             if val % 2 == 0:                 self.__class__ = EvenNumber             elif val % 2 == 1:                 self.__class__ = OddNumber             else:                 # keep the default Number implementation                 pass               class EvenNumber(Number):         def half(self):             '''              specific behaviour for even numbers             '''             return self.value / 2               class OddNumber(Number):         def next_int(self):             return self.value          if __name__ == '__main__':         for x in (Number(2), Number(3)):             '''             In the main algorithm, the processing depends on the type of the object             '''             if isinstance(x, EvenNumber):                 print(x.half())             elif isinstance(x, OddNumber):                 print(x.next_int())      What do you think about this approach? I knew `__class__` could be read, and was very surprised it can also be written. What do you think of changing `__class__` dynamically? Is this a well-known design pattern (it is not the _factory pattern_ nor the _state pattern_ nor the _strategy pattern_ , even if it seems related to all of them) **Edit** My real use-case I want to open a XBRL taxonomy, which is made of XML linkbases. Except the generic XML Linkbase, I want to handle more precisely some of them:   * XML Label linkbase   * XML Definition linkbase   * etc. In substance, here is what I have done:               class Linkbase(etree.xml.ElementTree):         '''         Generic linkbase         '''         def __init__(self, filename):             # parse XML             if self.type == 'definition':                 self.__class__ = DefinitionLinkbase             elif self.type == 'label':                 self.__class__ = LabelLinkbase               @property          def type(self):             return self.find('//xpath/expression').tag          class LabelLinkbase(Linkbase):        @property        def labels(self):          # find all appropriate elements and returns a list of Labels          class DefintionLinkbase(Linkbase):        @property        def definitions(self):           # returns all definitions      Alternatively, I could have used a factory. I can think of something like this, but it doesn't look as elegant as the first approach.               class Linkbase(etree.xml.ElementTree):         '''         Generic linkbase         '''         def __init__(self, tree):             self.tree = tree               @property          def type(self):             return get_type(self.etree)          class LabelLinkbase(Linkbase):        @property        def labels(self):          # find all appropriate elements and returns a list of Labels          class DefintionLinkbase(Linkbase):        @property        def definitions(self):           # returns all definitions          def build_Linkbase(file):         tree = etree.parse(file)         if get_type(tree)== "defintion"            return DefintionLinkbase(tree)         elif get_type(tree) == "label":            return LabelLinkbase(tree)         else:            return Linkbase(tree)     def get_type(tree):         return tree.find('//xpath/expression').tag


title: URL and Controller structure for parent-child-relationship

text: I use an MVC web framework to create an application which contains a hierarchy:               Location <1-N> Devices <N-M> Services      I have a number of Locations. Each Locations can have several devices (represented by an 1-N relationship in the database). Each device runs services. The services (like http, ftp, etc) are defines in an extra table and are connected to the devices using an N-M relationship. So far I have a model for each of the entities and one Location-controller for CRUD operations. Since the devices somehow belong to the location all the device CRUD-functions are located in the location controller as well. The services have their own controller. The url to access the data is structured like this:               /locations/    # to get an overview of the locations     /locations/*id*/    # to view the details of one location     /locations/*id*/edit    # to edit the details of one location     /locations/*id*/device/*deviceid*/    # to view details of a device     /locations/*id*/device/*deviceid*/edit    # to view details of a device     /services/     # list of all the services     /services/*id/    # view details of a service      Note: There are also urls to create and delete entries, which are omitted. But I think you get the idea. Now to my questions: It feels wrong, and I think it is wrong to put all the functions inside the Location-controller, therefore I would like to move them so separate controllers. On the other hand, I like the URL-Structure, since it represents the hierarchy of the data pretty well. Furthermore I like when the URL structure corresponds with the Controllers. What is the "better" solution: Separate controllers with combined URLs? Separate controllers, separate URLs? Or combined controller with combined URLs?


title: is there a programming language designed to express data combinations?

text: Very often, when using the command line or just programming, you want to express some kind of combination that you end up using a `for` - which is often verbose.               for (int i = 0; i<10; ++i)         std::cout << "img_" << i << std::endl;          for f in *; do echo "$f"; done      I always wondered if there is some kind of language made to simplify this case? For example:               "mv img_[0~6] imgs"      Would translate to               mv img_0 imgs     mv img_1 imgs     mv img_2 imgs     mv img_3 imgs     mv img_4 imgs     mv img_5 imgs      `img_[0~1][0~1]` could work for `img_00, img_01, img_10, img_11` `img_[x:0~2][x]` could work for `img_00, img_11, img_22` Etc. I'm not asking for this particular syntax, just if there is any kind of language/feature ever implemented with the purpose of expressing such combinations as easy as possible?


title: Not sure how to study Web programming

text: Hello everyone and thank you for your time :) So I'm a 17 portuguese boy and I'm thinking about starting a website, but because I don't have much money I decided I'd need to learn how to do it myself. So I got several books on the main languages ([X]HTML, AJAX, JS, PHP, MySQL, CSS) but I'm not sure what to do with them. I started studying them in January and, for I thought this was hard, I decided to basically copy the books into several notebookes, and then, once I got the general picture of how these languages operate, I'd restart and starting apply the knowledge. However, this is taking too long. I've been studying this for over 6 months now, wasted over $20 in notebookes, and still there are several books that remain untouched. I'm thinking: maybe it would be a better approach to simply study the books and directly apply the knowledge and keep doing that, step by step, instead of overkilling like this. Meaning: instead of taking notes as you'd do in a normal school class, simply ignore that and dive right into the action and learn from experience. Thoughts? :) Thanks again.


title: How can I unit test audio?

text: I have inherited a small project and want to extend it and stabilize it at the same time by writing Unit Tests for all the new code I am adding. The first class, `TypedAudioCreator`, creates audio files and this turned out to be very easy to test first and write code for second. However, when it came time to write `TypedAudioPlayer`, I had no idea how I could test it. It's a very small class focusing on the very basics of playing sound:               public class TypedAudioFilePlayer     {         public event StartedPlayingHandler StartedPlaying;         public event StoppedPlayingHandler StoppedPlaying;              public readonly int TimeBetweenPlays;              private Queue<TypedAudioFile> _playlist = new Queue<TypedAudioFile>();               public TypedAudioFilePlayer(int timeBetweenPlays)         {             TimeBetweenPlays = timeBetweenPlays;         }              public void AddFile(TypedAudioFile file)         {             _playlist.Enqueue(file);         }              public void StartPlaying()         {             ThreadPool.QueueUserWorkItem(ignoredState =>             {                 while (_playlist.Count > 0)                 {                     var audioFile = _playlist.Dequeue();                          if (StartedPlaying != null)                         StartedPlaying(audioFile);                          audioFile.SoundPlayer.PlaySync();                     audioFile.SoundPlayer.Dispose();                          if (StoppedPlaying != null)                         StoppedPlaying(audioFile);                 }             });         }              public void StopPlaying()         {             if (StoppedPlaying != null)                 StoppedPlaying(null);         }     }      I'm still very new at TDD, but I realize the benefits of the practice and would like to try and get better at it. I have written Code first, no tests here, but that was just me being too lazy to properly think of the TDD way of solving it. The question I have is, how should/could I test this class?


title: Should I be bothered if my LOC/day ratio is too high?

text: I'm currently working on an indie project, so I don't exactly have the luxury of throughout human testing or external code review — however, I don't see any difficult bugs in my current code (I fix them as I see them, and most of the time they're just wrong field names and such, things that you fix in a minute or two), and I test it after implementing any feature before pushing it. Lately my LOC number was about 400 a day (for the record, it's C#), and I'm not only implementing new systems, but also rewrite things I've already written and fix some bugs. Should I be bothered? Is it the sign that I need to stop and review all the code I've been writing up to this date and refactor it?


title: Object Oriented Design

text: Suppose you have the following:                    +--------+     +------+          | Animal |     | Food |          +-+------+     +----+-+            ^                 ^            |                 |            |                 |       +------+              +-------+       | Deer |              | Grass |       +------+              +-------+      `Deer` inherits from `Animal`, and `Grass` inherits from `Food`. So far so good. `Animal` objects can eat `Food` objects. Now lets mix it up a bit. Lets add a `Lion` which inherits from `Animal`.                    +--------+     +------+          | Animal |     | Food |          +-+-----++     +----+-+            ^     ^           ^            |     |           |            |     |           |       +------+ +------+     +-------+       | Deer | | Lion |     | Grass |       +------+ +------+     +-------+      Now we have have a problem because `Lion` can eat both `Deer` and `Grass`, but `Deer` is not `Food` it is `Animal`. With out using multiple inheritance, and using object oriented design, how do you solve this problem? FYI: I used http://www.asciiflow.com to create the ASCII diagrams.


title: Introducing Scala to a Technical Manager

text: I've been promoting Scala at work as something we should try out for things like testing with Specs http://code.google.com/p/specs/ and rapid prototyping of web services with tools like Scalatra https://github.com/scalatra/scalatra and Lift http://liftweb.net. A technical manager is interested in hearing more about Scala, and has no experience with the language. I've pointed out how Scala prototypes could be written quickly and deployed into our existing Java infrastructure as well as use our existing Java libraries. He is largely interested in the specific benefits of using Scala over Java and will be interested in concrete examples. I'd like to hear any thoughts or experiences people have introducing Scala to technical management. Thoughts on good code, clear, concise examples that demonstrate a big win over the Java equivalent, would be greatly appreciated. Some examples areas for discussion I have been thinking about are: **REPL**   A big win over Java, and I use it every day to test the Java code I am writing. **Basic Collection Iteration**   One of the first areas I think Java programmers can see immediate benefit. **Type Inference**   We use a lot of Python at work - I think less type boilerplate in a strongly typed language will be appealing. **Java Integration**   Given our Java investment, this will be a biggie. **Concurrency**   A brief run through of Akka actors and the new parallel collections. I'd love to see any small, focused examples anyone has here. **Specs**   I've been finding BDD with Specs excellent for testing Java applications. **Web development**   I've found Scalatra ideal for rapid development of REST services. Please share any other areas you think might be of interest as well as any focused code examples in these or other areas you think demonstrate advantages of Scala over the Java equivalent. **EDIT:** To be perfectly clear I am primarily interested in **concise concrete code examples** appropriate to this situation. Not at all interested in another "Java vs Scala" thread. I hope that was clear. Something like: **Java:**                 Foo theFoo = null;     for(Foo aFoo: allTheFoos) {       if (aFoo.getId().equals(theIdIWant)) {         theFoo = aFoo;         break;       }     }      **Scala:**                 val thefoo = allTheFoos.find(aFoo.id == theIdIWant)


title: exception for string literal conventions

text: If I'm used to use ' for string literals in PHP, would it be better if I'll stick to it in any situation or can there be exceptions when it would increase readability? example: `$foo = "bar'baz"; // this may be easier to read $foo = 'bar\'baz'; // but this would stick to the convention`


title: What to call objects that may delete cached data to meet memory constraints?

text: I'm developing some cross-platform software which is intended to run on mobile devices. Both iOS and Android provide low memory warnings. I plan to make a wrapper class that will free cached resources (like textures) when low memory warnings are issued (assuming the resource is not in use). If the resource returns to use, it'll re-cache it, etc... I'm trying to think of what this is called. In .Net, it's similar to a "weak reference" but that only really makes sense when dealing with garbage collection, and since I'm using c++ and shared_ptr, a weak reference already has a meaning which is distinct from the one I'm thinking of. There's also the difference that this class will be able to rebuild the cache when needed. What is this pattern/whatever is called? Edit: Feel free to recommend tags for this question.


title: How can I secure a request handler so I only respond to the correct clients?

text: Here's the scenario... I have a web site that has a generic handler written in asp.net (.ashx file) that accepts http requests, gets relevant data, converts the result into xml and then passes that back via the response. This will eventually be used so that a windows application can make data requests to this web site. My concern is that anyone who knows how to put together the request can then access potentially personal data. The data isn't anything as sensitive as financial information, but it will have names and addresses so I obviously need to think about securing it. My initial thought was to encrypt the information before responding, and maybe even encrypt the request as well, and I'm happy to do this, but I just wanted to ask some other boffins for their opinion on the matter. Is this something that has a "standard" way of doing it, or is it simply a case of thinking of something suitable and implementing it. Incidentally, the windows app will be distributed all over the country so the requests will come from many places. Using the IP address is not only a laborious way of doing it, but it also doesn't help as you could obviously send the message from an IP without using the application. TL;DR How do I make sure that it was my windows app that asked my web app for information?


title: What do I need to know about Data Structures and Algorithms in the "real" world

text: I just finished the data structures and algorithms course in school , I took it during the summer so 6wks course vs a 16 wk course during the regular semester. So not only was the course hard but it was really really really fast. My question is what do I need to know about data structures in the real world? I understand what they do and how they work, for the most part, but I had a real tough time coding them , I wouldn't be able to write the code for a binary tree class or a balanced tree class from scratch .... Is that bad? should I retake it , or is knowledge of how they work sufficient, without being able to write the classes from scratch?


title: What are some ramifications of open source software turning into closed source software?

text: If a company takes a permissively licensed open source application and then develops a closed source application from that by reworking extensive parts of the application, adding new features and applying bug fixes... Ignoring any license requirements...   * How does the transition happen and what can be done to prevent it beyond choosing a difference license?   * What are the (ethical or social) responsibilities for the company? (For example: Giving back to the open source project would be the ethical thing to do)   * If the open source version and closed source version are both available, how does the competition affect either product? Are there any examples of companies or products that have done this (either successfully or unsuccessfully) in the past? What was the community attitude toward those projects?


title: Assembly as a First Programming Language?

text: How good of an idea do you think it would be to teach people Assembly (some variant) as a first programming language? It would take a lot more effort than learning for instance Java or Python, but one would have good understanding of the machine more or less from "programming day one" (compared to many higher level languages, at least). What do you think? Is it a realistic idea, at least to those who are ready to make the extra effort? Advantages and disadvantages? _Note: I'm no teacher, just curious_


title: Eclipse RCP - Programming or configuring?

text: when I develop a RCP application I always ask myself should I do it 'by hand' or should I use the XML configuration? Is it only a matter of taste, what benefits am I missing when I don't use the configuration approach. Is there anything to think of when converting an RCP app to e4 in the future? Thanks for sharing your thoughts! Thomas


title: Inheritance vs mixins in dynamic languages?

text: **When should you prefer inheritance patterns over mixins in dynamic languages?** By mixins, I mean actual proper mixing in, as in inserting functions and data members into an object in runtime. When would you use, for example, prototypal inheritance instead of mixins? To illustrate more clearly what I mean by mixin, some pseudocode:               asCircle(obj) {       obj.radius = 0       obj.area = function() {         return this.radius * this.radius * 3.14       }          myObject = {}     asCircle(myObject)     myObject.area() // -> 0


title: Visual Studio's Developer License duals as a personal license?

text: I can be completely wrong but I vaguely remember hearing from a podcast that according to Visual Studio's license, a developer who works with Visual Studio professionally at their work place automatically has the license to use it in their personal life. That means a developer may not have to pay for Visual Studio to legally use/own it. Again, I can be completely wrong but if I'm right, can someone confirm with a source?


title: Is there any "real" reason multiple inheritance is hated?

text: I've always liked the idea of having multiple inheritance supported in a language. Most often though it's intentionally forgone, and the supposed "replacement" is interfaces. Interfaces simply do not cover all the same ground multiple inheritance does, and this restriction can occasionally lead to more boilerplate code. The only basic reason I have ever heard for this is the diamond problem with base classes. I just can't accept that. To me, it comes off an awful lot like, "Well, it's _possible_ to screw it up, so it's automatically a bad idea." You can screw up anything in a programming language though, and I mean anything. I just cannot take this seriously, at least not without a more thorough explanation. Just being aware of this problem is 90% of the battle. Furthermore I think I heard something years ago about a general-purpose work-around involving an "envelope" algorithm or something like that (does this ring a bell, anyone?). Concerning the diamond problem, the only potentially genuine problem I can think of is if you're trying to use a third-party library and can't see that two seemingly unrelated classes in that library have a common base class, but in addition to documentation, a simple language feature could, let's say, require that you specifically declare your intent to create a diamond before it'll actually compile one for you. With such a feature, any creation of a diamond is either intentional, reckless, or because one is unaware of this pitfall. So that all being said...Is there any **real** reason most people hate multiple inheritance, or is it all just a bunch of hysteria that causes more harm than good? Is there something that I am not seeing here? Thank you. **Example** Car extends WheeledVehicle, KIASpectra extends Car and Electronic, KIASpectra contains Radio. Why doesn't KIASpectra contain Electronic?   1. Because it _is_ an Electronic. Inheritance vs. composition should always be an is-a relationship vs. a has-a relationship.   2. Because it _is_ an Electronic. There are wires, circuit boards, switches, etc. all up and down that thing.   3. Because it _is_ an Electronic. If your battery goes dead in the winter, _you're in just as much trouble as if all your wheels suddenly went missing._ Why not use interfaces? Take #3, for instance. I don't want to write this over and over again, and I _really_ don't want to create some bizarre proxy helper class to do this either:               private void runOrDont()     {         if (this.battery)         {             if (this.battery.working && this.switchedOn)             {                 this.run();                 return;             }         }         this.dontRun();     }      (We're not getting into whether that implementation is good or bad.) You can imagine how there may be _several_ of these functions associated with Electronic that are not related to anything in WheeledVehicle, and vice-versa. **Edit** I wasn't sure whether to settle down on that example or not, since there is room for interpretation there. You could also think in terms of Plane extending Vehicle and FlyingObject and Bird extending Animal and FlyingObject, or in terms of a much purer example.


title: Connecting a native iOS app to backend and database

text: I have a good amount of experience working with objective-C and making iOS apps that work locally and with BaaS providers (Parse.com). However, I'd like to take my mobile development to the next level and I'd like tips on the order in which to do things and tips on which services/technologies to use. So, I need a database, and a place to host my database. I've used Amazon AWS for some things, and I can easily set up a mySQL DB on an EC2 instance there. Alternatively, I've heard that GAE is very useful. I don't really know if I have to write any back-end code. It seems to me that objective-C can take the place of my back-end code. Is that secure? Should I be making an entire service that is simply called from the iPhone? So, I know that it's a loaded question, and it may require a few different opinions to really round out a good answer. Sorry about that. But, assuming that I am proficient enough with Obj-C to make anything happen client side, and that I'm sentient enough to learn other languages that I might not know and follow tutorials and examples online - What are the steps (and the best technologies/services at each step) to making a native iOS app that does not use a BaaS provider like Parse.com or Stackmob.com. Thanks!


title: Common diagnostics which VisualVM is used for

text: There's a lot of documentation out there on how to _use_ the 'jvisualvm' profiler, but very little (if any) real-life advice on how to _analyze_ all those charts and dumps. I'm just a little overwhelmed by all the graphs and having trouble making sense of it all. I know this is sort of a monolithic-type question, but there _has_ to be a way to condense its _typical_ uses into a fairly concise list - finding memory leaks, zombie threads and such. What specifically are some of the common analyses for VisualVM?


title: Should I force users to update an application?

text: I'm writing an application for a medium sized company that will be used by about 90% of our employees and our clients. In planning for the future we decided to add functionality that will verify that the version of the program that is running is a version that we still support. Currently the application will forcequit if the version is not among our supported versions. Here is my concern. Hypothetically, in version 2.0.0.1 method "A" crashes and burns in glorious fashion and method "B" works just fine. We release 2.0.0.2 to fix method A and deprecate version 0.1. Now if someone is running 0.1 to use method B they will be forced to update to fix something that isn't an issue for them right now. My question is, will the time saved not troubleshooting old, unsupported versions outweigh the cost in usability?


title: How would you answer this job-interview question?

text: One of the five people who interviewed me asked a question that resulted in an hour-long discussion: **"Explain how you would develop a frequency-sorted list of the ten thousand most-used words in the English language."** My initial response was to assail the assumptions underlying the problem. Language is a fluid thing, I argued. It changes in real time. Vocabulary and usage patterns shift day-to-day. To develop a list of words and their frequencies means taking a snapshot of a moving target. Whatever snapshot you take today isn't going to look like the snapshot you take tomorrow or even five minutes from now. Thanking you advance for your answers and consideration.


title: How should I deal with external data sinks?

text: I recently took on a contract job that will largely involve generating data feeds from my client's data and sending it to external partners, via feeds and API invocations. I've always found this particular kind of coding to be frustrating, for a number of reasons:   * You have to rely on specs, which often diverge from the actual implementation or simply don't go into sufficient detail   * You have little to no ability to see into the external system, to ensure that your data has been accepted and interpreted properly   * If there's any kind of problem with data you've generated, it's not always straightforward to back out the changes and try again   * External testing and staging environments frequently diverge from production logic and the production database What are some best practices for doing this kind of work? Creating mocks and stubs won't necessarily resolve my problems, as my real concern is: do my feeds have the correct effect on another system, which is basically a black box? Mocks simply duplicate my assumptions.


title: Source/Version control for application used by multiple companies

text: Do you find it easier to keep a branch for each company that uses software you support/develop? Each company will want "customizations" and I am just trying to figure out the best way to handle those changes. A branch for each company makes sense in the short term but I could see how this could cause issues with upgrades when a new version is developed. Is better to have a branch for each company or to setup customizations so that they are always merged to a main branch to minimize issues with future releases?


title: Difficulty understanding difference between Project Manager (Business Analyst) and Software Architect and Scrum Master

text: From what I've gathered: **Project Manager (PM)(or Business Analyst (BA))** : Decides EVERYTHING. Capable of solving problems. This means he or she will have the skills necessary to look at data and other relevant information in order to determine where the losses are within a company. He or she must be skilled in negotiation, listening, motivational speaking and will also be a good team leader.   * Responsible writing the BRD, where contained are all the Business Requirements of the users/customers.   * BAs serve as a communication conduit between the stakeholders and the team **Software Architect** : The Architect is the interface between the dev team and the stakeholders. They need to be able to understand the business side and the technical details. Architects see what you need now, what you mean when you say what you need, and design a software strategy that will give you what you need today, and a home that you can grow into (and from) in the future. **Scrum Master** : Priority # 1 is to remove impediments as reported by team. He should also constantly look out for potential impediments.. and more importantly impediments that are there but not yet identified. Impediments are opportunities. So scrum-master should avail these opportunities all day long to bring his team(s) to hyper productivity. (avail = use or take advantage of) It appears several of these roles overlap one another. Please help clarify this issue. Some kind of story that strings together all these people would really help! Thanks much.


title: xaml schedule control how to cope with items of vastly differing durations

text: I have to create a schedule control using WPF XAML for displaying items with duration as little as 1 seconds and potentially as large as couple of hours. First thing which seems clear is that I will need some kind of zoom capability, for drilling into the items with very short durations and zooming out to view the items with very large durations. I have a UI style in mind where by when the control is zoomed to view the large items, any small duration items which generally occur between the large duration items are some how collected in to a 'bucket' which has a height >= a minimum display height. So that I can perhaps hover a mouse over this bucket and get a tool tip which renders the contained items into a time ordered list view. I am at a loss as to where to begin. I feel that I could perhaps achieve something in the Measure/Arrange overrides of a custom Panel. But I think this could adversely affect render performance. If I were to do it this way, I guess I would need to inject a 'bucket' view into the panels children collection, but that would break the use of ItemTemplate in my Custom Items Control? My second though is that I create a custom observable collection which has a bindable Scale property which then organises the collection into 'buckets' of a duration large enough to be displayable. Does anyone have any thoughts on how I should best approach this problem?


title: Should I really need to implement event sourcing is this case?

text: An example of use case when event sourcing is applicable here whose excerpt is: > Say, something went wrong in your app and as a result, a user gets blocked > for abuse but that user claims to not have done anything to break rules. Now > you can go back to your staging environment and play the events leading up > to the block in that system and see what happens first hand. > > What’s needed for this is a comprehensive log of events for basically any > interaction that happens around your app and a staging system to replay > events to. Based on the sensitivity of your data you may want to anonymize > some details before hand but that’s about it. IMO, event sourcing has a real benefit when we are asking for "why" was there this state rather than "what" was the state. My application is designed following CQRS principle, but I don't use Event Sourcing yet. If my application is really focus on the "what" rather than the "why" (since operations are really simple, meaning there are no different ways to end up the same result), is it similar to use the Temporal Pattern as introduced here (persisting object's versions/revisions in database) rather than implementing event sourcing? Especially for tracking user abuses (like posting some insults) that were temporary (so hidden), a simple query asking for the version where the abuse was commit could be enough and quickly made, rather than having a "script" in staging environment replaying the events to get the right snapshot showing the abuse.


title: Representing timezone list

text: I have a web application that allows the user to choose the timezone from the list. The list is very long (pretty much all CLDR-supported timezones). So the question is - how should I represent it? How should it be sorted - alphabetically or by timezone offset? What information should each item contain - offset, location, long name (like Europe/Zurich) or short name (like CET)? Should I display information about DST or only current offset? Let's say I can't right now do something like fancy maps OS configuration dialogs display, so the list is the only option. However I want to make the list look nice. Any best practices how it's done?


title: How to ramp up my data structures skills after a long hibernation

text: I was pretty good with algorithms and data structures once, a long long time ago. Since then, I programmed professionally, and then went to manage a small team, which totally shot my tech skills in this field back. I've decided I want to be a developer again, and work for Google. The thing is, I'm so out of practice, that if I were to be interviewed right now I would surely flunk out in 10 minutes. What training program would you recommend for me to get back into shape? I already started this weekend by going back to the absolute basics and implementing a few sort algorithms, linked list, and hash table. Next, I think I'll read through the entire course material on the other basic data structures and graph algorithms. I want to find a focused set of practical exercises I can do in a relatively short amount of time, to juggle the old brain cells. I know this stuff - I just need to remind myself that I know it.


title: Defensive Programming Techniques

text: I was attempting to identify an element of software engineering that I think is overlooked, not emphasized or not taught in typical undergraduate course work for CS or SE. What I came up is the concept of defensive programming. I would like to hear the community's options on defensive program and/or specific techniques that you use on a regular basis. Also, I would to know if there are any language specific techniques. Edit: Just to more clear. I am not looking for a lesson in defensive program. I understand what it is. I was hoping this would be more of discussion about different method members of the community employ or find valuable. Here are some techniques that I use. Keep in mind that I use C almost exclusively. Coding standard. You not might initially think that this has anything to do with defensive programming, but it does. To illustrate, suppose your coding standard requires you to prepend variable names with the type of variable it is such as IntValue or UIntValue. The convention allows you to easily spot potential promotion rule issues like (IntX = IntValue * UIntValue) Use preprocessor macros for constants. Personally, I think this also make your program more readable and maintainable, but it also provided a safety net. You can be sure that all areas of the code that use the macro will be updated when you change the value. Other uses of preprocessor macros can also provided defensive attributes in your code. Some technique are built right into the language such as static variables or function declarations or in c++ data encapsulation. Of course there are more obvious ones including validating all your input and output.


title: Lecture-like CS videos

text: I have no formal education in computer science (I am a mathematician), and I recently discovered that well-made videos make for decent substitutes of actual lectures. I'm looking for advice about some nice video lectures, but I have a more specific requirement than this question. Namely, many videos I found online do not make use of the blackboard and use a still camera. In these videos you just see the teacher talking and pointing at something that may be projected on the overhead, but you have no way to tell. Often there are slides to follow, but these are not a great help. Instead lectures like SICP or this course on Channel 9 make use of blackboards and have undergone a proper video editing, which ensures that you always see the relevant slides. This makes an enormous difference with respect to still camera lectures, which I find mostly unuseful. I can easily Google for lectures, but I need the help from people that actually followed them to find the relevant ones. I am mostly interested in the following topic, in descending order:   1. Compilers and interpreters   2. Operating systems   3. (Advanced) data structures and algorithms   4. Networks and protocols I don't really mind for the language used for the course, but in case I speak (at various levels) PHP, Javascript, Python, Scheme, C and Haskell. Even better if the courses proceed at a high pace. I generally learn rather quickly, but I do not have much spare time.


title: Best design pattern for library with data model

text: I am refactoring an old Codeigniter library to be php framework agnostic. There are these core parts:   * the connection object - this will come from the "user"; ie, the framework's connection, or their own connection library. My library will not want to "know about it" except that (at first) it will be a PDO conn object (but things should be written to handle a native driver type)   * the model object - runs the queries & returns results array (or error array) to the main lib. As it is now, it is very "thin" and only has transactions, query building & the actual db query   * the model interface - I'm a big fan of interfaces, and I see this model as being swappable for a NoSQL model, for example   * the main library - in my current CI library, this 1) receives the function request, 2) validates the params passed to it, 3) requests from the model, 4) creates a response array that includes the data & error codes and messages (multilingual configurable, but not really part of this question)  So, in summary, the way it works NOW is in your controller or calling page: 1) call main lib function 2) main lib calls model 3) model returns to main lib 4) main lib returns to controller * * * NOW starts my real design pattern question: I would like to pass my conn object via DI to my main library, but I'd also like to pass my model via DI to the main library to keep things flexible. The flexibility goal I'm after would be to allow people to create their own Native DB or NoSQL models & pass non-PDO conns into this, so keeping them decoupled seems optimal. BUT to do this, the only thing I can think of would end up as: (controller - where I might actually execute the query in the lib, not model)               $conn //from the user     $model = new MyModel();     $lib = new MyLib($conn, $model);      or               $conn //from the user     $model = new MyModel($conn);     $lib = new MyLib($model);      which feels more "natural" since the query & conn tend to work together Either case feels pretty clumsy for the user, and I can't help but wonder if I'm not either overdoing this whole DI thing or just have picked the wrong design pattern to go about this. Any guidance as to how to best set this up would be greatly appreciated - spent more time thinking about this than it will take me to refactor the actual code! TIA


title: Project organization with professionals and students

text: I am working as a PhD student developing scientific/engineering simulations and algorithms to be tested in these simulations. These days the first student started to work on my project (for his Bachelor thesis) and I am wondering: how should I organize the project now? I think I have some good C++ knowledge (although I still want to improve everyday!) and the code contains some design patterns, lots of templated classes etc. These techniques are new to the student and I wonder if it's a good idea to have him work directly in the trunk of the project. Do you have any experiences what happens if programming newbies and more experienced programmers are mixed? Does the code get messed up or do the newbies learn more by this? Is it wise to have a branch for the student to test his algorithms and maybe merge them into the trunk later? Should I first give him a book like The Pragmatic Programmer for reading (better suggestions?)? Thanks for every answer! PLEASE NOTE: I asked this question on Stackoverflow. The answer was about code reviews and I think this is a good way, but I was also advised that this site might be the more correct one, so I wanted to see if there are more things that might help or other opinions?