Qualifying 'happiness' in software development?

It occurred to me today that often the real goal of questions asked on sites such as this one (where the questions tend to be more open-ended than say, SO) is for the OP to become happier upon achieving the result. We often excuse this by saying our desire is to be more productive or release a better product, but if you continue to look down this path you can determine that the OP seeks greater productivity or product-quality because those are important to his/her 'happiness'. With that in-mind I ask **this** : Have their been efforts to study software development from this perspective? In other words, what practises increase happiness in those who develop software as a career, and who, if anyone, has researched this specifically? As I mentioned above, they may include strategies that increase productivity or improve product quality, but by no means should they be limited to just those.


Resources for learning common algorithms by Lisp

Many books about algorithms and data structures are coded by imperative languages. Is there any book that can show functional programming languages can do the same thing or do them better? In particular I am interested in sorting, searching, data structures and graph.


How do I authenticate users from facebook/twitter?

I need to build a site for a mobile app that allows users to sign in with facebook/twitter or sign up as a new user (traditional username/password). No matter which method the user chooses, they should remain login until they choose to logout. While signing up as a new user is straight forward, using username/password as authentication, I have no idea how I can authentication users who signs up with facebook/twitter. I think there's an access token returned when user gives access to our app, but is this token permanent? Can we reliably store it in our database for authentication? Any advice is appreciated.


Which paradigm to use for writing chess engine?

If you were going to write a chess game engine, what programming paradigm would you use (OOP, procedural, etc) and why whould you choose it ? By chess engine, I mean the portion of a program that evaluates the current board and decides the computer's next move. I'm asking because I thought it might be fun to write a chess engine. Then it occured to me that I could use it as a project for learning functional programming. Then it occured to me that some problems aren't well suited to the functional paradigm. Then it occured to me that this might be good discussion fodder.


best approach to learning for an undergrad operating systems course?

what is the best approach to learning for an undergrad operating systems course in order to understand the concepts and get a good grade in the exam? I know that some courses can be mastered through diligently reading the textbook or attending lectures while for others the concepts can only be understood by doing hands on projects. Is there a general studying approach that should be adopted for this type of a course? I know this may be subjective but I am looking for personal experiences/study methods by those who have taken similar courses to see if there is one particular method that worked well for the majority.


Which .NET technology would work as an improvement for this client/server application?

I am helping a friend with his rewrite of his .NET application, currently using WinForms + sockets, which is a client/server program that currently has on average ~120 concurrent users (sending messages, using the chat). The client will grow and eventually must be able to handle a several thousand concurrent users. A thread is created per user but this is not scalable due to hardware limitations (the server broke when stress-testing more users), not to mention the research I've done on the topic points to this being a bad practice. Speaking of research, I've gathered the following possibilities for this rewrite:   1. Using asynchronous threads with a thread pool of 8 or so threads (will this be able to handle 8,000 users?) or   2. Using WCF (this seems like the more .NET approach and more intuitive with its callbacks instead of using loops) I'm leaning more towards WCF right now. Before anyone asks, I have mentioned how this could be a web application instead, but he said no. Edit (answers to questions): The threads currently read from the socket (the packet) and parse it (simple string parsing) and depending on the type payload, executes another function. The functions executed are not very resource-intensive.


Git: rebasing and keeping current to a remote branch - accepted practices?

When developing on a long-running branch (here defined as living longer than one release), what's the most accepted practice(s) to keeping the branch current with its origin while keeping the history relatively clean prior to merging back? As an example, consider the origin branch (`m`) and a (topic) branch (`t`) with the following history graph:                A[1]--------F[2]--H[3]--J[4] (m)       \           \     \        B----C-D-E--G-----I-----K (t)          [1] - Release 1.0     [2] - Release 2.0     [3] - Hotfix 2.1     [4] - Hotfix 2.2      In branch `t` I've been merging from master (`m`) periodically to keep my topic branch up to date, but there are many small commits between `B` and `K` that I'd like to squash with a rebase. I'm concerned if I squash those commits that I will change the hash of the merged commits from master and create problems for others when I merge my branch back into master for Release 3.0. If I `rebase -i` the topic branch, I expect the graph would look like this:                A---------F---H---J (m)       \        B-----------------K (t)      where `K` contains all the squashed commits between `B` and `K` including the merged changes from master (`F` and `H`). If I then merge `t` back to master `m` I'm wondering if there likely be conflicts from `F` and `H`. The graph should look like this then:                A---------F---H---J---L (m)       \                   /        B-----------------K   (t)      `t` can now be deleted because it's no longer used. I'd like to keep the history of where `t` was branched from, so rebasing `B` onto `J` would lose that information and probably solve my problem but the graph would look like:                A---------F---H---J---K' (m)      Is this a valid concern? What is the commonly-accepted practice to keep one's feature branch current with its origin while keeping a relatively clean history? _Note: the example here is simplified, there are actually hundreds of commits from the branch point to HEAD on the topic branch - over 300 - many of which could be squashed out of existence_


Is try-finally expensive

In case of code where you have to do a resource cleanup before exiting a function, is there a major performance difference between these 2 ways of doing it.   1. Cleaning the resource before every return statement              void func()     {         login();              bool ret = dosomething();         if(ret == false)         {             logout();             return;         }              ret = dosomethingelse();         if(ret == false)         {             logout();             return;         }              dootherstuff();              logout();     }        2. Cleaning the resource in a finally block              void func()     {         login();              try         {             bool ret = dosomething();             if(ret == false)                 return;                  ret = dosomethingelse();             if(ret == false)                 return;                  dootherstuff();              }         finally         {             logout();         }     }      I did some basic tests in sample programs and there doesn't seem to be much of a difference. I so much prefer the `finally` way of doing this - but I was wondering if it will cause any performance hit in a big project.


Why is CATALINA_HOME named that way and other interesting program names

I work with open source software a lot and keep coming across weird and funny names for executables, variables, constants and etc. Currently I am wondering why CATALINA_HOME environment variable was named that way? I did a quick search on google with but nothing relative came up. My only guess is that it is named after the island of the shore of south California. On the related note, very often I find amusing and clever names used in open source programs. One of my favorites are **slapd** and **slurpd** executables of OpenLDAP suite. What are your favorite/noteworthy variable/executable names that you have seen in your programming career? Do you think it is OK to name your variables/executables this way, or would you rather see boring but clear names? PS. This is not really a programming question but I think it somewhat fits in here, according to faq.


General knowledge about building businesses applications for (small) businesses?

How can one a software developer learn about how to provide business solution? including but not limited to, implement business applications in decent software architectural style? CRM, ERP, MDM, SOA etc... are they really strictly reserved for _enterprise_? Where to learn about their...   * common features   * software / data architecture of such system in general   * complexity involved   * latest trend   * no silver bullets, then what are the options?   * popular open source projects that one can build on?   * commercial option if money is not an issue? I searched on Safari Books Online and most of the books are manual for how to customize Vendor X's CRM / ERP for your needs, or wordy and boring written for business students (not for software dev's) Any good resource to learn those listed above? Or is working at a software firm that writes that kind of software the only way to learn the in and out's of writing business application? **update:** bold assumption - large enterprises would go with a vendor like SAP without thinking of building one themselves. Thanks.


Microsoft Terminology: .NET C++ vs. traditional C++

I've recently been working with a team that's using both .NET C++ and pre-.NET C++. I fully understand the technical differences between the two technologies. However, I sometimes feel like I'm floundering when it comes to the terminology used to differentiate the two. Example: Say we have two projects:   **ProjectA** contains "C++" code that builds a .NET assembly DLL.   **ProjectB** contains Visual C++ code that builds a traditional native Windows DLL. What is the best way to succinctly and terminologically draw a distinction between the two projects? Again, I'm not asking for an in-depth technical description of the differences between the two technologies. I'm just looking for names and labels. This is how, today, I might try to make the distinction when talking to someone: _"ProjectA is a managed .NET C++ project"_   and   _"ProjectB is an unmanaged native C++ DLL project."_ However I am not at all certain that this terminology is ideal, or even correct. Please describe what you feel the ideal language to use in this situation (or similar situations) might be. Feel free to motivate your answer.


How useful are employment tests when interviewing candidates and predicting success?

When pre-screening candidates for a position prior to the first face-to-face interview, how useful are technical tests in filtering out poor candidates and possibly predicting their ability to succeed in the position? While some of the personality based ones might not say much, is there benefit to sending a technical test (e.g. on Java or C#) prior to a face-to-face interview or even a phone screen? Also, do these tests ever falsely identify a strong candidate as one that is likely a poor fit for the position?


What is the purpose of whitelisting in Phonegap? Is there a way around it?

I am using the new phonegap 1.5.0 (which is confusingly renamed cordova despite no mention of the rename on the phonegap site), and I'm finding that the white-listing feature on iOS is quite restrictive. I understand that having a whitelist is more secure in that it only allows trusted domains, but what if you want to load urls that have been loaded dynamically? You don't know exactly which domain will be loading, so you can't put it on the whitelist. An example use-case would be ad-serving and opening privacy policies. Why is the whitelist mandatory, and is there a way around it?


Database design and performance impact

I have a database design issue that I'm not quite sure how to approach, nor if the benefits out weigh the costs. I'm hoping some P.SE members can give some feedback on my suggested design, as well as any similar experiences they may have came across. As it goes, I am building an application that has large reporting demands. Speed is an important issue, as there will be peak usages throughout the year. This application/database has a multiple-level, many-to-many relationship. eg               object a     object b     object c     object d          object b has relationship to object a     object c has relationship to object b, a     object d has relationship to object c, b, a      Theoretically, this could go on for unlimited levels, though logic dictates it could only go so far. My idea here, to speed up reporting, would be to create a `syndicate` table that acts as a global many-to-many join table. In this table (with the given example), one might see:               +----------+-----------+---------+     | child_id | parent_id | type_id |     +----------+-----------+---------+     |    b     |     a     |    1    |     |    c     |     b     |    2    |     |    c     |     a     |    3    |     |    d     |     c     |    4    |     |    d     |     b     |    5    |     |    d     |     a     |    6    |     +----------+-----------+---------+      Where a, b, c and d would translate to their respective ID's in their respective tables. So, for ease of reporting all of a which exist on object d, one could query               SELECT * FROM `syndicates` ... JOINS TO child and parent tables ... WHERE parent_id=a and type_id=6;      rather than having a query with a join to each level up the chain. # The Problem This table grows exponentially, and in a given year, could easily grow past 20,000 records for one client. Given multiple clients over multiple years, this table will VERY quickly explode to millions of records and beyond. Now, the database will, in time, be partitioned across multiple servers, but I would like (as most would) to keep the number of servers as low as possible while still offering flexibility. Also writes and updates would be exponentially longer (though possibly not noticeable to the end user) as there would be multiple inserts/updates/scans on this table to keep it in sync. Am I going in the right direction here, or am I way off track. What would you do in a similar situation? This solution seems overly complex, but allows the greatest flexibility and fastest read-operations. _Sidenote 1_ \- This structure allows me to add new levels to the tree easily. _Sidenote 2_ \- The database querying for this database is done through an ORM framework.


Should we test the values of objects returned from the methods being unit tested?

Being new to unit testing I would like to know if I am supposed to test the values of objects returned from methods when doing unit testing. As an example, consider the following classes:               public class Person     {         public int Id { get; set }         public int Age { get; set; }         public string Name { get; set; }         public Pet Pet { get; set; }     }          public class Pet     {         public int Id { get; set; }         public int Age { get; set; }         public Breed Breed { get; set; }     }      And a method with the following declaration:               public Person GetPerson(int id) { ... }      I am now curious if I am supposed to create a test that checks to see if the various properties of the Person are correct (GetPerson_PersonFound_PersonHasCorrectName() and so on)? I suspect that I, under normal circumstances, should? All depends on the requirements? If those properties should be tested, am I then supposed to dig into Pet and check those properties as well? What about going even further, down into Breed? Can add up to quite a few tests quite quickly.


What to expect as a programmer in a bank?

After three phone interviews, I got this offer in a large bank as a Java programmer. I have no prior experience in financial institutions (only two years as a regular Java dev), so I'm a little bit scared and concerned about whether my skills are right for this role. The main thing that bothers me is math. During all of those interviews we never touched the topic of mathematics, but I know that this position is related to financial instruments like derivatives. How much math should I expect on the assumption that no trading is involved, but rather, accounting? How can I prepare better for this job? I was searching Google for some Java financial programming tutorials/books but no luck here - maybe you can recommend something? I'm really interested in the stock market but never tried this theoretical approach. Thanks!


Making sure users have a modern web browser

We have several users running on old hardware and old browsers. What would be the best way to get them to upgrade to a newer web browser, without nagging users with a newer web browser.


Can we say that Java or C# have unified inheritance trees?

Can we say that Java or C# are OO languages with a unified inheritance tree/unified type system? By unified inheritance tree/unified type system I mean that every class derives implicitly or explicitly from one single type? Are there any object oriented language that do not follow that concept?


Creating a online database creator

I've been thinking of creating an online database creator (think DabbleDB, Zoho Creator, Intuit Quickbase, etc.). I've been thinking of a couple solutions:   1. Have 4 database tables: **Tables** , **Rows** , **Columns** , **Items**. To create a database as a user, you'd go to the "Add New Table" page, give a name and type to as many columns as you want, then save. Then you'd be taken to a page which displayed a list of rows that had items inside that corresponded with the columns. The problem with this approach is I can't figure out how to link the item with both the row and the column.   2. Create an actual database table for each user, and when they insert a new column ( or field), it would just a database INSERT. Cons: I think this would be slow and expensive (correct?), not to mention would make a feature like how DabbleDB did relationships between tables very hard to implement. So what is the best way to build this? Or is there a better way than even the two I've mentioned.


What electronic user-story-mapping tools can you recommend?

Agile software development relies heavily on a work item type called **user stories**. For example, you have a backlog full of user stories and you can select a few of them to work on during the next sprint. But where and how do you find user stories to put into the backlog? There is a popular technique for doing that called **story mapping**. Jeff Patton invented it and here is the definitive guide on how to do it. The question is, what electronic tools are out there that support Patton's story-mapping technique? I've done a bit of research, found Pivotal and Rally plug-ins (but I'm not a customer of either) and I'm currently experimenting with SilverStories. What other tools are out there? What have you used? What do you (not) recommend? Why? **UPDATE:** Some people who wrote comments seem to lean towards an answer that applying this technique is simply impossible with an electronic tool and we should just accept that. Can't someone write it up as an answer? **UPDATE** (to clarify the question in light of Alex Feinman's comment): the question is about identifying options for story-mapping. Since Jeff Patton's technique can obviously be done on a white-board with stickies, the question focuses on additional options that might be provided with electronic tools. (Premature) commitment to any particular tool or class of tools is not the point of this question.


What are the typical naming conventions for OO C public and private functions?

**Short Question**   Is there a typical way to name 'public' and 'private' members of an OO C project? **Background**   I fully understand that public and private members do not _really_ exist in the C language. However, like most C programmers, I still treat members as public or private to maintain the OO design. In addition to the typical OO methods I have found my self following a pattern (see example below) that makes it easier for me to distinguish which methods are _meant_ for the outside world vs the private members that may have fewer checks / are more efficient etc... Does a standard or best practice exist for such a thing or is my example below a good way to approach this? **Example Header**               #ifndef _MODULE_X_H_     #define _MODULE_X_H_          bool MOD_X_get_variable_x(void);     void MOD_X_set_variable_x(bool);          #endif /* _MODULE_X_H_ */      **Example Source**               // Module Identifier: MOD_X      #include "module_x.h"          // Private prototypes     static void mod_x_do_something_cool(void);     static void mod_x_do_something_else_cool(void);          // Private Variables     static bool var_x;          // Public Functions - Note the upper case module identifier     bool MOD_X_get_variable_x(void)      {return var_x;}     void MOD_X_set_variable_x(bool input){var_x = input;}          // Private Functions  - Note the lower case module identifier     void mod_x_do_something_cool(void){          // Some incredibly cool sub routine      }          void mod_x_do_something_else_cool(void){          // Another incredibly cool sub routine      }


If a language changes quickly, is this considered a good thing?

I have seen some languages that change quickly (I mean they are improved every year for example) and some others that are improved slowly. My question, if a language changes quickly is this a good thing or a bad thing for the programmer? Do programmers like to learn new thing in the language or do they prefer to stick with what they already know?


HTTP API that wraps any Python-Scrapy spider

I have to write an HTTP API that wraps any Scrapy spider, it should accept Requests, execute them in Scrapy, and return data extracted by the spider and lets the user reuse the same code to extract interactively. Scrapy supports crawling in batch mode very well, i.e. a long running process starting from seed requests, extracting and following links and exporting data. How should I go about doing this ? What are the technologies involved ? Where can I learn those ? Any help would be greatly appreciated.


How to manage focus for a small set of simple widgets

I'm developing a set of simple widgets for a small (128x128) display. For example I'd like to have a main screen with an overlay menu which I can use to toggle visibilty of main screen elements. Each option would be an icon with a box around it while it is selected. Button (left, up, right, down, enter) events should be given to the widget that has "focus". Focus is a simple thing to understand when _using_ a GUI, but I'm having trouble implementing this. Can you suggest a simple concept for managing focus and input events? I have these simple ideas:   * Only one widget can have focus, so I need a single pointer to that widget.   * When this widget gets some kind of "cycle" input (as in "highlight the next item in this list"), the focus is given to a different widget.   * a widget must have a way of telling the application which widget the focus is given to next.   * if a widget cannot give a "next focus" hint, the application must be able to figure out where the focus should go. Widgets are currently structured like this:   * A widget can have a parent, which is passed to the constructor. Widgets are created statically, as I want to avoid dynamic memory allocation (I only have 16kB of RAM and I'd like to have control over that).   * widgets have siblings, implemented as an intrusive linked list (they have a `next` member). A parent has a pointer to the head of its list of children. Input events are arguments to the widgets `buttonEvent` methods which can accept or ignore that event. If it ignores the event, it can pass the event to its parent. **My Questions:**   1. How can I manage focus for these widgets?    2. Am I making this too complicated?


How to get around the Circular Reference issue with JSON and Entity

I have been experimenting with creating a website that leverages MVC with JSON for my presentation layer and Entity framework for data model/database. My Issue comes into play with serializing my Model objects into JSON. I am using the code first method to create my database. When doing the code first method a one to many relationship (parent/child) requires the child to have a reference back to the parent. (Example code my be a typo but you get the picture)               class parent     {        public List<child> Children{get;set;}        public int Id{get;set;}          }     class child     {         public int ParentId{get;set;}         [ForeignKey("ParentId")]         public parent MyParent{get;set;}         public string name{get;set;}      }      When returning a "parent" object via a JsonResult a circular reference error is thrown because "child" has a property of class parent. I have tried the ScriptIgnore attribute but I lose the ability to look at the child objects. I will need to display information in a parent child view at some point. I have tried to make base classes for both parent and child that do not have a circular reference. Unfortunately when I attempt to send the baseParent and baseChild these are read by the JSON Parser as their derived classes (I am pretty sure this concept is escaping me).               Base.baseParent basep = (Base.baseParent)parent;     return Json(basep, JsonRequestBehavior.AllowGet);      The one solution I have come up with is to create "View" Models. I create simple versions of the database models that do not include the reference to the parent class. These view models each have method to return the Database Version and a constructor that takes the database model as a parameter (viewmodel.name = databasemodel.name). This method seems forced although it works. NOTE:I am posting here because I think this is more discussion worthy. I could leverage a different design pattern to over come this issue or it could be as simple as using a different attribute on my model. In my searching I have not seen a good method to overcome this problem. My end goal would be to have a nice MVC application that heavily leverages JSON for communicating with the server and displaying data. While maintaining a consistant model across layers (or as best as I can come up with).


Sorting lists (global vs local)

In my application users have lists. They can either add a new item to their list or add an item from a previous list. The set of all items I'll call G (global) (each user's global list is their own). G = { a1, a2, a3,...,an} After (or during) a user has created a list they can sort it. This has been no problem. The problem happens when try to apply an items order globally. For example, if list one has m items: L1 = {b1, b2, b3,...,bm} And the user changes the order of b1 from 1 to 9 in L1. Then when the user saves the list I'd like its global order to change as well. But I'm not sure what to change it to. Here's how I'm doing this now. Take our list L1: L1 = { **b 1**, b2, b3,...,bm} Move b1: L1 = {b2, b3, **b 1**,...,bm} Find out the global index of b3 (say 41), add one (42) and that's b1's index. Then find all other items that have a global index greater than or equal to 42 and add one. What's the best (or at least better) way to do this?


Coming up with a valid ranking algorithm for articles

I'm creating a website which will publish one or more articles a week. I'd like to be able to rank the articles based on popularity. In order to do this, I need a formula to calculate a score for each article. This formula should reward popular articles (those that receive many views), while also bringing new articles closer to the top in order to keep the content fresh and interesting. The website doesn't support voting on the articles. The readers will be able to comment and I can have the site track the amount of unique views the article gets. * * * # My attempt I have come up with a way to calculate a score for each article but I'm not sure if it's the right way to do it, or if it will work at all. This formula calculates the score:               score = unique_views / ( hours_since_release * 4 )      The formula keeps articles with many views afloat, while also making sure that they'll eventually subside to leave space for new articles. I wrote a small program to test this formula. **Here is the output of one run.** This script generates between 0 and 2 articles every day, and simulates their score as time progresses. When an article is created, it chooses a random number (`M`) between 100 and 1000, representing its popularity. Every "day", the script adds a random number of views between 0 and `M` to each article. The actual views shown in the output (`V`) are the result of this formula:               view_count = ( 10 * log10( view_count ) ) ^ 2      I used this to make sure the view count doesn't keep growing forever. Instead, its growth will slow down as time goes, as it might in real life. The values `A` and `S` in the output represent respectively the age in days of the article and its score, based on the formula shown above. This formula causes some interesting behavior: if you look at the game **Tomb Raider: Anniversary** , it spawns with a big `M`number, which means it's going to be very popular. It gets to the top on the first day, goes down in the next 2 days and then comes back to the top for 3 days in a row due to the amount of views it gets. This seems to be the behavior I'm looking for, but I'm not sure if it will work in practice, or even if this is the right approach at all. You can find the source of my rough prototype here if you'd like to run it yourself. * * * Here comes the question: **How can you come up with and test ranking algorithms so that they satisfy the conditions of the problem, using the available variables?** Secondary question: _Is my ranking algorithm appropriate, and would it work in the situation I described?_ * * * EDIT: From the links in _maythesource.com_ 's answer, I just realized there's also the issue of score gaming. Would only considering _unique_ visits somehow prevent gaming, or is it a weak countermeasure?


Should you use PHP to render the html page or use javascript frameworks? Server-side page rendering or client-side page rendering?

This may be a inappropriate question, but I'm really need help demystifying this. Suppose we want to create web application like reddit or Gmail. The way I understood it from my research is that there are two ways to approach this problem. 1) Web application like reddit can be created using PHP only. HTML for the front-end will be rendered by PHP on the server and application logic will also be written in PHP on the back-end side. With this method, web application would not feel "real-time" since for any changes you would need to refresh the page. 2) Create RESTful backend in PHP and use JavaScript frameworks like backbone.js to create single page web application and manipulate the HTML on the front-end. Front-end written in javascript would send requests to back-end which would only return JSON packages (no HTML). On the front-end, Javascript should decide how to manipulate the front-end based on the JSON packages returned from the back-end. With this method, web applications would be real- time. What is the advantage of using method 2 over method 1? I read that Gmail is implemented using method 2. Why did they use javascript frameworks to create the front-end, if they could send HTML rendered on the back-end side and make AJAX calls to check for notifications? Is it generally better to use method 2 over method 1? Server-side page rendering or client-side page rendering? Thanks in advance!


Why is subclassing too much bad (and hence why should we use prototypes to do away with it)?

I was reading up on design patterns, and I read that the prototype design pattern does away with excessive subclassing. Why is subclassing bad? What advantage would using a prototype bring about over subclassing?


How useful is a project log or diary?

I want to know how difficult/useful it is to keep a project log or diary. I'm worried that keeping track of what I did will eat up too much time...


Class fields/variables. Keep single reference point at class level or pass to individual methods?

Often I see a class where a value is injected into a method or even a constructor. That value is then used by several methods within that class and a reference is simply passed through to each method that requires it. To me this seems like a code smell, although I could very well just be a pedant. Unless a variable is only required once within the scope of a single method, I would usually have a class level field that is initialised by the method that receives the value. Any other methods would then reference this field if needed. This seems to be a lot cleaner to me. Thoughts?


Shorter release cycle with DVCS

Does the choice of using a DVCS over a CVCS actually make for shorter release cycles? If so, what makes software release cycles shorter and what are the arguments for this?   1. Related to pull request? Does easier submission of patches play a role here?   2. Related to people factor? Are project teams that use CVCS act more conservative with release schedules?   3. Any other factors?


Class Design -- Multiple Calls from One Method or One Call from Multiple Methods?

I've been working on some code recently that interfaces with a CMS we use and it's presented me with a question on class design that I think is applicable in a number of situations. Essentially, what I am doing is extracting information from the CMS and transforming this information into objects that I can use programatically for other purposes. This consists of two steps:   1. Retrieve the data from the CMS (we have a DAL that I use, so this is essentially just specifying what data from the CMS I want--no connection logic or anything like that)   2. Map the parsed data to my own [C#] objects There are basically two ways I can approach this: **One call from multiple methods**               public void MainMethodWhereIDoStuff()     {         IEnumerable<MyObject> myObjects = GetMyObjects();         // Do other stuff with myObjects     }          private static IEnumerable<MyObject> GetMyObjects()     {         IEnumerable<CmsDataItem> cmsDataItems = GetCmsDataItems();         List<MyObject> mappedObjects = new List<MyObject>();         // do stuff to map the CmsDataItems to MyObjects         return mappedObjects;     }          private static IEnumerable<CmsDataItem> GetCmsDataItems()     {         List<CmsDataItem> cmsDataItems = new List<CmsDataItem>();         // do stuff to get the CmsDataItems I want         return cmsDataItems;     }      **Multiple calls from one method**               public void MainMethodWhereIDoStuff()     {         IEnumerable<CmsDataItem> cmsDataItems = GetCmsDataItems();         IEnumerable<MyObject> myObjects = GetMyObjects(cmsDataItems);         // do stuff with myObjects     }          private static IEnumerable<MyObject> GetMyObjects(IEnumerable<CmsDataItem> itemsToMap)     {         // ...     }          private static IEnumerable<CmsDataItem> GetCmsDataItems()     {         // ...     }      I am tempted to say that the latter is better than the former, as GetMyObjects does not depend on GetCmsDataItems, and it is explicit in the calling method the steps that are executed to retrieve the objects (I'm concerned that the first approach is kind of an object-oriented version of spaghetti code). On the other hand, the two helper methods are never going to be used outside of the class, so I'm not sure if it really matters whether one depends on the other. Furthermore, I like the fact that in the first approach the objects can be retrieved from one line-- most likely anyone working with the main method doesn't care how the objects are retrieved, they just need to retrieve the objects, and the "daisy chained" helper methods hide the exact steps needed to retrieve them (in practice, I actually have a few more methods but am still able to retrieve the object collection I want in one line). Is one of these methods right and the other wrong? Or is it simply a matter of preference or context dependent?


Generate analog signal from Windows 7

I want to output an analog signal from my Windows 7 computer. The wave will be a combination of about 5 frequencies, with a maximum of 28 MHz. It won't be a problem to generate the wave data with C++, but I am not sure how to output the wave dynamically (as it is being generated). I am sure an audio port is not set up to output 28 MHz, but is there some way to bypass the sound card and interface directly with the port? If not, what would be the easiest way to output a high frequency analog signal with C++?


How do you handle multiple users editing the same piece of data in a webapp?

There's a project I'm working on that is looking to produce a web application that will manage a task list between multiple users. This is a master task list whose task items get distributed by an authorized user. Each user has his/her own account to login and view the tasks they are assigned; it is possible for multiple users to have a single task in-common. I am trying to leave details of the project out of this as I'm grappling more with the overall concept of how to handle the following situations, but if it helps, I'm using Java, EclipseLink, and GWT with RequestFactory implemented. The database is PostgreSQL. So the conceptual problems I am attempting to reconcile are the following:   1. If a single task that is common to multiple users changes in any way e.g. task completed, deleted, etc., the task list of all the users who have this task will be updated. What design patterns are there that assist in implementing this function?      * Some patterns I have looked at are Observer and Mediator - are there others that should be considered over these?   2. Say there are two users changing the same task at the same time.      * First, should I allow that situation to happen or should I put a lock on it until one or the other person is done making changes?      * Second, if I don't put a lock on it, how do I reconcile whose changes to accept? This involves the situation in 1 because user 1 could submit the data and before user 2 receives the updated data, he/she may have gone ahead and submitted his/her's changes. I am really looking for any guiding points, advice, or tips you can provide on how to properly sync data between multiple instances of this web app. I would very much appreciate it!


how to improve design ability

I recently went on a couple of interviews and all of them asked a one or two design questions, like how you would design a chess, monopoly, and so on. I didn't do good on those since I am a college student and lack of the experience of implementing big and complex systems. I figure the only way to improve my design capability is to read lots of others' code and try to implement myself. Therefore, for those companies that ask these questions, what are their real goals in this? I figure most of college grads start off working in a team guided by a senior leader in their first jobs. They might not have lots of design experience fresh out of colleges. Anyone could give pointers about how to practice those skills? Thank you very much


Documentation Generation - FiM++

_This is a question I originally asked on Stack Overflow, but as a conceptual design question as opposed to a technical issue, I believe it may be more appropriate, or possibly have alternate parallel value, on this board._ The structure of a FiM++ program requires that it end with the closing of a letter and the code author's name in a specific manner.               Dear Princess Celestia and Stack Exchange and String: A Sample:         ...     Your faithful student, Southpaw Hare!      According to the language specification, the keyword "Your faithful student," (including the comma but not the following space) is used as an end tag for class definitions, and the following name is a comment with no syntactical effect. The fact that the author is automatically included (if not strictly required) in every file makes me wonder if it can be used as a form of interpretable documentation akin to Java Docs. In other words, that other programs or editors would be able to parse out this name and use it in some manner.   1. What is the requirement of such internal comment-based documentation? Is there anything in this particular type of syntax that would cause problems?   2. Is the keyword sufficient to fit with the theme? It occurs to me that the lack of ability to use "Your faithful students," for a plural form (or possibly "Yours faithful," or "Yours truly," for an ambiguous version) would make listing multiple authors look awkward and unnatural (and looking like a natural human-written letter is one of the core design paradigms).   3. If creating a Java Docs methodology was considered, then what other features should be included? For one, a date seems common. Including some form of date comment at the top of the letter would probably look natural and not defy the design paradigm. Since the language is new, unfamiliar to most, and honestly quite silly, here are a few resources to consider: Original Release Announcement October Followup


TDD and test automation in applications heavily dependent on databases and user input

Recently I have been reading online about eXtreme programming and agile practices. I wish to adapt them. However most of my code is all in PHP which is the normal CRUD type web applications. Moreover I user web framework like CodeIgniter, which also abstracts a lot of the core features. To sum up, how can I implement the test driven development into applications which are heavily dependent on databases and user input, particularly in the test automation part? ### I would now ask this question targeting my current project I am working on an college forum web application. It has the basic social network features and also includes XMPP server on its stack. The following components constitute my application stack:   1. Apache web server with mod_php enabled.   2. PHP as a back-end language.(CodeIgniter framework)    3. MySql database.   4. Openfire server for XMPP.   5. HTML, CSS, jQuery and Strophe(for XMPP) on front end, and   6. A Python middleware for XMPP. Currently I am working without any testing or build cycle. I use SVN as the version control system. And I wish to include TDD and CI into the development process. I already have some code in the project. What strategies and best practices should I adopt for implementing TDD and CI in this kind of project? PS: We are a team of three people working on a self project as such we dont have any other person who influences the design(apart from the end users). ### This is what I did to start implementing I refactored the login function which was taking the username and password passed from the front end and then applies sanity checks, checks for valid username, then for valid password, If yes it sets the session cookie and redirects the user to a page based on his role. I broke the above function into three one to take username and password and check if they are correct, another to set the cookies and the last one that takes the values from front end and applies sanity checks, calls the other two functions and then redirects. I could write test for only the first function. Is that enough?


Kanban: How to choose work item size

Starting with Kanban, I'm not sure about how granular my work items should be. While you find lots of concrete recommendations about how to choose the WIP, most of the Kanban tutorials I've read stay quite vague about the size of a work item (= a card on the board). For planning and estimation, people often recommend to keep the size of an item small, say 2-16 hours. Does the same apply for Kanban? Is there always a 1:1 mapping from my plan to the board? If there's no best practice or general recommendation, which factors would influence my choice of work item granularity?


What demands should be placed on source repository / versioning tools?

And do you know a tool which meets those demands?


Designing entities to be self-manageable

Although this is a gamedev project, the question is about general OOP practices, so I believe it goes here. Here's the problem: (note: I will call any equivalent of real-world physical objects "entities" from now on; e.g. a rock in the game is an entity) A specific class:               class Character     {     public/private CharacterInventory Inventory;     public/private CharacterStats Stats;     public/private CharacterEquipment Equipment;     }      Inventory functionality is self-contained in the CharacterInventory class. Same goes for stats. My aim is to make each character in my game a self- manageable entity. What do I mean by this? To put it plainly, I want to design the base Character class so that in the end I get an object that reacts in its entirety even when the smallest change occurs, in any of its components. To make things clearer, here's an example: when an item that changes the strength of the character gets equipped, the CharacterEquipment component of Character gets updated. At the same time, the Character will call the Stats object to change the strength attribute. I've thought about doing this using events. Character subscribes to Equipment's OnEquip event, and in its handler, tells the Stats component do do its job. I believe this is an elegant enough solution; my issue however lies somewhere else. I've got two ways in which I can update the character's inventory. First, by making the inventory (and any other component) private and providing a public method inside of Character, that does the work of calling the appropriate update method in the inventory. Like so:               Character chara = new Character();     chara.AddItemToInventory(SomeItem);      The 2nd way is by making the components public and accessing them like:               Character chara = new Character();     chara.Inventory.AddItem(SomeItem);      To me, both ways seem roughly equivalent in terms of readability. But the 2nd way seems like it's breaking the whole "self-manageable" idea. Basically, I'm invading the "private" space of the character. By going with the 2nd way, I can hook to the inventory events from some other place, but then again, this breaks the main idea even further. However, going the 1st way, I get the impression of writing duplicated code; even though it's not! I think the impression is given to me by the fact that Character.AddItemToInventory(...) and CharacterInventory.AddItem(...) share enough naming similarities to suggest duplicated code. To be sincere, I'd go the first way, even though it seems to me like an extra layer of code. Then again, to make the character a self-manageable object, an extra layer of _security_ is essential. But I'd like to hear from people more experienced than me. Are there any advantages to the 2nd way? Any severe disadvantages? I just can't get over the impression that I'm writing extra, unnecessary code.


Why are the arguments for substring functions mismatched?

In many languages, the substring function works like this: substring(startIndex, endIndex) returns the substring from startIndex until endIndex-1 (if you view startIndex and endIndex as 0-based) / from startIndex+1 to endIndex (1-based) This is confusing. I understand that the two parameters can be interpreted as "startIndex" and "length of the substring", but in my opinion that is still confusing and even in this case, startIndex is 0-based while length is 1-based. Why not stick to one convention for both the function arguments? and why do newer languages like ruby and python continue to stick to this standard?


How to determine whether Design Pattern is implemented correctly?

I am successfully able to scale all my old applications which were not using documented Design Patterns. Whatever pattern it is I don't know. To a large extent, I only felt a need to use simple OOP concepts. The Design Patterns concept is complex and hard to understand. When implemented, how to determine whether the implementation is correct and the application possess real loose coupling?


What do update versions really mean?

A lot of software updates follow the scheme of v0.1 to v0.2 to v2.6.5.6. What do these "updates" to software really mean? Is there an industry standard always followed or do programmers pretty much keep raising the update # or adding more decimals?


What is the pronunciation of $ / $. in jquery

When you are reading jQuery code aloud and you get to anything that uses `$`, do you pronounce that as "dollar sign", "jQuery", "jQuery selector". Is there some other pronunciational shorthand for the `$.` syntax (as in `$.each`)? Or is it just as simple as saying "dollar sign dot ... "?. I ask because since `$` is an alias of `jQuery`, I wonder if its pronunciation carries over.


System evolution approach: gradual or cataclysmic?

When working on established systems, I've often found ways to improve a user interface to maximize user efficiency (example: legacy app maintenance screen doesn't allow multi-line operations where doing so could save the user hours per week over the "edit one line at a time" existing method). The challenge I encounter is that a GUI improvement is something that I can't apply universally to a system without a more sizable programming effort (an effort that management is unlikely to approve). I then struggle with the decision to either try and add the improvement in one screen, or give up on it until the mythical project is someday approved. Not doing it means the system is not enabling users to be most efficient, and this bothers me, as if I have purposely allowed a speed throttle on them that they don't deserve. But doing it means that now there is some inconsistency in the system GUI. Not all the screens will work the same way, which can create potential confusion. Given your knowledge and experience, what is the best practice here? Consistency or efficiency? **Update** Thank you everyone for your answers. I have upvoted all your thoughtful responses. I am familiar with the Spolsky article Robert Harvey links to. The change I refer to is less risky than the whole rewrite of the Netscape example it refers to, but the article is pertinent and always a good read. This question was spurred by a time when I found a way to make it possible for users to process items for invoicing faster, so it could be argued that it improved revenue efficiency, however, as many of you ascertained, it was not critical. The stakeholders succumbed to the decision-consequence gap, and as they were not the ones having to do the data entry were more than happy to let the users languish with the inefficient GUI. However, the craftsman in me wants continuous improvement, and as Justin Cave says, if you do nothing, your system is not evolving, it is stagnating. In some other cases I've done what is suggested in the responses and tried a grassroots approach, having users push for change through their stakeholder representatives. I found that approval for incremental changes that broke consistency have depended on accessibility to end-users, a willing stakeholder in the change request meetings and strangely enough, IT leaders that either cared very much or not at all about the application in question. Those that cared empathized with the end-user's pain and those that didn't were comfortable leaving the decision to subordinates that did. The moderately concerned would glom onto the consistency principle which is arguably laudable but to which rigid adherence without a plan for change means stagnation.


Do I need to upgrade log4j to slf4j

We are reviewing our JEE web application for some planned refactoring and one of the suggestions is to replace `log4j` with `logback` or `slf4j` The team is not clear on whether we should do this - because currently we want to follow _if it ain't broke, don't fix_ in this area. **Edit:** I'm not asking for a comparison of the logging frameworks, but whether it is a valuable _refactoring_ element to change the framework when we're quite happy with log4j


force recompilation of war file including its Jar dependencies

I have a project A (a webapp), depending on project B (B.jar) and this one depending on project C (C.jar). I would like to create a maven goal named "Rebuild War", that clean all compiled code for these 3 projects and rebuild the whole in order to obtain a fresh War file. I tried mvn clean package on project A, but I noticed that B and C are not recompiled. Indeed, B.jar and C.jar that are contained in local repository don't have a changing creation date. Is there an adapted maven command for this requirement ?


What does this mean: Expression<Func<TModel, TValue>>

In ASP.Net MVC, in the razor view, you can type this kind of code:               @Html.EditorFor(model => model.Name)      (in this case, it creates a textbox for the field Name of the object which is defined as the type of the model) Now when i see the definition of the EditorFor method, it is this:               EditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression);      So i tried implementing that kind of method myself, but i realy don't see what this means **`Expression<Func<TModel, TValue>>`** Who can explain to me what an expression is, and the Func, and the Expression of type Func? The explanations i found where all so abstract it didn't give me a clue....


I'm at a crossroads with programming and theory

I bought "Beginning C++ Through Game Programming" yesterday to start learning about C++ and programming. I'm going on hour 33, and I can't seem to put this book down. I was talking to a friend who's more experienced, and he suggested that I should now spend my time learning about algorithm design and data structures because languages come and go but in depth knowledge of theory (as in not just knowing about all the different types of algorithms, but being able to create my own) will be everlasting and more beneficial. I guess what I'm asking is this: Should I focus more on learning more C++ and buying more books or should I instead buy a book on algorithms and focus more on that? (Yes, I know I can do both and I plan to, but I'm asking which should receive more attention) P.S. - I've been looking into Financial Engineering for college and apparently C++ is the dominant language, but as my friend said, "languages come and go" so would I be wasting my time by trying to master C++?


Will this referral code scheme work?

I'm thinking of implementing the following referral code scheme to sell my software:   * Anybody can obtain a referral code. They just provide an email and I send them the code.   * With that they can recommend the software to their friend, etc.   * Each time someone buy a license using a referral code, I give 10% of this license to the referrer   * They can do that as many times as they want What do you think? Can you see any potential problem with this scheme? Do you think it will work?


Type mocking frameworks does not change coding practices from testability point?

Many people recommend that we should code against interfaces and avoid statics for testability. Interfaces are not just for testability, they are sometimes a requirement. But sometimes we introduce new interfaces in application only for testability. If type mocking frameworks help us to isolate dependent types, then why should we use interfaces just for the sake of testability? Also, why should we avoid static members?


Create code editor auto-suggest (like IntelliSense)

If one would to write auto-suggest for an IDE/code editor (like IntelliSense), does one generally need to write a parser for any language that should be supported, or do compilers/runtimes provide these things? Neither the PHP or Python binaries seem to support just parsing files and generating some kind of raw output. Eclipse seems to roll their own parser, but is this the only way to do it? Using the "native" parser would be awesome on so many levels :)


With entity framework - who needs a DAL

On EF4 actions on entities are actually done via the Business Element layer (BE). Why do I need the Data Access (DAL) on another layer?


The business and architecture challenge behind creating effective user stories

A friend of mine in another department had a problem and came to me with a question that I wasn't sure how to help him with. He recently became promoted to architect and he was put in charge of design and leading a team of developers that are of questionable quality and little to no experience with following a project plan. This team got in the habit of starting development as soon as possible before business needs were even evaluated, and then hacking the software to pieces when requirements finally became clear near the end of the deadline. Because of this they have tried formulating design standards in the past but never bothered following them later in the project when the heat was turned up. He aims to change this and asked me about the best way to handle these challenges. My perspective is that the project is doomed before they start because management sets a tight deadline before the requirements are clearly known or understood. Dithering from the client exacerbates the problem further. I told him that Agile was MADE for these kinds of problems, formulate user stories based on the customer requirements as you are aware of them now, and then as more user stories or as they change just add to the backlog and readjust your sprint plan accordingly. But then I got thinking about what really is the best way to handle this? The client has no way of knowing exactly what they want from the software now, but they know they want it and are willing to pay for it and they want at least some kind of working release by a specific date. They are given a quote with a breakdown of what will be delivered (it is a guess for both vendor and client), price is agreed upon. When formulating the quote a deadline of some kind must exist even though it is soft at this point. User stories aren't even known and certainly not tasks and the ability to provide a reasonable estimation either. How do you approach this challenge? When this quote is taken and agreed upon is it normal to use the rough deliverables as outlined in the quote as a basis for formulating your user stories? Further do you have any advice on how to "keep the design patterns and documents alive" throughout the project as requirements change drastically? **EDIT:** It seems many people assume that the client involved should be the one to provide the user stories as if it were a given. I don't have any personal experience with a client willing to put this kind of effort into being involved with the development process. Due to this, it seems to make sense that because of their lack of input into the development process, they are not a very good stakeholder for the project itself. The stakeholders at this point become the business analysts and application managers who are supposed to squeeze whatever trickle of information they can get from the client and turn it into usable information for the developers. This is clearly not working though so perhaps the ONLY way that Agile or Kanban can work is to have direct client involvement in user stories or else the project is doomed to failure?


good literature for teaching object oriented thinking in C

Quite often C is the primary platform for the development. And when things are large scale, I have seen partitioning of the system as different _objects_ is quite a natural thing. Some or many of the object orientated analysis and design principles are used here very well. This is not a debate question about whether or not C is a good candidate for object oriented programming or not. This is also NOT a question how to do OO in C. You can refer to this question and there are probably many such citations. As far as I am concerned, I have learned some of this things while working with many open source and commercial projects. (libjpeg, ffmpeg, Gstreamer which is based on GObject). I can probably extend a few references that explains some of these concepts such as   1. Event Helix article   2. Linux Mag article   3. one of my answers which links Schreiner's reference   Schreiner is definitely one of the only reference I know. However, there are few things/ approaches that I don't quite like about it. At times, this books gears more towards theoretically being closure to OO_ness_ rather than being useful. But, definitely, this is perhaps the most giant leap of all reference I have found. Unfortunately, when we induct younger folks, it seems too hard to make them learn all of it the hard way. Usually, when we say it's C, a general reaction is to throw away all of the "Object thinking". Looking for help extending above references from those who have been in the similar areas of work. > **Are there any good formal literature that explains how Object thinking can > be made to use while you are working in C?** I have seen tons of book on general "object oriented paradigms" but they all focus on advanced languages mostly not in C. You see most C books - but most focus only on the syntax and the obfuscated corners of C and that's it. There are hardly ANY good reference, specially books or any systematic (I mean formal) literature on how to apply OO in C. This is very surprising given that so many large scale open source projects use C which are truly using this very well; but we hardly see any good formal literature on this subject.


Best Creational Pattern for loggers in a multi-threaded system?

This is a follow up question on my past questions : Concurrency pattern of logger in multithreaded application As suggested by others, I am putting this question separately. As the learning from the last question. In a multi-threaded environment, the logger should be made thread safe and probably asynchronous (where in messages are queued while a background thread does writing releasing the requesting object thread). The logger could be signleton or it can be a per-group logger which is a generalization of the above. Now, the question that arise is how does logger should be assigned to the object? There are two options I can think of: **1\. Object requesting for the logger:** Should each of the object call some global API such as `get_logger()`? Such an API returns "the" singleton or the group logger. However, I feel this involves assumption about the Application environment to implement the logger -which I think is some kind of coupling. If the same object needs to be used by other application - this new application also need to implement such a method. **2\. Assign logger through some known API** The other alternative approach is to create a kind of virtual class which is implemented by application based on App's own structure and assign the object sometime in the constructor. This is more generalized method. Unfortunately, when there are so many objects - and rather a tree of objects passing on the logger objects to each level is quite messy. > My question is there a better way to do this? If you need to pick any one of > the above, which approach is would you pick and why? Other questions remain open about how to configure them:   1. How do objects' names or ID are assigned so that will be used for printing on the log messages (as the module names)   2. How do these objects find the appropriate properties (such as log levels, and other such parameters)  In the first approach, the central API needs to deal with all this varieties. In the second approach - there needs to be additional work. Hence, I want to understand from the real experience of people, as to how to write logger effectively in such an environment.


Is there a need for a reporting system in PHP?

I have designed a reporting system to be used in our enterprise level application.   I am able to open source it as this is not our business, and we can gain improved code by contributing it to the community.   My question, is there all ready a reporting system written in PHP, written for php 5.3 by the latest standards etc? Some features of the current version:   1. 100% MVC separation   2. Good framework to manipulate query results, before, during and after fetching   3. easily apply pagination to report   4. Extremely easy to apply numerous filters to reports   5. System, once is learned, can be easily extended (has hookups almost to anything)   6. easily re factored   7. statistical functionality. (Will also be happy to hear what other features I need to add).


Continuous Integration : which frequency?

I've always launched builds after each commit, but on this new project, the architects just asked me to change the frequency to "one build every 15 minutes", and I just can't understand why that would be a good reason vs "building on each commit". First off, some details :   * Objective-C (iOS 5) project   * 10 developpers   * each build actually takes ~1 min, and includes build and unit testing.   * the integration server is a Mac Mini, so computing power isn't really a problem here      * we use Jenkins with the XCode plugin My arguments were that if you build at each commit, you can see right now what went wrong, and correct directly your errors, without bothering the other devs too often. Plus our tester is less bothered by UT errors this way. His arguments were that devs will be flooded by "build error" mails (which is not completely true, as Jenkins can be configured to send a mail only for the first broken build), and that metrics can't be done properly if the frequency of builds is too high. So, what's your opinion on this ?


starting project with growth in mind.

I have an idea for a web application and have some good people keen to get involved. I will be doing most of the code at the start and have a few years experience with some quite large projects. I have nearly 0 budget. What view should I take with regard to data storage / database? Get the project running quickly and inexpensively, then re-evaluate if it is a success? Does anyone have experience with this and advice?


Is it reasonable to require passwords when users sign into my application through social media accounts?

I've built an application that requires users to authenticate with one or more social media accounts from either Facebook, Twitter, or LinkedIn. **Edit** Once the user has signed in, an 'identity' for them is maintained in the system, to which all content they create is associated. A user can associate one account from each of the supported providers with this identity. I'm concerned about how to protect potential users from connecting the wrong account to their identity in our application. **/Edit** There are two main scenarios that could happen:   * User has multiple accounts on one of the three providers, and is not logged into the one s/he desires.   * User comes to a public or shared computer, in which the previous user left themselves logged into one of the three providers. While I haven't encountered many examples of this myself, I'm considering requiring users to password authenticate with Facebook, Twitter, and LinkedIn whenever they are signing into our application. Is that a reasonable approach, or are there reasons why many other sites and applications don't challenge users to provide a user name and password when authorizing applications to access their social media accounts? Thanks in advance! **Edit** A clarification, I'm not intending to store anyone's user name and password. Rather, when a user clicks the button to sign in, with Facebook as an example, I'm considering showing an "Is this you?" type window. The idea is that a user would respond to the challenge by either signing into Facebook on the account fetched from the oauth hash, or would sign into the correct account and the oauth callback would run with the new oauth hash data.


Code review process when using GIT as a repository?

What is the best process for code review when using GIT? We have an external GIT provider (Unfuddle) and have caps on resource usage - so we can't have dedicated remote repositories for every dev. Current process:   * We have a GIT server with a `master` branch to which everyone commits    * Devs work off the local `master` mirror or a local feature branch    * Devs push to server's `master` branch   * Devs request code review on last commit Problem:   * Any bug in code review are already in master by the time it's caught.    * Worse, usually someone has burnt a few hours trying to figure out what happened... So, we would like   * To do code review BEFORE delivery into the 'master'.    * Have a process that works with a global team (no _over the shoulder_ reviews!)   * something that doesn't require an individual dev to be at his desk/machine to be powered up so someone else can remote in (remove human dependency, devs go home at different timezones) We use TortoiseGIT for a visual representation of a list of files changed, diff'ing files etc. Some of us drop into a GIT shell when the GUI isn't enough, but ideally we'd like the workflow to be simple and GUI based (I want the tool to lift any burden, not my devs).


TDD verifying dependency method invoked correctly

I am trying to follow TDD in my proj but I can't get my head around how to verify I am calling a dependency correctly or even if I should be trying to verify it. Here's the requirement: Write an AddSalesOrderTask class that is responsible for adding an order to an ERP system. The class can take any dependencies needed but must have an Execute method signature like this:               public class AddSalesOrderTask {                  public override bool Execute(OrderData input) {           throw new NotImplementedException();       }     }      The AddSalesOrderTask.Execute method needs to map OrderData to ERPSalesOrder and then call IERPClient.AddSalesOrder. I have an interface to access the ERP service like so:               public interface IERPClient {         void AddSalesOrder(ERPSalesOrder order);     }      How do I verify that the mapping is done and then passed into the client? Should I be testing both operations in this method? To make this testable my first thought was to introduce an IMapper interface and pass it as a dependency to AddSalesOrderTask:               public interface IMapper<in TFrom, in TTo> {         void Map(TFrom source, TTo destination);     }      Following TDD would this be a good first test?                   private AddSalesOrderTask _testObj;              [Fake, UsedImplicitly]         private IERPClient _client;              [Fake, UsedImplicitly]         private IMapper<Order, SalesOrder> _mapper;              [TestInitialize]         public void MyTestInitialize() {                     Fake.InitializeFixture(this);             _testObj = new AddSalesOrderTask();         }              [TestMethod]         public void Execute_MappedSalesOrderAddedToERP() {                  // Arrange             var input = new OrderData();             var salesOrder = new SalesOrder();                  // Act             _testObj.Execute(input);                  // Assert                         A.CallTo(() => _mapper.Map(context.Order, salesOrder))                 .MustHaveHappened();             A.CallTo(() => _client.AddSalesOrder(salesOrder))                 .MustHaveHappened();         }      Am I thinking about this correctly?


how to communicate clearly and make sure the team is on task

I'm just doing a course in communication where we code a server and write design documents. Most of the server is already coded, and from the information given in the assignment we just try to fill in the blanks. I'm not really the team leader, but my two teammates are very passive. We often interpret the assignment differently, and I don't understand their thinking very well which frustrates everyone. I try to explain to them my point of view and acknowledge theirs, but after awhile they just give in to me. I want them to understand me, not give in. Teammate A seems to look defeated after we argue, and he gets emotional when frustrated. Should I be more gentle? We all code together. Sometimes I get lost while coding and after a few hours I have no idea what my teammates have done. I ask them what they are doing from time to time but I don't want to be too controlling. Also I'm confused as to which parts should be mine and which parts are my teammates. If a functionality that they need to code ends up having to use my function and change my function a bit, do I have to code the part that will be in my function?


What is the current state of SECD and SKI machine use and research?

I'm doing some independent research/study with a professor who's a very functional guy. The goal is to examine more of what's happening behind the scenes with functional languages than we normally would during the course of the class I'm also taking with him (in which we're writing interpreters). The independent course will go beyond the interpreter level and look at how we might translate some of the concepts to a hardware machine. Specifically, my professor mentioned two books, _Functional Programming: Application and Implementation_ by Peter Henderson -- which covers the _SECD machine_ (an idealized machine for functional computing), and _The Implementation of Functional Programming Languages_ by Simon Peyton Jones -- which covers the _SKI machine_ (and of course _combinators_ ). From the poking around I've done, these two books seem pretty legendary in the functional programming world -- which is great (I still think K&R is one of the best _C_ books). But, both books are also more than 30 years old. I'm curious if there has been any further research or instructive literature produced regarding these topics. It would also be interesting to know if any of these concepts are making their way into modern compilers and close-to-the- kernel interpreters.


Branches/decision count in an example

Having read SO, just found this question:               if (x > y)          print (x)     else if (x < y)          print (y)     else          print (x,y)      **How many branches and decisions are there?** It mentiones there should be 3 decision and 5 branches, yet I cannot see how. For me I can only imagine 4 branches (2 Ifs with two possible results). Original question here


Minimize travel distance of n people to n locations

The problem: Given the coordinates of N people on a regular 2-dimensional plane and N target points-of-interest (POI) on the same plane, determine the set of pairs of people and POIs that minimize the sum of straight-line distances between the locations in each pair. No two people can go to the same POI, and all POIs must be covered. In other words, if I have 5 trucks that need to go to 5 locations and trucks are interchangeable, where do I send the trucks so that the least amount of fuel is used (assuming fuel use is proportional to distance traveled)? Discussion: Brute force would take N factorial. Is there a better way? This would seem to be a pretty common operations research problem, but my google-fu is insufficient.


Is a partially familiar scripting language desirable?

Given that a program (under development) needs a scripting language, and that for various reasons it's not possible to use an off-the-shelf one as is, I'm considering basing it on the syntax and some of the semantics of JavaScript, being something pretty much everyone is familiar with, including using the .js file extension so that e.g. editors will know how to syntax highlight scripts. It's necessary to make _some_ changes anyway, for certain technical reasons. It strikes me as reasonable to make some other changes that most people would consider improvements. For example, eliminating the 'semicolons are optional' rule that sometimes trips people up, and making a block within a function a new lexical contour. But I'm not certain this is what most people actually want. So of the following options:   1. Stick as close to JavaScript as I possibly can, even aspects of it that everyone agrees are mistakes in and of themselves, deviating only when technical considerations make it absolutely necessary. (There is no question of being able to use existing JavaScript code in any case, I'm talking purely about the benefits of familiarity from the user's viewpoint.)   2. Go with the plan currently under consideration, make something that looks pretty much like JavaScript but differs in various regards.   3. All or nothing, if I can't use actual JavaScript, create a new scripting language that is visibly completely different (e.g. not C-style syntax) so there's no possibility of confusing it with JavaScript. Which option would generally be considered preferable? Is there a fourth option I'm missing?


Can I develop GUI in MonoTouch and MonoDroid with a shared .NET backend?

Is it possible to create a shared backend logic using .NET and have the respective GUI front ends in MonoTouch and MonoDroid?


Unit Testing a method that contains two output type parameters

I was following a book Art of Unit Testing, This book says that You must not have any logic in Your asserts as this reduces readability of test, or I may be testing too many things at a time. Suppose there is a method with signature as below:               public int DoSomething(int variable1, out string variable2, out float variable3)     {     ...     }      How should I test this method, as I have to assert on return value, variable2, variable3 ??? * * * Sample Test method that tests all of these three concerns:                   public void DosSomethingTest(){             //add code for arrange             int expectedvalue=12;             string expectedVariable1="I am expected";             string expectedVariable3=15.9;             string actualVariable1, actualVariable3;             var sut=new Foo();             int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);                  //this is where I am testing 3 concerns in one test. Is there a better way?              if(actualValue==expectedvalue){                 if(expectedVariable1==actualVariable1){                     if(expectedVariable3!=actualVariable3){                         Assert.Fail("Unexpected variable2 returned");//pseudo code                     }                 }                 else{                     Assert.Fail("Unexpected variable1 returned");//pseudo code                 }             }             else{                 Assert.Fail("Unexpected Value returned");//pseudo code             }         }      ## Approach 2 * * * Seperate Test methods that tests concerns separately:                   public void DosSomething_Passing15_Returns12Test(){             //add code for arrange             int expectedvalue=12;             string expectedVariable1="I am expected";             string expectedVariable3=15.9;             string actualVariable1, actualVariable3;             var sut=new Foo();             int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);                  Assert.IsTrue(actualValue, expectedvalue);         }              public void DosSomething_Passing15_ReturnsExpectedVariable1Test(){             //add code for arrange             int expectedvalue=12;             string expectedVariable1="I am expected";             string expectedVariable3=15.9;             string actualVariable1, actualVariable3;             var sut=new Foo();             int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);                  Assert.IsTrue(actualVariable1, expectedVariable1);         }              public void DosSomething_Passing15_ReturnsExpectedVariable2Test(){             //add code for arrange             int expectedvalue=12;             string expectedVariable1="I am expected";             string expectedVariable3=15.9;             string actualVariable1, actualVariable3;             var sut=new Foo();             int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);                  Assert.IsTrue(actualVariable3, expectedVariable3);         }      Isn't approach 2 adhering to "Tests should not test more than one concern"? ## Conclusion * * * If redesigning of SUT is possible:   1. There should ideally be no out parameter instead an aggregate class should be evaluated in Asserts.    2. If there are unrelated out parameters then SUT method should be refactored into multiple methods, then those new methods should have their own Test methods and they will then test only one concern. If redesigning of SUT is not possible then as per the answer there will be three Asserts


Schemaless NoSQL RESTful design?

In a recent project; I used MongoDB with MongoEngine (an ORM/ODM for Python). This allowed me to specify schema in a central "Model". My new project I am hosting on Windows Azure; and there is no non-SQL based ORM/ODM wrapper for it in Python. How would you recommend I proceed:   * Engineer my own Python ORM/ODM for Windows Azure   * Or should I not worry about complicated backend business-logic—to reduce computation and transport overhead—and just write routes like this:              POST /api/u_speced/<noun>/create -d {'type': 'schema', **(JSON_schema)}     → {'created': true}     PUT /api/u_speced/<noun>/add -d {'type': 'data', **(JSON validated against JSON_schema)}     →  {'id': <id>}     GET /api/u_speced/<noun>/<id>     →  {JSON representation of record}


How to properly handle conditional dependencies in a factory?

Let's say you have a string `$action` run-time, that specifies which type of `$object` needs to be created: `$dbobject`, `$memcacheobject`, `$fileobject`, `$xmlobject`, etc. Assume also, that creation of an object is non-trivial and a `$factory` is required. Obviously, different object types depend on different things, one on PDO, another on Memcache and so on. So how should I create an object in this conditions? I'm left with a few options:   1. Create a `switch ($action) {}` _outside_ of a factory in order to call different subclasses of my factory, which will call it's type of object, for example: `case 'db': $obj = new DBFactory($dbh); break;`. This is clearly bad, since this switch have to be present everywhere where the object is needed.   2. Have a `switch ($action) {}` _inside_ some sort of a factory factory, which will do the code in #1. What should then the parent factory depend on, everything it _might_ create? Since it _might_ need database and memcache, in order to follow dependency injection rules you need to supply parent factory with _both_ pdo and memcache instances, _even if it won't use them_. That also sounds pretty bad. Another problem is that if I create another object type that depends on something new, then I have to add it's dependencies all over the code where theese factories are instantiated, which is a horizontal change which I should in fact be avoiding. That tells me there is some concept for this problem I don't see right now, therefore the question. What I'm trying to point out is that even if only the `$fileobject` is needed, which does not depend on anything, the code that parses `$action` still needs all dependencies (which is an overkill) or it will instantiace some of them (which is against DI) or needs to reach out to global state/use singletons/registry, which is also considered a bad practice. What would then be a good practice in this situation?


Algorithm for base-conversion in C?

I put in this code which does what it's supposed to do, but perhaps there is a better or more general approach? I'm converting a 4-digit base 10 number e.g. "11" to base 16 e.g. "17" (which gets written out on the display as 11 when called with 17 because the function takes bits as argument).                   int hex1 = perhapsprime / 1000;         int hex2 = (perhapsprime - hex1*1000) / 100;         int hex3 = (perhapsprime - hex2*100 -hex1*1000) / 10;         int hex4 = perhapsprime - hex3*10 - hex2*100 - hex1*1000;         int test = 16*16*16*hex1+16*16*hex2+16*hex3+hex4;      The integer "test" will have the correct value after this code was run, but is there a more efficient way to do it? ## Update 140330 09:43 CET I settled for the following that appears to be able to convert any number of digits to BCD:               int tbcd(int v) {         int total = 0;         int resultbase = 1;         while(v > 0) {             total += resultbase * (v % 10);             resultbase *= 16;             v /= 10;         }         return total;     }


Programming languages differences and efficiency, does it matter?

I am fairly new to programming, I have studied in computer science for 3 years at college, but as you know, school is only 2% of what really makes one a fully-fledged programmer. I have a lot of trouble understanding why people say language x is more efficient that language y. I only understand when it comes to pre-compiled vs runtime compiled. I understand defining data types like a constant in code is bound to be faster than letting the computer/language figure it out(like php or ruby), but when it comes to using C or Java what is it that makes C faster? Aren't they both going to be compiled into machine language in the most efficient way possible? To me, it seems as if the only difference between using a language like C or Java is; a higher level language like java would be easier to organise and write/maintain large applications with classes and inheritance. But I feel as if it should really make no difference when once it is compiled. Can someone explain? btw i only know higher level languages like php, java, ruby, vb, c#. Maybe that's why it is hard for me to imagine? the next language i want to explore is most probably C


Automation Approaches: Events/Triggers/Cron

It has been my experience, when building websites, that most of the logic of a system is executed when user input is accepted, be it via POSTs, GETs etc. I would like to know what processes or methodologies exist in Python (leaning towards using Python), PHP, and Ruby that allow web applications to perform tasks automatically without user input. For instance performing tasks at a certain time or condition or event. I have no experience with, and little understanding of, triggers, events, or cron, and all of the articles I ran across on google during my searches assumed a high familiarity with those concepts. I simply desire a description of ways one could go about handling non-reactive processes in a web application.


How to organise intermodule integration in a modular project?

I'm currently writing my own PHP Framework (yes, another one) for studying purposes. I'll actually try to use it as my graduation dissertation. After two failed attempts, I've finally found a way to develop it in a modular architecture, like Zend and Symfony. I have some loosely coupled modules that can work apart from each other, but their usability would be better if I stick them together. Now I'm wondering the best way of integrate them. I'm not willing to put a module as requirement for the other, because this breaks the modular design. My first idea was to create a different module that requires the other two and put them to work together. This would work fine when I have just two modules, but when I have a module that can be integrated with two or more modules I get lost. Should I create one module for each possible integration? Or should I create just one module and put all integrations I could have there? Am I clear? If not, I'll try to explain it better. ### Edit: A practical example. My Data Access Layer implements the **Table Row Gateway** pattern. I have a `TableGatewayInterface` and a default implementation `TableGateway`. Imagine now that I want a table with a cache for the last queries. I can achive this with the **Decorator** pattern, creating a `CachedTableGateway` that depends on `TableGateway` and a cache component, let's say `CacheInterface`. I don't need the cache, but it could be useful. Should I embed this decorated implementation into the original package, creating a requirement to the cache component? Or should I create an "integration package" that requires both cache and table gateway?


Avoiding pitfalls of a naturally recursive relationship between tables

I'm developing a system to manage "cases". There will eventually be many different "kinds" of cases, so I've started with a "CaseTemplate" table that can be used to define what a case looks like and, via satellite tables, define the specific characteristics for a particluar kind of case. One such characteristic is phases. A case may move through a series of phases, but the phases depend on the kind of case. So, naturally, I created a CasePhases table with a many to one relationship with the CaseTemplate table (since each template may define its own phases). But then I hit a snag... which phase should a case start in? My first thought was that I could just define the "StartingPhase" in the CaseTemplate table using a foreign key, but that creates a recursive relationship between the CaseTemplate and CasePhases tables. I suppose I could make the StartingPhase field nullable and just not assign a value at first (updating the record later when the phases for the CaseTemplate have been defined, and using business logic to ensure that a CaseTemplate has defined a StartingPhase). Or I could add an "IsStartingPhase" field to the CasePhases table (with some business logic to enforce that a Template may have only one phase set as a Starting Phase). Both have some advantages and disadvantages, but neither strike me as particularly elegant or perferable over the other. I've got to believe that this is not an uncommon scenario. Are there any best pratices for handling this database relationship, maybe some terminology I'm missing? I'm looking for an explanation of the problem domain I'm dealing with and perhaps some approaches I've not considered. I'm using a relational database (SQL Server), so solutions using "exotic" technologies probably won't work in my environment.


Naming convention for List in xsd schema

What is the best way to name a List in XSD schema?               <xs:element name="CurrentEmployee" type="Employee" minOccurs="0" maxOccurs="unbounded" />      Currently I have a list of Current Employees as specified in my schema above. But when the Java classes are generated , I access the list of employees as               List<Employee> emps =  req.getCurrentEmployee();      which gives a wrong impression that we are retrieving a single employee. If I make my schema as "CurrentEmployees" , Java code would look good but when we look at the XML data , each row will be displayed as `"<CurrentEmployees ...".` So I can't decide between CurrentEmployees vs CurrentEmployee. Any suggestion for getting this naming convention correct?


Any resources or books to build VNC client

I am very interested in network programming and I want to build a VNC client for fun and for learning purposes. I have been Googling for resources about VNC client and server, but most of time, resources found were about how to use VNC not how to build or how it actually works in business layer so I can get an idea about how it could be simulated. Please suggest me any documentation / articles / resources related to this. Thanks in advance. It is my first post on Programmers Stackexchange site so please forgive me if this question is not appropriate for topic of this site.


Using interfaces as part of encapsulation

I'm creating interfaces for a number of our existing classes for mocking reasons. Many of these classes also have package scope methods as an attempt to give some level of encapsulation by ensuring only the controller can modify some of their state. I had thought I could use this change to try to get cleaner encapsulation as well. My question is two fold. First, is it considered viable to use interfaces for encapsulation? I could make certain methods not in my interface that are available in the class. or I could have my IBar method have a getFoo method that returns an IFoo, but my bar class overrides getFoo to return a Bar. The problem is that anyone could easily cast my Ixxx to the actual class, so is it really considered a worthwhile encapsulation? My second question has to do with my model. I would want my model to have some getAllFoo sort of methods that return IFoo objects. however, I want my controller to have a way to fetch the actuall Foo implementation (ie, know that my IFoo is of type Foo) so that it has access to methods not in the interface. What is considered the cleanest way to ensure my controller has access to the full class but other classes only see the interface? I asume just casting the interface to it's concrete class would be considered rather sloppy?


Is it a good idea to use Header("Content-Type [...]"); in the core file of a CMS?

I have been working on content management systems for about 7 years. 2 years ago created my own. Currently building a newew, better and bigger version. However, fell into dilemma. I have a core file, that gets included to all pages. Core file makes sure of adding functions, config, mysql connection etc. I also have added `Header("Content-Type: text/html; charset=UTF-8");` on the top of the code in the core file. Recently I had to make a xml-generator, with `Header("content-type: text/xml; charset=UTF-8");`. First, of course I couldn't get the xml working, because I forgot about my content-type setting in the core file.. Later I just added the content-type: text/xml after the core file include..   Basically everything works, but I wish polish this project to the finest. **So I'm thinking now, is adding the "content-type: text/html" in the core file, a good idea?** I had an idea, to include the core file like this: `include($rootpath . 'inc/core.php?content-type=xml');`, then in the core file, the header will be set based on the `$_GET['content-type']`.. Is that a good solution?


How can I create and manage permissions more dynamically?

I want to implement a security system into my web-based Intranet application which allows security administrators to 'fine-tune' exactly what type of access a user/role has to an object. For example, an ACL-based solution might allow a receptionist access to `Create`, `Read` and `Update` an appointment but not `Delete` it, similarly I might be able to let user Bob only `Read` or `Comment` on a company memo, but not `Create`, `Update` or `Delete` them. However, how would I go about allowing a receptionist only to make appointments within opening hours? How would I restrict appointments to dates from today to one month from now? What about Bob - how would I let him `Create` a memo after he had gained enough 'respect' points (a bit like on here). Crucially, how can I keep these values dynamic (opening hours, date restrictions, respect points, some new constraint) so that I don't hard-code them into the application? Can anyone recommend a method (or framework, book to read etc) so that I can let the administrator create and manage these roles and their constraints rather than the programmer? The existing ACL and role-based systems I've seen don't seem to offer any way to deal with constraints - you either have access or you don't! Thanks


Do You Still Need Indexing After Database Normalization

After you have done a good normalization, do you still need to index the table? How is this going to affect the performance? Will it even affect the performance in some way after a good normalization? Which columns are usually indexed if you already have the primary key and the foreign key? It's seems like it's already effective to normalize a database. But, I might have skipped how indexing affects the database. Is this only effective when queries are used? How does this work/perform and make a database better?


Why do websites have to ask language and country when the browser can tell them that?

So, why do websites have to ask (spoken) language and country when the browser can tell them that? Edit: Specifically, I mean why not use the accept-language section in the http header, set by the language settings in the browser, not based on the IP address. This question focuses the websites that put up a wall, forcing the user to select a language before using the website, that should instead make available an easily accessible setting. Edit: This is a user experience question, focused on the point that the user should have set the language settings in the browser when they first set up their computer (if the user is smart enough, or can ask someone smart enough).


Creating documents from snippets

From time to time I create whole documents (e.g. XML or proprietary) programmatically. If it easy enough, I just write something like               stringbuilder.append("<blah>");     stringbuilder.append("<blubb>");     stringbuilder.append(someValue);     stringbuilder.append("</blubb>");     stringbuilder.append("</blah>");      But what if the document schema gets more complex? How would one describe it? What if it is not well structured like XML, but has an arbitrary format? Right now I thought about an abstract description of the format that just needs to get the blanks filled. What if I also have to parse such a document? But this seems to be a recurring problem to me. So: Is there some "pattern" to solve that?