title: When is using DI and optionally a IoC framework a step too far?

text: Consider a logging system - used absolutely everywhere in your codebase. _(note - logging is just an example, don't take it too literally and point me at your favourite logging system)._               public interface ILogger     {         void LogMessage(string message);     }          // Just used for testing, do nothing     public class NullLogger : ILogger     {         public void LogMessage(string message) { }     }          public class FileLogger : ILogger     {         public FileLogger(string fileName){...}         public void LogMessage(string message) {              // Log to a file here          }     }      No I could make every single class have ILogger in ctor or param and use some IoC framework. Or I could just use something like               public static class Globals     {        public static ILogger Log = new NullLogger();     }      Use at any point by `Globals.Log.LogMessage("Hello Logging World");` And at 'Compositon Root' (main entry point of program) set `Globals.Log = new FileLogger("somefile.log");` Or this could be done as a Singleton of course. When is using DI and optionally IoC a step too far? What would you do in this case?


title: Improve logic finding possible misconceptions

text: I made a logic to accomplish a specific problem, but it's too long. I've sure that it can be reduce too fit it. I have the following model               public class ColumnChart     {                 public virtual string type { get; set; }         public virtual string name { get; set; }         public virtual List<double> data { get; set; }     }      The idea of `List<double>` is to keep 12 values (1 per month if exists). All these 12 values, has to belong someone, so the `name` will kept the legend The type is `column` (not always, but in this case will to make it simple) **Big Logic**               // Create a List of ColumnChart's     var list = new List<ColumnChart>();          // Instantiate one object of type ColumnChart     var serie = new ColumnChart();          // Instantiate the List<double> (like my model says)     serie.data = new List<double>();          // Control the loop     int i = 0;          foreach (var element in MyDataSource)     {        // If the serie.name don't have the current Group Name that came from my DataSource        if (serie.name != element.GroupName)        {            // Isn't the first loop ?            if (i != 0)            {                // Return a new empty instance of ChartColumn                serie = NewInstance();                     // Set the legend that belong all data                serie.name = element.GroupName;                     // Set the type of the chart                serie.type = "column";                     // Instantiate a new List<double> (like my model says)                serie.data = new List<double>();                     if (serie.data.Count == element.Month - 1)                {                    serie.data.Insert(element.Month - 1, element.ValueRevenue);                }                     // If the number of elements in my List<double> is lower then the Month.                else                {                    while (serie.data.Count < element.Month - 1)                    {                        serie.data.Add(0);                    }                        serie.data.Insert(element.Month - 1, element.ValueRevenue);                 }            }                 // Is the first loop interaction            else            {                 serie.name = element.GroupName;                 serie.type = "column";                 serie.data.Insert(element.Month - 1, elemento.ValueRevenue);                 i++;             }        }             // The serie.name have the same current Group Name that came from my DataSource        else        {            serie.data.Insert(element.Month - 1, element.ValueRevenue);            i++;        }             // My i variable that control the loop is the last interaction ?        if (i == MyDataSource.Count() - 1)        {            list.Add(serie);        }     }          i = 0;      **Data Source**               MyDataSource           [0]                  Month: 1                GroupName: 'Music'                ValueRevenue: 700.0           [1]                  Month: 2                GroupName: 'Music'                ValueRevenue: 700.0           [2]                  Month: 3                GroupName: 'Music'                ValueRevenue: 700.0           [3]                  Month: 4                GroupName: 'Music'                ValueRevenue: 700.0           [4]                  Month: 5                GroupName: 'Music'                ValueRevenue: 700.0           [5]                  Month: 6                GroupName: 'Music'                ValueRevenue: 700.0           [6]                  Month: 7                GroupName: 'Music'                ValueRevenue: 700.0           [7]                  Month: 8                GroupName: 'Music'                ValueRevenue: 700.0           [8]                  Month: 9                GroupName: 'Car'                ValueRevenue: 700.0


title: How to handle encryption key with a large development team?

text: If we have a large development team, say 100, and we would like to keep our encryption key hidden from developers who are not directly involved in the encryption module/algorithm, what are some best practices to keep this key as secret as possible while still allowing for development and debugging?


title: Time passage arithmetic explanation

text: I ported this from http://www.effectgames.com/effect/article.psp.html/joe/Old_School_Color_Cycling_with_HTML5 some time ago. However i'm now wanting to modify it for the purpose of changing it from floating point to fixed point maths for enhanced efficiency (for those who are going to talk about premature optimization and what not, i want to have my entire engine in fixed point both as a learning process for me and so i can port code more easily to systems in the future that dont have native floating points such as arm cpus) My initial conversion to fixed points just resulted in the cycling stuck on either the first or last frame of cycling. Plus it would be nice to understand better how it works so i can add more options and so forth in the future, my maths however sucks and the comments are limited so i don't really know how the maths work for determining the frame it shoud use (cycleAmount) I was also a beginner when i ported it as i had no idea between floating points and integers and what not. So in summary my question is, can anyone give an explination of the arithmatic used for determining the cycleAmount (which determings the "frame" of the cycle) This is the working floating point maths version of the code:               public final void cycle(Colour[] sourceColours, double timeNow, double speedAdjust) {       // Cycle all animated colour ranges in palette based on timestamp.       sourceColours = sourceColours.clone();            int cycleSize;       double cycleRate;       double cycleAmount;            Cycle cycle;       for (int i = 0, len = cycles.length; i < len; ++i) {         cycle = cycles[i];              cycleSize = (cycle.HIGH - cycle.LOW) + 1;         cycleRate = cycle.RATE / (int) (CYCLE_SPEED / speedAdjust);         cycleAmount = 0;              if (cycle.REVERSE < 3) {           // Standard Cycle           cycleAmount = DFLOAT_MOD((timeNow / (1000 / cycleRate)), cycleSize);           if (cycle.REVERSE < 1) {             cycleAmount = cycleSize - cycleAmount; // If below 1 make sure its not reversed.           }         } else if (cycle.REVERSE == 3) {           // Ping-Pong           cycleAmount = DFLOAT_MOD((timeNow / (1000 / cycleRate)), cycleSize << 1);           if (cycleAmount >= cycleSize) {             cycleAmount = (cycleSize * 2) - cycleAmount;           }         } else if (cycle.REVERSE < 6) {           // Sine Wave           cycleAmount = DFLOAT_MOD((timeNow / (1000 / cycleRate)), cycleSize);           cycleAmount = Math.sin((cycleAmount * 3.1415926 * 2) / cycleSize) + 1;           if (cycle.REVERSE == 4) {             cycleAmount *= (cycleSize / 4);           } else if (cycle.REVERSE == 5) {             cycleAmount *= (cycleSize >> 1);           }         }              if (cycle.REVERSE == 2) {           reverseColours(sourceColours, cycle);         }              if (USE_BLEND_SHIFT) {           blendShiftColours(sourceColours, cycle, cycleAmount);         } else {           shiftColours(sourceColours, cycle, cycleAmount);         }              if (cycle.REVERSE == 2) {           reverseColours(sourceColours, cycle);         }       }     colours = sourceColours;     }          // This utility function allows for variable precision floating point modulus.     private double DFLOAT_MOD(final double d, final double b) {       return (Math.floor(d * PRECISION) % Math.floor(b * PRECISION)) / PRECISION;     }


title: Procedural Code vs OOP code

text: I've finished a project in PHP of 13000+ lines in Procedural Style [because I'm very familiar with that, though I know OOP], and the project is running perfectly. But should I convert it to OOP? [ _because the world is busy with OOP_ ] My code doesn't need any of the feature of OOP [encapsulation, inheritance basically...]! So what should I do? And what kind of help I will get if I convert it to OOP ?


title: What is the best way to get a method name in runtime?

text: Here is a little background of my problem: I implemented a singleton logger class which is being called from several projects. I want to log the name of the class as well as the name of the method asked for logging. So far, I thought about two ways to get the name of the method and the class - either by reflection or by manually writing them. The advantage of using reflection is that whenever the name of the class or the method will be renamed, which is not that often, it will be updated automatically. The disadvantage of reflection is that it is performance consuming and it is suggested not to use it whenever you can avoid it, as can be seen in the documentation of reflection (http://docs.oracle.com/javase/tutorial/reflect/index.html) or in various threads online. What would be the best way and why?


title: Is it bad practice to use <?= tag in PHP

text: I've come across this PHP tag `<?= ?>` recently and I am reluctant to use it, but it itches so hard that I wanted to have your take on it. I know it is bad practice to use short tags `<? ?>` and that we should use full tags `<?php ?>` instead, but what about this one : `<?= ?>`? It would save some typing and it would be better for code readability, IMO. So instead of this:               <input name="someVar" value="<?php echo $someVar; ?>">      I could write it like this, which is cleaner :               <input name="someVar" value="<?= $someVar ?>">      Is using this operator frowned upon?


title: Arguments for a coding standard?

text: A few friends and i are planning to work on a project together and we want a COMPLETELY DIFFERENT coding standard. We do NOT want to use the coding standard the libraries/language uses. Its our project and we want to mess around. So i came here to ask what you guys think are good standards and arguments for it (or what not to do and arguments against it). The styles i remember most are   * Upper casing the entire word   * Camel and Pascal casing   * Using '_' to separate each word   * pre or postfixing letters or words (i hate m for member but i think IsCond() is a good func name. SomethingException as a postfix example)   * Using '_' at the start or end of words   * Brace placement. On a new or same line?  I know of libs that use Pascal casing on all public and protected members. But would you ever get confused if something is a func, var or even property if the lang supports it? What about if you decide a public member to be private (or vice versa) wouldnt that great a lot of fix up work or inconsistencies? Is prefixing C to every class a good idea? I ask what do you think and why?


title: Is it a acceptable approach to put try catch wherever null pointer exception occurs?

text: There are instances where the references to objects, fields, variables etc can be null and there might be a possible occurrence of Null Pointer exception occurring at that point. Is is a permanent solution to put these code blocks which expect Null ponter exception to be put in a try catch block?


title: requirements for software quality for internally developed / shared software?

text: In environments where software is built internally by one team and then that software is used by other internal teams, how does one decide what the required quality should be for the produced artefacts? For example:   1. documentation completeness and accuracy   2. extensibility/re-usability of artefact (without hacking at source code)   3. defects   4. etc I guess one aspect to consider is the length of time into a project before quality is considered. It should be more cost effective to ensure quality is built into a product from the start rather than leaving it until later in the project life-cycle.


title: Searching for text within a webpage

text: I'm currently designing a search algorithm for a document, and just got curious about this while designing the algorithm: how do web browsers search a webpage? For example, in Google Chrome, you can press the keyboard shortcut Ctrl-F to activate the "Find" bar, which will let you search a particular webpage for text. How does it do that, given that it only has the raw HTML as reference?


title: Java advice needed, What is Java Messaging Service

text: Is it used for Software Development or Website development? Is it needed (or good) for a JSP Programmer to learn JMS? I know server side scripting languages like JSP and PHP, but I have not found any relation between JSP and JMS.


title: Reasons NOT to use JSF

text: I am new to StackExchange, but I figured you would be able to help me. We're crating a new Java Enterprise application, replacing an legacy JSP solution. Due to many many changes, the UI and parts of the business logic will completely be rethought and reimplemented. Our first thought was JSF, as it is the standard in Java EE. At first I had a good impression. But now I am trying to implement a functional prototype, and have some really serious concerns about using it. First of all, it creates the worst, most cluttered invalid pseudo-HTML/CSS/JS mix I've ever seen. It violates every single rule I learned in web- development. Furthermore it throws together, what never should be so tightly coupled: Layout, Design, Logic and Communication with the server. I don't see how I would be able to extend this output comfortably, whether styling with CSS, adding UI candy (like configurable hot-keys, drag-and-drop widgets) or whatever. Secondly, it is way too complicated. Its complexity is outstanding. If you ask me, it's a poor abstraction of basic web technologies, crippled and useless in the end. What benefits do I have? None, if you think about. Hundreds of components? I see ten-thousands of HTML/CSS snippets, ten-thousands of JavaScript snippets and thousands of jQuery plug-ins in addition. It solves really many problems - we wouldn't have if we wouldn't use JSF. Or the front- controller pattern at all. And Lastly, I think we will have to start over in, say 2 years. I don't see how I can implement all of our first GUI mock-up (Besides; we have no JSF Expert in our team). Maybe we could hack it together somehow. And then there will be more. I'm sure we could hack our hack. But at some point, we'll be stuck. Due to everything above the service tier is in control of JSF. And we will have to start over. My suggestion would be to implement a REST api, using JAX-RS. Then create a HTML5/Javascript client with client side MVC. (or some flavor of MVC..) By the way; we will need the REST api anyway, as we are developing a partial Android front-end, too. I doubt, that JSF is the best solution nowadays. As the Internet is evolving, I really don't see why we should use this 'rake'. Now, what are pros/cons? How can I emphasize my point to not use JSF? What are strong points to use JSF over my suggestion?


title: What Kind of Source Control Do High Security Projects Use?

text: I was just reading this slightly older post on choosing a good source control system when I started thinking about how different projects use source control. Where I work we've essentially moved completely to Git and things have been mostly good. I have wondered about high security projects such as military software projects. Using something like Git there would fundamentally be unsafe; even allowing repo clones under restricted circumstances could be problematic. Using SVN or TFS may not even provide enough security in itself. Are there any VCS systems that have any stronger security considerations? Or are there additional considerations that go into using VCS for high security projects?


title: What issues are there for doing freelance work?

text: I'm considering doing some contract work on the side of my normal job. I know that it will kill my free time, but I figure I can control when I'm doing projects and then get a little extra money or even eventually make it my full time job. But as I've never done this before, I'm wondering what issues people face to do this kind of work. For instance: how do you find customers? What difficulties do you normally face on a project? How do you deal with projects that are too large for one programmer to effectively complete? What about projects that need other skill sets (for instance web design for a web app?)


title: Should I incorporate exit cost into choosing a solution

text: I'm currently choosing between two viable software designs/solutions. Solution 1 is easy to implement, but will lock some data in a proprietary format, and will be hard to change later. Solution 2 is hard to implement, but will be a lot easier to change later on. Should I go YAGNI on this or should I incorporate the exit cost in the decision making? Or asked differently, is the exit cost part of the TCO? I'm thinking of going back to the customer with this to ask whether or not he thinks the exit costs are relevant, but I'd like to know what the community thinks first. P.S. Is exit cost the correct term?


title: So they're trying to pull me into management

text: I work in a small IT department in a non tech company. My manager recently quit and they are looking for a replacement. I guess since I'm one of those "rare" developers with people skills, the director is encouraging me to apply Part of me wants to apply but another part of me says no. The pay and ability to make a difference sound intriguing, and I'm a little burnt out on programming after 12 years, but there are downsides too it seems. I'd be managing someone else who is very interested in the position and it could be awkward since he's a friend and currently higher on the ladder than me (along with a few others). Has anyone else been in a similar position? Is anyone in management and happier or has anyone taken a management job and wished you didn't? Any feedback would be appreciated! * * * @Pratik: When managers worked for ex-employees in the companies that you worked for, did they give them any trouble? * * * EDIT: Thanks everyone for your answers. While this seems like it might be a good opportunity, there are a few things that make me uncomfortable about this. 1) I would be responsible for EVERYTHING instead of what I am asked to do. The department is still reeling after several rounds of lay offs...overstressed and on the verge of burnout. I do have a pretty good relationship with everyone on the team....but I wonder if it wouldn't change if I took this job. 2) A couple of other co-workers despise the director for whatever reason. He might try to get me to do his dirty work and punish them if they butt heads. 3) Managing people who are older than me which doesn't seem to be an issue based on Codemwnci's post. 4) It's a small department and I really don't think a full time manager is needed. IMO we don't need someone to spend 50% of their time ordering people around (because everyone knows what they have to do) and 50% of the time doing nothing. The dept need more of a player-coach IMO. I think it would actually help the team because they would have another person to do support work full time (instead of having a support person write code like I'm doing now) if that makes any sense.   It is difficult but what I'm doing now is also difficult (development + support work) I'd just hate to see them bring in someone from the outside that doesn't know what they're doing or ruins the team we have now which is pretty solid. * * * EDIT (4/30) > Your relationship with the rest of the team **will** change. You are now the > boss rather than a mate. You will need to tell people what to do and they > should do it. Some will be OK with the change, but others might resent that > you've been promoted rather than them. That could be a problem since I'm friends with most of them now. > In this case allocate some of the "easy" project tasks to yourself. These > should be non-critical items that you can pick up and drop at a moment's > notice. This allows you to help on the project, keep up with the code base > but not get distracted from the managerial activities. Another thing you can > do is field all the bug reports that come in. Check them out to make sure > that they are real bugs and, if it's an easy edit, fix it straight away. > Larger problems can then get scheduled in to the rest of the team's > activities. This stops the team getting distracted and also shows the > client/upper management that things do get fixed. Sounds like a good strategy... > To me it comes down to which day-to-day activities you enjoy. Do you like > coaching, meeting with people, project management, building rapport, and > solving people problems? Or do you need lots of alone time, find meetings > draining, dislike drama, and like intellectual/technical problems? I can do both. The main thing for me is work-life balance. My old boss had work-life balance but only because he had dedicated employees below him that knew what they were doing, worked the extra hours, and made his job easy. Of course if someone else took over and the department was mismanaged, work-life balance for everyone could be out the window. * * * EDIT (5/1) @Jeff It's a corporate environment and I have no control in how many people we have or job description of each position. I would hope that my fellow teammates would want me to succeed but I'm not sure. I made friends with some of them and surely this would change our relationship. But I'm not sure the other candidates would be able to run the dept and keep things running smoothly...although I could be wrong.


title: Source code stolen\hacked by rival company

text: On some companies I've worked for, managers have spent quite a lot of money on it-security consultants. Primarily because they're afraid we're gonna get the source code stolen by a rival company. However, as a programmer, I see it as a minor concern that a rival company would find the actual source code useful. After all, just having access to our application is enough, and that can be done without breaking the law. In my opinion, the data handled by the business people would much more useful than source code. My question is; _are there any known examples where source code has gotten stolen AND a rival company have used it extensively?_ I know some game engine (quake 1 and half life 2 if I remember correctly) source code has gotten stolen, but I can't really see that really hurt their business. (I know, this question might be more appropriate for other forum at stackexchange)


title: Field symbol and Data reference in SAP-ABAP

text: If we compare field symbol and data refernece with that of the pointer in C i concluded that :- In C language, Say we declare a variable "var" type "Integer" with default value "5". The variable "var" will be stored some where in the memory and say the memory address which holds this variable is "1000". Now we define a pointer "ptr" and this pointer is assigned to our variable. So, "&ptr" will be "1000" and " *ptr " will be 5. Lets comapre the above situation in SAP ABAP. Here we declare a Field symbol "FS" and assign that to the variable "var". Now my question is what "FS" holds ? I have searched this rigorously in the internet but found out many ABAP consultants have the opinion that FS holds the address of the variable i.e. 1000. But that is wrong. While debugging i found out that fs holds only 5. So fs (in ABAP) is equivalent to *ptr (in C). Please correct me if my understanding is wrong. Now lets declare a data reference "dref" and another filed symbol "fsym" and after creating the data reference we assign the same to field symbol . Now we can do operations on this field symbol. So the difference between data refernec and field symbol is :- in case of field symbol first we will declare a variable and assign it to a field symbol. in case of data reference first we craete a data reference and then assign that to field symbol. Then what is the use of data reference? The same functionality we can achive through field symbol also.


title: Competency matrix for 3D graphic skills

text: As a part of self-evalution, I bumped into this programmer competency matrix which collects many major aspects of being good/expert programmer. It really helped me a lot to understand what I know about programming, what I don't know and what I have never even thought about. Now, I would need same kind of matrix about 3D graphics programming skills - not so much about using software to build models but about general 3D stuff, mathematics, using shaders, performance/optimizations etc. Does anyone have an idea where I could find one? It does not have to be perfect (and not even matrix necessarily) but it would be nice to have at least some basic aspects covered.


title: Is "Interface inheritance" always safe?

text: I'm reading "Effective Java" by Josh Bloch and in there is Item 16 where he tells how to use inheritance in a correct way and by inheritance he means only class inheritance, not implementing interfaces or extend interfaces by other interfaces. I didn't find any mention of interface inheritance in the entire book. Does this mean that interface inheritance is always safe? Or there are guidlines for interface inheritance?


title: is there an “app store” for regular pc apps?

text: I have written an app for the computer in java, but i don't want to give it out for free. I only want to charge somewhere between $0.99 - $2.99, is there a website that i can upload it to, to do this for me. I am looking for something like the apple app store, or the android market, but for the computer. Does this exist? also, is there a way to control the amount of computers it can be installed on? ie. if a person is using a specific key, they can only use the program one one computer at a time, like i-tunes movies. the program is a standalone app, meaning there is no installation process, you just open the executable file and it works. will this be a problem for integrating a licensing function.


title: Event driven language for Robotics

text: There are several options that are available like C, C++, Matlab and some more. But is there a language that naturally feels like Event programming? For example: If I see a red ball (Event) ---> Do this (Action)


title: css - use universal '*' selector vs. html or body selector?

text: Applying styles to the body tag will be applied to the whole page, so               body { font-family: Verdana }      will be applied to the whole page. This could also be done with               * {font-family: Verdana}       which would apply to all elements and so would seem to have the same effect. I understand the principle that in the first instance the style is being applied to one tag, body for the whole page whereas in the second example the font is being applied against each individual html elements. What I am asking is what is the practical difference in doing that, what are the implications and what is a reason, situation or best practice that leads to using one over another. One side-effect is certainly speed (+1 Rob). I am most interested in the actual reason to choose one over the other in terms of functionality.


title: How do you keep code with continuations/callbacks readable?

text: Summary: **Are there some well-established best-practice patterns that I can follow to keep my code readable in spite of using asynchronous code and callbacks?** * * * I'm using a JavaScript library that does a lot of stuff asynchronously and heavily relies on callbacks. It seems that writing a simple "load A, load B, ..." method becomes quite complicated and hard to follow using this pattern. Let me give a (contrived) example. Let's say I want to load a bunch of images (asynchronously) from a remote web server. In C#/async, I'd write something like this:               disableStartButton();          foreach (myData in myRepository) {         var result = await LoadImageAsync("http://my/server/GetImage?" + myData.Id);         if (result.Success) {             myData.Image = result.Data;         } else {             write("error loading Image " + myData.Id);             return;         }     }          write("success");     enableStartButton();      The code layout follows the "flow of events": First, the start button is disabled, then the images are loaded (`await` ensures that the UI stays responsive) and then the start button is enabled again. In JavaScript, using callbacks, I came up with this:               disableStartButton();          var count = myRepository.length;          function loadImage(i) {         if (i >= count) {             write("success");             enableStartButton();             return;         }              myData = myRepository[i];         LoadImageAsync("http://my/server/GetImage?" + myData.Id,             function(success, data) {                  if (success) {                     myData.Image = data;                 } else {                     write("error loading image " + myData.Id);                     return;                 }                 loadImage(i+1);              }         );     }          loadImage(0);      I think the drawbacks are obvious: I had to rework the loop into a recursive call, the code that's supposed to be executed in the end is somewhere in the middle of the function, the code starting the download (`loadImage(0)`) is at the very bottom, and it's generally much harder to read and follow. It's ugly and I don't like it. I'm sure that I'm not the first one to encounter this problem, so my question is: **Are there some well-established best-practice patterns that I can follow to keep my code readable in spite of using asynchronous code and callbacks?**


title: Challenges in multi-player Android Game Server with RESTful Nature

text: I'm working on an Android Game based on Contract Bridge, as a part of my college Summer Internship project. The game will be multi-player such that 4 Android devices can play it, so there's no BOT or CPU player to be developed. At the time of getting project, I realized that most of the students had already worked on the project but none of their works is reusable now (for variety of reasons like, undocumented code and design architecture, different platform implementation). I have experience working on several open source projects and hence I emphasis to work out on this project such that components I make become reusable as much as possible. Now, as the game is multi-player and entire game progress will be handled on server, I'm currently working on Server's design, since I wanted to make game server reusable such that any client platform can use it, I was previously confused in selecting Socket or REST for Game Server's design, but later finalized to work on REST APIs for the server. Now, since I have to keep all players in-sync while they make movements in game, on server I've planned to use Database which will keep all players' progress, specific for each table (in Bridge, 4 players play on single table, and server will handle many such game tables). I don't know if its an appropriate decision to use database as shared medium to track progress of each game table (let me know if there's an appropriate or better option). Obviously, when game is completed for the table, data for that table on server's database is discarded. Now the problem is that, access to REST service is an HTTP call, so as long as client doesn't make any request, server will remain idle, and consider a situation where   * A player has played a card on his device and the device requests to apply this change on the server.   * Now, I need to let rest of the three devices know that the player has played a card, and also update view on their device.   * AFAIK, REST cannot provide a sort-of Push-notification system, since the connection to the server is not persistent.      * One solution that I thought was to make each device constantly poll the server for any change (like every 56 ms) and when changes are found, reflect it on the device. But I feel this is not an elegant way, as every HTTP request is expensive. (and I choose REST to make game play experience robust since, a mobile device tends to get disconnected from Internet, and if there's Socket-like persistent connection then entire game progress is subject to lost. Also, portability on client-end is important)   * Also, imagining a situation where 10 game tables are in progress and 40 players are playing, a server must be capable to handle flooded HTTP requests from all the devices which make it every 56 ms. So I wonder if the situation is assumed as DoS attack. So, explaining the situation, am I going on the right track for the server design? I wanted to be sure before I proceed much further with the code.


title: introducing automated testing without steep learning curve

text: We're a group of 4 developers on a ajax/mysql/php web application. 2 of us end up focusing most of our efforts on testing the application, as it is time- consuming, instead of actually coding. When I say testing, I mean opening screens and testing links, making sure nothing is broken and the data is correct. I understand there are test frameworks out there which can automate this kind of testing for you, but I am not familiar with any of them (neither is anyone on the team), or the fancy jargon (is it test-driven? behavior-driven? acceptance testing?) So, we're looking to slowly incorporate automated testing. We're all programmers, so it doesn't have to be super-simple. But we don't want something that will take a week to learn... And it has to match our php/ajax platform... The Question: Which testing framework will allow us to jump in right away without spending a lot of time learning the syntax and/or a new programming language.


title: Future proofing code

text: Where I work developers are always telling me that "I added this just in case for the future" or "I think it's a good idea to do this because they'll probably want it some day". I think it's great that they're proactive in trying to anticipate future changes but I can't help thinking that it's unnecessary and risks writing code that may never be needed and therefore unproductive (I also think that some developers just want to try out something new for the sake of it). Are the arguments for future proofing invalid if you just write good, clean organised code?


title: Merging similar graphs based solely on the graph structure?

text: I am looking for (or attempting to design) a technique for matching nodes from very similar graphs based on the structure of the graph*. In the examples below, the top graph has 5 nodes, and the bottom graph has 6 nodes. I would like to match the nodes from the top graph to the nodes in the bottom graph, such that the "0" nodes match, and the "1" nodes match, etc. This seems logically possible, because I can do it in my head for these simple examples. Now I just need to express my intuition in code. Are there any established algorithms or patterns I might consider? (* When I say based on the structure of the graph, I mean the solution shouldn't depend on the node labels; the numeric labels on the nodes are only for demonstration.) UPDATE: It has been correctly pointed out that using the structure alone, most of these graphs can't be solved with 100% accuracy. I've added some thoughts to each graph. I'm also interested in the performance of any potential solutions. How well will they scale? Could I merge graphs with millions of nodes? In more complex cases, I recognize that the best solution may be subject to interpretation. Still, I'm hoping for a "good" way to merge complex graphs. (These are directed graphs; the thicker portion of an edge represents the head.) ![Example 1](http://i.stack.imgur.com/vxEmS.png) This graph is a cycle with 1 node "attached to the outside." After attaching a second node to the outside it's not possible to determine whether the new node (node 5) is attached to node 1 or 3. The 4 nodes composing the cycle can't be perfectly matched either. ![Example 2](http://i.stack.imgur.com/3Bkbd.png) Nodes 1 and 5 can be swapped in the bottom graph without changing the structure. Thus, you can only guess with 50/50 accuracy which is the new node. ![Example 3](http://i.stack.imgur.com/jmU7l.png) This graph has symmetry in 2 dimensions and can be mirrored without changing the structure. Meaning you can swap several nodes without changing the structure. ![Example 4](http://i.stack.imgur.com/CeUEb.png) This last graph is the only one for which you can identify the new node with 100% accuracy. Thanks Kirk Broadhurst, for pointing this out.


title: how a pure functional programming language manage without assignment statements?

text: When reading the famous SICP, I found the authors seem rather reluctant to introduce the assignment statement to Scheme in Chapter 3. I read the text and kind of understand why they feel so. As Scheme is the first functional programming language I ever know something about, I am kind of surprised that there are some functional programming languages (not Scheme of course) can do without assignments. Let use the example the book offers,the `bank account` example. If there is no assignment statement, how can this be done?How to change the `balance` variable? I ask so because I know there are some so-called pure functional languages out there and according to the Turing complete theory, this must can be done too. I learned C, Java, Python and use assignments a lot in every program I wrote. So it's really an eye-opening experience. I really hope someone can briefly explain how assignments are avoided in those functional programming languages and what profound impact (if any) it has on these languages. The example mentioned above is here:               (define (make-withdraw balance)         (lambda (amount)             (if (>= balance amount)                 (begin (set! balance (- balance amount))                     balance)                 "Insufficient funds")))      This changed the `balance` by `set!`. To me it looks a lot like a class method to change the class member `balance`. As I said, I am not familiar with functional programming languages, so if I said something wrong about them, feel free to point out. **EDIT** :I guess to fully understand the question, I have to dig into a pure functional programming language.Thanks for all the answers. I sure learned a lot.


title: How to maintain view logic separation with a server

text: I am writing a client server application. I wanted to fully separate the server logic, from the view. The first thing I wanted to to, is to make a sort of a message log. The server itself should not know if the messages will be shown at a GUI, or on the console. What I was thinking, would be to have a handler method, that would be called every time a new message was posted. So a GUI app would have it's own method to maybe add to a listView, while the console would have a simple printf. Is there a better way to do this?


title: Can some LGPL library published upgrades use a commercial library?

text: I am using a LGPL v3 library and have made upgrades to it. Before using these upgrades, I understand I have to publish them. That's al-right.   1. Is it legal if I perform upgrades that use a commercial library of my own (upgrades will be published, but not my commercial library)? Note: usually, questions are the other side: commercial applications that want to use GPL libraries.   2. If yes to (1), is there some restrictions on the build of the upgraded LGPL library ? Shall the commercial library be dynamically or statically linked, or whatever ?


title: How to explain OOP concepts to a non technical person?

text: I often try to avoid telling people I'm a programmer because most of the time I end up explaining to them what that really means. When I tell them I'm programming in Java they often ask general questions about the language and how it differs from x and y. I'm also not good at explaining things because 1) I don't have that much experience in the field and 2) I really hate explaining things to non-technical people. They say that you truly understand things once you explain them to someone else, in this case how would you explain OOP terminology and concepts to a non technical person?


title: how to install lib_mysqludf_sys.dll?

text: I have put the "lib_mysqludf_sys.dll" in C:/Xampp/mysql/lib/plugin. in "my.ini" config file the plugin directory has been set correctly. after putting that .dll file in the appropriate place, I restarted the mysql server. all things seems are correct. then I write CREATE FUNCTION sys_exec RETURNS INT SONAME 'lib_mysqludf_sys.dll' in phpmyadmin but I confront with Can't open shared library 'lib_mysqludf_sys.dll' (errno: 193 ) ... can anybody help me and say to me where I have done incorrectly or might have not done? your cooperation is appreciated before. meisam...


title: Prerequisites for developing an application with Unicode support

text: What could be the necessary prerequisites to be taken when developing an application with Unicode support in the context of   1. Web applications   2. Desktop applications   3. Embedded applications Prerequisites to be taken care of relating to   * Type casting and conversion   * Data Storage   * Fallback in case of no Unicode support   * Transition from a database without Unicode support to a database with Unicode support Answers pertaining to real-world projects are preferred


title: How should I extend an existing Service?

text: Our system's main functionality is encapsulated in a service, let's call it X. There are requests coming in to X-Manager service which deal with all validations and security issues, and activates X's functionality after everything passed. We now want to extend X's functionality with a new module, let's call it Y, but without changing X's code too much, preferably without changing it at all. Also, Y may be able to work on it's own some day (and not only extending X) The main idea now in the team is to make X-Manager **call Y with X instead of just calling X, so that Y will do it's thing and then Y Will call X's functionality instead of X-Manager.** I don't know why but this smells icky to me, I hope I managed to explain this well... **Is there any better way of doing this?**


title: Easiest way to create static HTML file with sortable and filterable table?

text: I want to create a static HTML file I can email to someone with a lot of data, and have that data sortable and filterable. What is the easiest to use library or package I can use to get this off the ground?


title: How can I handle this string concatenation in C in a reusable way

text: I've been writing a small C application that operates on files, and I've found that I have been copy+pasting this code around my functions:               char fullpath[PATH_MAX];     fullpath[0] = '\0';     strcat(fullpath, BASE_PATH);     strcat(fullpath, subdir);     strcat(fullpath, "/");     strcat(fullpath, filename);          // do something with fullpath...      Is there a better way? The first thought that comes to mind is to create a macro but I'm sure this is a common problem in C, and I'm wondering how others have solve it.


title: Line break before/after operator

text: While Sun's Java code convention suggests to put line break before the operator many other guidelines disagree with it. I do not see any obvious pros and cons, so are there advantages of using one of these styles over another?               String longVarName = a + b + c + d +               e + f;      vs               String longVarName = a + b + c + d               + e + f;


title: Is it a must to focus on one specific IT subject to be succesful?

text: Lately I'm deeply disturbed by the thought that I'm still not devoted to one specific IT subject after so many years of doing it as a hobby. I've been in so many different IT related hobbies since I was 12. I have spent 8 years and now I'm 20 and just finished freshman year at Computer Eng. Just to summarize the variety:   * 3D Game Dev. and Modelling (Acknex, Irrlicht , OpenGL, GLES, 3DSMAX)   * Mobile App.Dev (Symbian, Maemo, Android)   * Electronis (Arduino)   * Web.Dev. (PHP, MYSQL, Javascript, Jquery, RaphaelJS, Canvas, Flash etc.)   * Computer Vision (OpenCV) I need to start making money. But I'm having problem to pick the correct IT business to do so. **Is it a problem to have interest in so many different IT subjects?(in business world)** I'm having a lot of fun by doing all those stuff from time to time. Other than making money I also noticed that having so many different interests is lowering my productivity. But I'm still having difficulty to pick one. I'm feeling close to all those subjects (time to time).


title: LGPL open source license

text: I have recently become curious about open source licenses. I have a question about the LGPL. I created a Java web project and built it as a WAR package. Can I add LGPL jars to this WAR file?


title: Is there a reason that tests aren't written inline with the code that they test?

text: I've been reading a bit about Literate Programming recently, and it got me thinking... Well-written tests, especially BDD-style specs can do a better job at explaining what code does than prose does, and have the big advantage of verifying their own accuracy. I've never seen tests written inline with the code that they test. Is this just because languages don't tend to make it simple to separate application and test code when written in the same source file (and nobody's made it easy), or is there a more principled reason that people separate test code from application code?


title: Naming guard clauses that throw exceptions

text: I have a function `evaluate()` that parses a `String` for some variables and replaces them with their corresponding value:               public String evaluate() {         String result = templateText;         for (Entry<String, String> entry : variables.entrySet()) {             String regex = "\\$\\{" + entry.getKey() + "\\}";             result = result.replaceAll(regex, entry.getValue());         }         if (result.matches(".*\\$\\{.+\\}.*")) {    //<--check if a variable wasn't replaced             throw new MissingValueException();         }         return result;     }      Since the `evaluate()` function now does 2 things, it first replaces the variables with the values **AND** check for any variables that weren't replaced, I thought about refactoring it to:               public String evaluate() {         String result = templateText;         for (Entry<String, String> entry : variables.entrySet()) {             String regex = "\\$\\{" + entry.getKey() + "\\}";             result = result.replaceAll(regex, entry.getValue());         }         checkForMissingValues(result);     }          private void checkForMissingValues(String result) {         if (result.matches(".*\\$\\{.+\\}.*")) {             throw new MissingValueException();         }     }      Now is this a good name for the function `checkForMissingValues`? I mean it does check for missing values, but it also throws an exception. I thought about renaming it to `throwExceptionIfMissingValueWasFound()`, but this name tells **HOW** the function does it more than **WHAT** the function is doing. Is there a standard for naming such functions that check for a condition then throw an exception?


title: Bug Tracking Etiquette - Necromancy or Duplicate?

text: I came across a really old (2+ years) feature request issue in a bug tracker for an open source project that was marked as "resolved (won't fix)" due to the lack of tools required to make the requested enhancement. In the time elapsed since that determination was made, new tools have been developed that would allow it to be resolved, and I'd like to bring that to the attention of the community for that application. However, I'm not sure as to what the generally accepted etiquette is for bug tracking in cases like this. Obviously, if the system explicitly states to not duplicate and will actively mark new items as duplicates (much in the way the SE sites do), then the answer would be to follow what the system says. But what about when the system doesn't explicitly say that, or a new user can't easily find a place that says with the system's preference is? Is it generally considered better to err on the side of duplication or necromancy? Does this differ depending on whether it's a bug or a feature request?


title: What are pros and cons of using "in-house" tools?

text: What are pros and cons of using "in-house" tools, from real-world experience?


title: Why can't java generics be in arrays?

text: Why is it that when I try to make an array of ArrayLists: `ArrayList<Integer>[] arr=new ArrayList<Integer>[40];` there is an error and java does not allow this? Is there a reason related to java's implementation of generics, generics in any language, or something arbitrary?


title: What should web programmers know about cryptography?

text: Should programmers who build websites/web applications understand cryptography? I have no idea how most crypographic algorithms work, and I really don't understand the differences between md5/des/aes/etc. Have any of you found any need for an in-depth understanding of cryptography? I haven't needed it, but I wonder if perhaps I'm missing something. I've used salt + md5 hash to encrypt passwords, and I tell webservers to use SSL. Beyond that, I can't say I've used much else, nor can I say with any certainty _how_ secure these methods are. I only use them because other people claim they are safe. Have you ever found a need to use cryptography in web programming aside from these two simple examples?


# The General Question What are the differences between algorithms using data structures and algorithms using databases? # Some Context This is a question that has been bugging me for some time, and I have not been able to come up with a convincing answer for it. Currently, I am working on strengthening my understanding of algorithms that, of course, heavily involve data structures. These are basic structures such as Bag, Queue, Stack, Priority Queue, and Heap. I also use databases on a daily basis to store the data that has been processed and submitted by the end-user or processed by the program. I retrieve and submit the data through a DAL, which has data structures of its own that are generated based on the tables in the database. My questions come when I have the option to sort the data using the database to send it back to me ordered in either an ascending/descending fashion or retrieve and load the data into my logic, process this data in a priority queue, and heap sort all of it. Or another one would be to search for records using the database rather than loading a subset of the records and using something like binary search to find the record or records I am interested in. In my mind, I would try to have as many operations take place on the database- end before sending it over because communication is expensive. This also makes me wonder when do you use algorithms and data structures strictly defined within your own logic rather to process data than that of the database's? So here are the questions... # Questions   1. What are the differences between data structures and databases?   2. When do we use algorithms that use data structures defined solely within your own logic and not that of the database's?   3. **@Harvey post:** When do the methods in the database become less efficient to use than methods in your own logic?      * **@mirculixx post:** What makes a method efficient?   4. **@Harvey post:** How is processing data with data structures faster than doing it in the database? # Clarifications   1. **@Grant post:** The databases I normally work with are relational, and these questions are coming out of working with them. However, I do think these questions are applicable to any persistence framework (when I say framework, I mean it in the most general sense). I know answers without a specific context are difficult. Food-for-thought, advice, or discussion points are mainly what I'm looking for and would be most appreciated!


title: How far should one take e-mail address validation?

text: I'm wondering how far people should take the validation of e-mail address. My field is primarily web-development, but this applies anywhere. I've seen a few approaches:   * simply checking if there is an "@" present, which is dead simply but of course not that reliable.   * a more complex regex test for standard e-mail formats   * a full regex against RFC 2822 \- the problem with this is that often an e-mail address might be valid but it is probably not what the user meant    * DNS validation   * SMTP validation As many people might know (but many don't), e-mail addresses can have a lot of strange variation that most people don't usually consider (see RFC 2822 3.4.1), but you have to think about the goals of your validation: are you simply trying to ensure that an e-mail address can be sent to an address, or that it is what the user probably meant to put in (which is unlikely in a lot of the more obscure cases of otherwise 'valid' addresses). An option I've considered is simply giving a warning with a more esoteric address but still allowing the request to go through, but this does add more complexity to a form and most users are likely to be confused. While DNS validation / SMTP validation seem like no-brainers, I foresee problems where the DNS server/SMTP server is temporarily down and a user is unable to register somewhere, or the user's SMTP server doesn't support the required features. How might some experienced developers out here handle this? Are there any other approaches than the ones I've listed? Edit: I completely forgot the most obvious of all, sending a confirmation e-mail! Thanks to answerers for pointing that one out. Yes, this one is pretty foolproof, but it does require extra hassle on the part of everyone involved. The user has to fetch some e-mail, and the developer needs to remember user data before they're even confirmed as valid.


title: How can I efficiently approach cookie-based session handling?

text: Currently our web application uses server-sided sessions. Because of the large amount of memory usage, we want to switch to cookie-based sessions. I have been thinking about several ways: ### Idea 1 My first idea was to give the client two cookies: `SessionID` (a hash) and `SessionData` (the encrypted data). The `SessionID` will be used to look up a decryption key for `SessionData` in an in-memory hashtable. Because only decryption keys are stored on the server, this should wind up being less memory usage. However it still uses some memory, and the CPU load is increased due to encryption/decryption on every request. It'd also make the session cluster-dependant, with no graceful failover possible. ### Idea 2 My second idea was similar to the fist, but instead of looking up a decryption key in a cache, I'd use a salted version of `SessionID` to decrypt `SessionData`. The upside is that there wouldn't be any in-memory cache or hash table anymore, and that session would be cluster-independent if the salt is the same for all clusters. However, the tradeoff is that it's much less secure due to a potential danger of decrypting or modifying the `SessionData` cookie, and that the CPU load is increased due to encryption/decryption on every request. Is there a better way to go about this problem? Or a way to modify one of these ideas to be a little more palatable?


title: Are there any actual examples of profitable programmer's "worker's cooperatives"?

text: http://en.wikipedia.org/wiki/Worker_cooperative I'm curious whether there are, anywhere in the world, worker's cooperatives that center on a technology business that involves either programming, IT, or some sort of IT or programming related consulting or services. The wikipedia link above is an overview of the concept. The short form explanation is that a co-op is a worker-owned business. Also there is the notion that every worker owns shares in the business. I am interested in knowing whether an example of a "programmer's/IT co-op" even exists. Note: I am not talking about nor asking about a government-funded incubator nor any other socialized, state supported group. I also don't mean "co- working", which is renting an office with other self employed people doing their own thing. I mean a going, profitable IT business operating in a competitive environment that is worker-owned and run.


title: How to do this in Standard UML?

text: In the below Sequence  diagram, when the user have entered the Username and Password, I have to do the authentication. Now you can see two details **valid details** and **invalid detail** in the diagram , which i will return when the **user password match** and **miss-match** respectively. Now My big question is which one i have to draw first, either **valid details** or **invalid detail** , how I know which one will come first.


title: What's the limitation of APSL compared to BSD or MIT?

text: I heard some people complain that APSL 2.0 ( http://www.opensource.apple.com/license/apsl/ ) has too many limitations. What's the limitation of it compared to BSD or MIT?


title: Is javascript worth learning if you do not plan on being a web developer?

text: I heard Javascript is a full language just like c++. Is this true? What else is it good for programming besides web stuff?


title: Why DependencyProperties and not native language support?

text: With advent of WPF and MVVM Microsoft introduced `DependencyProperties` and `INotifyPropertyChange` interface to provide a way to implement the "reactive" approach used with those technologies. Sadly both of these constructs are very verbose, require much boilerplate, are clumsy to use, also are not really that safe since they require much use of "magic strings". So here come the question: why didn't they put these functionalities directly into the language - why didn't they create new kind of properties created with a simple keyword, providing useful stuff of `DependencyProperties` (like events on change and so on...). What were stopping them?


title: Is there a name for the school of thought behind writing tests?

text: Essentially it is a branch of software engineering but SE itself is too large an umbrella. I was curious if there was a title for the knowledge base that encompasses TDD, BDD, mocks/stubs/spys, unit tests vs. integration tests, code coverage, etc.


title: What am I risking if I don't update my SDK/JDK and bundled runtime/JRE every time there's a security update?

text: It seems like there's a new major security hole patched in Java every other week, and I would assume the same goes for other development platforms. After years of frustration trying to get customers to install and configure a compatible JRE on their systems, we started bundling one with our software. (By bundling, I mean we extract a copy of the JRE in our installation directory--we don't install the JRE and configure it as the system default.) The problem is, it's a hassle having to keep that JRE up-to-date because first we have to retest everything to make sure the update didn't break anything (it has broken some of our third-party dependencies in the past). How seriously, if at all, are we putting our customers at risk if we don't update our SDK/JDK and the runtime/JRE that we bundle with our product every time there's a security update? Is it reasonable to just update on a periodic schedule--say, once every 6 months or so?


title: Drawing thread interaction

text: I'd like to draw (pen and pencils) threads interaction in a UML(-like) notation. I don't insist on UML, anything that is obvious to the reader should do. I started with sequence diagrams, but I don't feel this is the best way to do that. All the time, there would be "action initiators" coming from off-screen which kinda break the SSD idea. I inherited a medium size code base with around 9 - 10 threads each owning a state machine and I'm trying to figure out how it works. How should I visualize thread interaction?


I'm writing an essay, and would like to have some empiric evidence, perhaps longitudinal data where the popularity of these technologies is compared over a period of some years. Are there any statistics that show the popularity of Git versus SVN?


title: Why do concurrent languages tend to have more complicated syntax?

text: This is a question that's been on my mind for a while. Recently I've been checking out concurrent languages like Haskell or Go or Erlang. From my point of view, they have huge benefit in performance as opposed to languages like C++ or Python because of the way they handle functions in parallel. My question is: Why is the syntax for languages like C++ or Python so much different (and IMO simpler) from those of concurrent languages, even though most concurrent languages are executed on runtime (and therefore they have more possibility in simplifying the syntax)? Here is an example, consider Go's `sqrt`:               // Package newmath is a trivial example package.     package newmath          // Sqrt returns an approximation to the square root of x.     func Sqrt(x float64) float64 {         z := 1.0         for i := 0; i < 1000; i++ {             z -= (z*z - x) / (2 * z)         }         return z     }      Now for the Python counterpart (ported this myself based on the `Sqrt` example from Go):               def Sqrt(x):      z = 1.0      for i in Range(0, 1000):       z -= (z*z-x/2*z)       return z      Now as you can see go has a syntax like ":=" for assignment, If you take a more complicated examples, the syntax will look more like what I am trying to point out. And Go is just the least "weird-looking" language. If you consider Erlang it's looking even weirder:               %% qsort:qsort(List)     %% Sort a list of items     -module(qsort).     % This is the file 'qsort.erl'     -export([qsort/1]). % A function 'qsort' with 1 parameter is exported (no type, no name)          qsort([]) -> []; % If the list [] is empty, return an empty list (nothing to sort)     qsort([Pivot|Rest]) ->         % Compose recursively a list with 'Front' for all elements that should be before 'Pivot'         % then 'Pivot' then 'Back' for all elements that should be after 'Pivot'         qsort([Front || Front <- Rest, Front < Pivot])         ++ [Pivot] ++         qsort([Back || Back <- Rest, Back >= Pivot]).      Parts that caught my eye were "++ [] ++", '<-' and '->' I am convinced these languages look like this for a reason, but I can't help but think: Can't it be simpler? Why are concurrent languages like this? Why if they use a runtime like Python and JavaScript, are they still type-safe? I know type-safe languages have an advantage of their own to not mix up variable types, but still, there's gotta be somebody who made a concurrent language that didn't have type-safety, if possible right? It seems like almost all concurrent languages have one thing in common: a bigger list of possible / valid syntax. I hope I've explained my question well enough.


title: How to manage a lot of Action Listeners for multiple buttons

text: I have this Tic Tac Toe game and I thought of this really cool way to draw out the grid of 9 little boxes. I was thinking of putting buttons in each of those boxes. How should I give each button (9 buttons in total) an `ActionListener` that draws either an **X** or **O**? Should they each have their own, or should I do some sort of code that detects turns in `this`? Could I even do a `JButton Array` and do some `for` loops to put 9 buttons. So many possibilities, but which one is the most **proper**? Code so far:               import javax.swing.*;          import java.awt.event.*;     import java.awt.*;     public class Board extends JPanel implements ActionListener{     public Board(){         Timer timer = new Timer(25,this);         timer.start();     }     @Override     protected void paintComponent(Graphics g){         for(int y = 0; y < 3; y++){             for(int x = 0; x < 3; x++){                     g.drawRect(x*64, y*64, 64, 64);             }         }     }     public void actionPerformed(ActionEvent e){         repaint();     }     }


title: Advantage of Tagging a Release in SVN versus Only Leaving a Comment for the Commit

text: In my company, we have had a policy of tagging every release. Someone new joined, and he suggested that instead of formally using a Tag, we could just leave a comment for the release build when it is checked in. I like using a Tag, but, obviously, we can also get to the source code for a build also by looking for the comment. The only advantage I see is that because our product spans multiple technologies, we can group the source code for both in the same directory with a folder for each. **Is there some other advantage of tagging releases that I'm missing?** BTW, we are using SVN.


title: How is architectural design done in an agile environment?

text: I have read Principles for the Agile Architect, where they defined next principles : > Principle #1 The teams that code the system design the system.   >  Principle #2 Build the simplest architecture that can possibly work.   >  Principle #3 When in doubt, code it out.   >  Principle #4 They build it, they test it.   >  Principle #5 The bigger the system, the longer the runway.   >  Principle #6 System architecture is a role collaboration.   >  Principle #7 There is no monopoly on innovation. The paper says that most of the architecture design is done during the coding phase, and only system design before that. That is fine. So, how is the system design done? Using UML? Or a document that defines interfaces and major blocks? Maybe something else?


title: How to sell your libraries?

text: If someone has created something like a DevExpress library, or Infragistics, Telerik, RavenDb etc., what's the easiest way to start selling it? What are the required steps? Is there some rules for licenses and stuff?


title: Should Libraries Use Events or a Set Action

text: I'm building a small reusable library for two systems our company manages. Something that I've been caught up on is whether I should expose a set of properties of type `Action<T>` for events such as Completed, Aborted, ExceptionOccured, or if I should use the `Event<T>` T : EventArgs methodology. In practice another internal library will be consuming this information and handling the display of information to the user. The library's classes will be instantiated within a single thread and wouldn't be consumed by anything outside of its owner. To me it seems more along the lines of if I only need to notifications are only ever going to be consumed by one object then it doesn't matter, however for completeness, and due to the fact that I as the library auther have little control over how another developer implements this, I should use the Event method due to it's broader ability to handle events. EDIT (sample code): @Robert Harvey, I read that post when searching for reasoning on picking one over the other. I understand the answer in context to that question, but I'm not sure how it relates to using the event keyword or the simple assigning of a property. @Fabio Marcolini, I understand that I'm using the word event to describe what is happening. What I'm trying to answer is that if using the event structure is preferred to simply executing a delegate property. Here are the properties that I use to define the event actions:               public Action<WorkflowInstallerCompletedEventArgs> InstallCompleted;          public Action<System.Activities.Activity, WorkflowInstallerActivityCompletedEventArgs> ActivityCompleted;          public Action<System.Activities.Activity, WorkflowApplicationAbortedEventArgs> InstallAborted;          public Func<System.Activities.Activity, WorkflowApplicationUnhandledExceptionEventArgs, UnhandledExceptionAction> UnhandledExceptionDuringInstall;      The idea would be to invoke one of them in this manner:                 if (this.InstallCompleted != null)         this.InstallCompleted(new WorkflowInstallerCompletedEventArgs(logs));      Now until @svick's comment I would've said that you could only have one Action (or Func) assigned to each property. Example implementation:                 WorkflowInstaller installer = new WorkflowInstaller(activity, new TestVariablesCollection()) { ActivitiesRunSequentially = true };       installer.AddInstallActivity(activity2);            installer.InstallCompleted = (e) =>       {         Log[] logs = e.Logs.ToArray();         string test = SerializationHelper<Log>.Serialize(logs.FirstOrDefault());         try         {           logOutputFromRun = SerializationHelper<Log[]>.Serialize(logs);         }         catch (Exception ex)         {              }         syncEvent.Set();       };       installer.InstallAborted = (a, e) =>       {         Assert.Fail("Unexpected abort during the install.");         syncEvent.Set();       };       installer.UnhandledExceptionDuringInstall = (a, e) =>       {         Assert.Fail("Unexpected exception during the install.");         syncEvent.Set();         return System.Activities.UnhandledExceptionAction.Terminate;       };            installer.StartInstallation();            syncEvent.WaitOne();      The answer to my question may not be a definitive this way or that way, but more of best practice or generally accepted approach. I'm really trying to expand my horizons when it comes to creating code that is acceptable to a wider audience.


title: Case insensitive keywords in a language

text: We're trying to write a custom scripting language. There has been a suggestion to make the language forgiving by providing **case insensitive** keywords. I personally do not like the idea, but there are few people in my team leaning towards it, saying it will make the end user happy! Examples of languages like FORTRAN, BASIC, SQL are given saying that these are case insensitive. Is this a good idea?


title: How to Properly Google for C

text: The problem with trying to use Google to find tutorials or answers for the C programming language is that C is not an expressive enough name to narrow down the searches. Even coupled with keywords like "Programming" and/or "Language" yields results mostly for C++, C#, and Objective-C. Is there a way to more effectively search for specific C resources using Google?


title: Methods as verbs: is the object the subject?

text: Is there some recommended practice regarding methods as verbs in OOP? Should the object work syntactically as subject or as object/complement? Should `object.doSomething()` be normally understood as "the object iself does something" (subject) or "the caller does something with the object"? I suspect that the first alternative is more right, and it sounds more natural with such a general verb... But consider for example "OutputStream.write(byte[])", which... > writes b.length bytes from the specified byte array to this output stream. Here it's not the object who is the subject of the action, it's the caller. The Writer (rather confusingly) does not really "write", its the caller is who "writes" bytes _to the Writer_. Should this be considered incorrect?


title: What skills to add for an older CS grad living in rural area?

text: The answers to this question might be different than the generic, "I graduated. Duh, now what should I do?" Living in an area with a low population presents limited opportunities compared to those in more urban or suburban communities. On the other hand...maybe the answers will be largely the same. I'm asking you folks who might be looking at this from a perspective of more years on the inside for your wisdom. I have just finished a CS degree. I am about 40 (does it matter much?). I left a successful, professional career in the laboratory robotics industry because it required me to either move to a big city or continue to travel extensively. In a few years we could potentially move somewhere else or I could start travelling again but I need to start working now. I need to make myself as employable as possible. There are few jobs available in my area for computer professionals. Of those few, the majority seem to be IT related more than software development related -- SharePoint, ERP, network security, web services, etc.. Might I be well served by trying to pick up some IT knowledge? Or should I continue to work on my software development chops? I have my own project now that I am proud of and excited about and could happily continue to extend it. It is a good vehicle for learning new stuff until (and hopefully after) I find employment. I'm hoping to get some others involved in it as well. Or I could start a new project that would be a vehicle for learning something marketable -- from .net to being able to support all that legacy COBOL there seems like a lot of stuff out there. Thanks for whatever insight anyone shares.


title: Going back to ASP.Net Webforms from ASP.Net MVC. Recommend patterns/architectures?

text: To many of you this will sound like a ridiculous question, but I am asking because **I have little to no experience with ASP.Net Webforms** \- I went straight to ASP.Net MVC. I am now working on a project where we are limited to .Net 2.0 and Visual Studio 2005. I liked the clean separation of concerns when working with ASP.Net MVC, and am looking for something to make webforms less unbearable. Are there any recommended patterns or practices for people who prefer asp.net MVC, but are stuck on .net 2.0 and visual studio 2005?


title: Does late have any meaning in Agile methodologies?

text: This came out of some of the answers and comments on another question (this one). I've worked primarily with waterfall projects and while I've worked on ad-hoc projects that have taken on agile behaviours and have read a fair bit about agile, I'd say I've never worked on a "proper" agile project. My question is does the concept of "late" have any meaning in agile, if so then what? My reasoning is that with agile you have no upfront plan and you have no detailed requirements at the outset. You may have a high level goal in mind and a notional date attached to it but both may change (potentially massively) and neither are certain. So if you don't know exactly what you're going to deliver basically until you deliver it and the user accepts it, and if you don't have a schedule beyond the next sprint, how could you ever be late in any way that actually has meaning? (Obviously I understand that a sprint might overrun but I'm talking about beyond that.) **Edit** : Just to be clear I'm (personally) happy with the assumption that on time waterfall projects (even relatively large ones) are possible based on the fact I've seen them and been involved in them - they're not easy or common even but they are possible. This isn't about knocking agile, it's about me understanding it. I've always seen the benefit of agile as nothing to do with deadlines or budgets (or rather only indirectly), it's to do with scope - agile delivers closer to what is really important rather than what the project team think is important before they've seen anything.


title: Algorithms: Find the best table to play (standing gambler problem)

text: _**Preface_** This is not code golf. I'm looking at an interesting problem and hoping to solicit comments and suggestions from my peers. This question is not about card counting (exclusively), rather, it is about determining the best table to engage based on observation. Assume if you will some kind of brain implant that makes worst case time / space complexity (on any given architecture) portable to the human mind. Yes, this is quite subjective. Assume a French deck without the use of wild cards. _**Background_** I recently visited a casino and saw more bystanders than players per table, and wondered what selection process turned bystanders into betting players, given that most bystanders had funds to play (chips in hand). _**Scenario_** You enter a casino. You see n tables playing a variant of Blackjack, with y of them playing Pontoon. Each table plays with an indeterminate amount of card decks, in an effort to obfuscate the house advantage. Each table has a varying minimum bet. You have Z currency on your person. You want to find the table where:   * The least amount of card decks are in use   * The minimum bet is higher than a table using more decks, but you want to maximize the amount of games you can play with Z.   * Net losses, per player are lowest (I realize that this is, in most answers, considered to be incidental noise, but it could illustrate a broken shuffler) _**Problem_** You can magically observe every table. You have X rounds to sample, in order to base your decision. For this purpose, every player takes no more than 30 seconds to play. What algorithm(s) would you use to solve this problem, and what is their worst case complexity? Do you:   * Play Pontoon or Blackjack ?   * What table do you select ?   * How many rounds do you need to observe (what is the value of X), given that the casino can use no more than 8 decks of cards for either game? Each table has between 2 and 6 players.   * How long did you stand around while finding a table? I'm calling this the " **standing gambler problem** " for lack of a better term. Please feel free to refine it. _**Additional_** Where would this be useful if not in a casino? _**Final_** I'm not looking for a magic gambling bullet. I just noticed a problem which became a bone that my brain simply won't stop chewing. I'm especially interested in applications way beyond visiting a casino.


title: Achieving forward compatibility with C++11

text: I work on a large software application that must run on several platforms. Some of these platforms support some features of C++11 (e.g. MSVS 2010) and some don't support any (e.g. GCC 4.3.x). I expect this situation to continue for for several years (my best guess: 3-5 years). Given that, I would like set up a compatibility interface such that (to whatever degree possible) people can write C++11 code that will still compile with older compilers with a minimum of maintenance. Overall, the goal is to minimize #ifdef's as much as reasonably possible while still enabling basic C++11 syntax/features on the platforms that support them, and provide emulation on the platforms that don't. Let's start with std::move(). The most obvious way to achieve compatibility would be to put something like this in a common header file:               #if !defined(HAS_STD_MOVE)     namespace std { // C++11 emulation       template <typename T> inline T& move(T& v) { return v; }       template <typename T> inline const T& move(const T& v) { return v; }     }     #endif // !defined(HAS_STD_MOVE)      This allows people to write things like               std::vector<Thing> x = std::move(y);      ... with impunity. It does what they want in C++11 and it does the best it can in C++03. When we finally drop the last of the C++03 compilers, this code can remain as is. However, according to the standard, it is illegal to inject new symbols into the `std` namespace. That's the theory. My question is: _practically speaking_ is there any harm in doing this as a way of achieving forward compatibility?


title: Is there a better way to model a many-to-many relationship on the same table with Entity Framework?

text: # The context We're building a web application using Entity Framework 5.0. One of the requirements is that it should be possible for the administrators to link related products so that when someone browses to a product we can render a list " _You might also like these products:_ ". Since a product can be linked to many products we need a many-to-many relationship for this. The table in the database could look something like this:                _________________________     | LinkedProducts          |     |-------------------------|     | ProductId1 | ProductId2 |     |------------|------------|     |     1      |     2      |     |------------|------------|     |     1      |     3      |     |------------|------------|     |     2      |     4      |     |------------|------------|      An additional requirement is that the linking should be bidirectional. This means that with the sample data from the table above, when you browse to product 2, you should get product 1 and 4 in the list. So for a given `ProductId`, you should be able to get its linked products from column `ProductId1` and `ProductId2`. # What I've come up with The product entity:               public class Product     {         public int ProductId { get; set; }         public string Name { get; set; }              public virtual ICollection<Product> References { get; set; }         public virtual ICollection<Product> ReferencedBy { get; set; }              public Product()         {             References = new List<Product>();             ReferencedBy = new List<Product>();         }     }      The product mapping:               public class ProductMapping : EntityTypeConfiguration<Product>     {         public ProductMapping()         {             HasKey(t => t.ProductId);                  Property(t => t.Name).IsRequired().HasMaxLength(150);                  ToTable("Products");             Property(t => t.ProductId).HasColumnName("ProductId");             Property(t => t.Name).HasColumnName("Name");                  HasMany(x => x.References).WithMany(x => x.ReferencedBy).Map(map =>                 {                     map.ToTable("LinkedProducts");                     map.MapLeftKey("ProductId1");                     map.MapRightKey("ProductId2");                 });         }     }      This all works. To display the list of linked products for a certain product, I can just get the union of `References` and `ReferencedBy`:               var product = db.Find(2);     var linkedProducts = product.References.Union(product.ReferencedBy);      # The problem As I said, this works, but I don't really like it and I was wondering if there is a better way to deal with a situation like this when working with Entity Framework. # The solution I liked Ryathal's suggestion to add two records to the database when linking products. So, when linking product 1 to product 2, I now insert two records: `{ 1, 2 }` and `{ 2, 1 }`. This also allows me to remove the `ReferencedBy` collection in the `Product` class so that only one collections remains: `References`. To link to products:               product1.References.Add(product2);     product2.References.Add(product1);      To remove the link between products:               product1.References.Remove(product2);     product2.References.Remove(product1);      Here is my new `Product` class with the mapping:               public class Product     {         public int ProductId { get; set; }         public string Name { get; set; }              public virtual ICollection<Product> References { get; set; }              public Product()         {             References = new List<Product>();         }     }      The product mapping:               public class ProductMapping : EntityTypeConfiguration<Product>     {         public ProductMapping()         {             HasKey(t => t.ProductId);                  Property(t => t.Name).IsRequired().HasMaxLength(150);                  ToTable("Products");             Property(t => t.ProductId).HasColumnName("ProductId");             Property(t => t.Name).HasColumnName("Name");                  HasMany(x => x.References).WithMany().Map(map =>                 {                     map.ToTable("LinkedProducts");                     map.MapLeftKey("ProductId1");                     map.MapRightKey("ProductId2");                 });         }     }


title: Why doesn't Java 8 include immutable collections?

text: The Java team has done a ton of great work removing barriers to functional programming in Java 8. In particular, the changes to the java.util Collections do a great job of chaining transformations into very fast streamed operations. Considering how good a job they have done adding first class functions and functional methods on collections, why have they completely failed to provide immutable collections or even immutable collection interfaces? Without changing any existing code, the Java team could at any time add immutable interfaces that are the same as the mutable ones, minus the "set" methods and make the existing interfaces extend from them, like this:                                    Iterable (already immutable)                              |                     ImmutableCollection             _______/    /          \   \___________            /           /            \              \      Collection  ImmutableList  ImmutableSet  ImmutableMap  ...         \  \  \_________|______________|__________   |          \  \___________|____________  |          \  |           \___________  |            \ |           \ |                       List            Set           Map ...      Sure, operations like List.add() and Map.put() currently return a boolean or previous value for the given key to indicate whether the operation succeeded or failed. Immutable collections would have to treat such methods as factories and return a new collection containing the added element - which is incompatible with the current signature. But that could be worked-around by using a different method name like ImmutableList.append() or .addAt() and ImmutableMap.putEntry(). The resulting verbosity would be more than outweighed by the benefits of working with immutable collections, and the type system would prevent errors of calling the wrong method. Over time, the old methods could be deprecated. Wins of immutable collections:   * Simplicity - reasoning about code is simpler when the underlying data does not change   * Documentation - if a method takes an immutable collection interface, you know it isn't going to modify that collection   * Concurrency - immutable collections can be shared safely across threads As someone who has tasted languages which assume immutability, it is very hard to go back to the Wild West of rampant mutation. Clojure's collections (sequence abstraction) already have everything that Java 8 collections provide, plus immutability (though maybe using extra memory and time due to synchronized linked-lists instead of streams). Scala has both mutable and immutable collections with a full set of operations, and though those operations are eager, calling .iterator gives a lazy view (and there are other ways of lazily evaluating them). I don't see how Java can continue to compete without immutable collections. Can someone point me to the history or discussion about this? Surely it's public somewhere.


title: UDP order of packets with direct connection

text: If i have two systems (A and B) running on LAN(INTRANET) which are directly connected. There are no routers in the middle. In this case, if system A sends a few UDP packets every few milliseconds to system B: Is it possible that system B receives the packets in a different order? Please note that I'm not asking whether to use TCP or UDP. I'm interested in whether the above scenario will have packets out of order - I'm aware that UDP packets are not guaranteed to arrive in order.


Lately I started studying about different interesting concepts that exist in languages other than Java. Since the only language I've ever programmed with is Java, a lot of these concepts are very new to me. So this question may be very naive :) . I learned recently about first class functions and function pointers. Why are there no function pointers in Java? Or at least some variation of them, like delegates in C#? Maybe it's just the excitement of learning about this concept, but it seems to me like it could be a powerful feature in the language.


title: How to store Status for Reservation table

text: I have a reservation table (a user fills out a form to request a reservation). It has two parts that need to be confirmed. isReservationAccepted (decline,accept,waiting) and hasReservationBeenSent (sent, declined, waiting) Not sure how to structure my table, thinking about making a lookup table for each column, or maybe just creating them as int, and having 1 = accepted/sent, 2 = declined, 3 = waiting. not sure if there is a better way (probably)


title: Sharing code in LGPL and proprietary software

text: I'm working on a piece of software that'll be released as a dll under LGPL. The software interfaces with hardware from a small company that has provided me with the needed libraries and some code to use them correctly (not only headers but its all in a separate file). As far as i know, the same code is used in their proprietary software that they don't intend to open source but they'd be fine releasing the piece of code they've given me. Now here's the question: What license could be used on the code I got from the company? I guess using GPL or LGPL would make them violate GPL when using the same code in their other software. Is MIT a good idea? Is it ok to just include a file with MIT license on it in my otherwise LGPL:ed project? Since I'm not the copyright holder, I'd have to ask the company to apply the license obviously but that shouldn't be a problem. Thanks /Martin


title: Infinite Bitmap

text: I'd like to build a bitmap during runtime. The bitmap should be scalable on all sides and pixel access should be quiet efficient. ![Some illustration](http://img546.imageshack.us/img546/4995/maptm.jpg) Between and after the commands shown in the picture, Map.setPixel() and Map.getPixel() should set/return data saved in the bitmap. I don't expect an implementation just a concept how to allocate memory in such a way that the setPixel()/getPixel is as fast as possible.


title: How to record/store edits?

text: In many programs and web apps (stack exchange included) the program is able to backtrack what edits where made to the piece. My issue is similar: I want to be able to store a "timeline" of edits, where the user can go back and see what they typed at a specific time/when the typed certain words. What's the standard way to do this? Also, in things like google docs and other programs, they automatically "group" actions together (Like if I delete something by hitting back space 5 times, it knows I was deleting one word), any ideas on how to do that to?


title: Modified Strategy Design Pattern

text: I've started looking into Design Patterns recently, and one thing I'm coding would suit the Strategy pattern perfectly, except for one small difference. Essentially, some (but not all) of my algorithms, need an extra parameter or two passed to them. So I'll either need to   * pass them an extra parameter when I invoke their calculate method  or   * store them as variables inside the ConcreteAlgorithm class, and be able to update them before I call the algorithm. Is there a design pattern for this need / How could I implement this while sticking to the Strategy Pattern? I've considered passing the client object to all the algorithms, and storing the variables in there, then using that only when the particular algorithm needs it. However, I think this is both unwieldy, and defeats the point of the strategy pattern. Just to be clear I'm implementing in Java, and so don't have the luxury of optional parameters (which would solve this nicely).


title: Computer Science vs. Game Programming

text: I'm interested in going to University in the hope of taking programming to a professional level, in particular I would like to go into Game Programming. Would I benefit more from going to a University and getting a degree in a "Game Programming" type course, or would a more general degree in Computer Sciene be better?


title: How do you store "fuzzy dates" into a database?

text: This is a problem I've run into a few times. Imagine you have a record that you want to store into a database table. This table has a DateTime column called "date_created". This one particular record was created a long time ago, and you're not really sure about the exact date, but you know the year and month. Other records you know just the year. Other records you know the day, month and year. You can't use a DateTime field, because "May 1978" isn't a valid date. If you split it up into multiple columns, you lose the ability to query. Has anyone else run into this, if so how did you handle it? **Edit:** To clarify the system I'm building, it is a system that tracks archives. Some content was produced a long time ago, and all that we know is "May 1978". I could store it as May 1 1978, but only with some way to denote that this date is only accurate to the month. That way some years later when I'm retrieving that archive, I'm not confused when the dates don't match up. For my purposes, it is important to differentiate "unknown day in May 1978" with "May 1st, 1978". Also, I would not want to store the unknowns as 0, like "May 0, 1978" because most database systems will reject that as an invalid date value.


title: Using MVC strictly with DAAB?

text: I am the only one at my company that is familiar with MVC and they are getting more pressure to modernize and switch to MVC for future projects, so I was tasked to create a template to use as a base for any training or as a base for new projects. This is perfectly fine and I'm glad to do it. However, one absolute requirement is that I use EL Data Access Block. Doesn't this kinda defeat the purpose of MVC and using an ORM for simpler data code? I have tried looking everywhere online for any standard practices when using MVC with DAAB but I cannot find a single good article or tutorial or code anywhere, which leads me to believe I should not do it this way, but i have to.. So, on that note, is it possible for me to use EL Data Access for the Model and set it up so that it can be strongly typed and get it to basically act kinda like EF? I was thinking that I could just create a t4 template or something to help generate the models based off of the DB tables and add as much of the CRUD operations as I could. No clue if this will be a good idea though.


title: Can all the recursive functions be coded with iterations?

text: What are the advantages of recursion? Some programming languages can optimize tail recursion, but, still in general terms, recursion consume more resources than regular loops. Is it possible to have an iterative version of some recursive function?


title: Why would you opt to fully qualify a package instead of importing it?

text: In java, to print the date we could do either of the following: **Fully qualified**               public class MyMain {              /**          * @param args          */         public static void main(String[] args) {             // TODO Auto-generated method stub                  System.out.println(new java.util.Date());              }          }      **Using an import**               import java.util.*;          public class MyMain {              /**          * @param args          */         public static void main(String[] args) {             // TODO Auto-generated method stub                  System.out.println(new Date());              }          }      What are the advantages and disadvantages to for each way? For me, using an import seems tidier, as you can see at the top of your class, just what packages are being used.


title: Should main method be only consists of object creations and method calls?

text: A friend of mine told me that, the best practice is class containing `main` method should be named `Main` and only contains `main` method. Also `main` method should only parse inputs, create other objects and call other methods. The `Main` class and `main` method shouldn't do anything else. Basically what he is saying that class containing `main` method should be like:               public class Main     {         public static void main(String[] args)         {             //parse inputs             //create other objects             //call methods         }     }      Is it the best practice?


title: Single line comments for multiple indented lines of code

text: After many years of coding, trying various programming styles, weeding out unreadable or impractical stuff, I still can't figure out one thing: what is the best way to single-line-comment multiple lines of indented code. 1.                   setup_checkpoint();     //    if (object->looks_suspicious())     //        guard->full_body_scan(object);      2.                   setup_checkpoint();         // if (object->looks_suspicious())         //     guard->full_body_scan(object);      3.                   setup_checkpoint();         // if (object->looks_suspicious())             // guard->full_body_scan(object);      Please, don't suggest multiline commenting, because sometimes you want to leave that possibility for bigger blocks, which may include smaller pieces of comments.