title: Is this pattern bad?

text: I notice that when I code I often use a pattern that calls a class method and that method will call a number of private functions in the same class to do the work. The private functions do one thing only. The code looks like this:               public void callThisMethod(MyObject myObject) {         methodA(myObject);         methodB(myObject);  // was mehtodB before     }          private void methodA(MyObject myObject) {         //do something     }           private void methodB(MyObject myObject) {         //do something     }      Sometimes there are 5 or more private methods, in the past I have moved some of the private methods into another class, but there are occasions when doing so would be creating needless complexity. The main reason I don't like this pattern is that is not very testable, I would like to be able to test all of the methods individually, sometimes I will make all of the methods public so can I can write tests for them. Is there a better design I can use?


title: How to handle complex conditions?

text: We are working on project where we have to manage these conditions. i.e.: A User can save an order under these conditions:   * User has permission "SaveOrder"   * Order is in state "shipped"   * Online Shop is opened. This condition is for example - I would like to point out, that we have three conditions from different areas(role and permissions, inner state of object order and state of another domain object). In a previous project we used this code:               public static bool CanSaveOrder(Order order)     {        return        CurrentPrincipal.HasPermission(Permissions.SaveOrder) &&        order.State == States.Shipped &&        OnlineShop.IsOpen();     }      But I feel that there can be a more elegant/dynamic solution. I have read something about a "business role engine". Is it a right way to manage this condition?


title: calling methods if previous call success

text: I my c# program I have to perform 5 steps(tasks) sequentially. basically these five should execute one after the other only the previous task performed is success. Currently I have done it in following style. But this is not very good code style to follow.               var isSuccess=false;     isSuccess=a.method1();          if(isSuccess)         isSuccess=a.method2();          if(isSuccess)         isSuccess=a.method3();          if(isSuccess)         isSuccess=a.method4();          if(isSuccess)         isSuccess=a.method5();      How can I re factor this code. What is the best way I can follow?


title: One-line functions that are called only once

text: Consider a parameterless ( _edit:_ not necessarily) function that performs a single line of code, and is called only once in the program (though it is not impossible that it'll be needed again in the future). It could perform a query, check some values, do something involving regex... anything obscure or "hacky". The rationale behind this would be to avoid hardly-readable evaluations:               if (getCondition()) {         // do stuff     }      where `getCondition()` is the one-line function. My question is simply: is this a good practice? It seems alright to me but I don't know about the long term...


title: Which is preferred coding style to validate and return from a method

text: Which of the below is a preferred coding style (in c# .net)               public void DoWork(Employee employee)     {       if(employee == null)         return;            if(!string.IsNullOrEmpty(employee.Name))        return;            // Do Work          }      **or**               public void DoWork(Employee employee)     {       if(employee != null && !string.IsNullOrEmpty(employee.Name))        {         // Do Work        }     }


title: Is using subprocedures to logically separate my code a bad idea for structured programming?

text: Most of my programming experience is in OOP where I have fully embraced the concepts thereof including encapsulation. Now I'm back to structured programming where I have a tendency to logicaly seperate my code using subprocedures. For example, if I have a large switch case (30 cases or more), I'll put that in it's own procedure so the main method looks a little "neater". Generally, subprocedures are used to help keep things _DRY_ , but in some instances these logical seperations I create usually amount to being used only once. Some of my code was being reviewed, and it was mentioned that this is a bad idea. His backing to this claim is that it muddies the water and "unecessarily hides" code. Instead, he insists that a subprocedure MUST be used more than once to merit making a subprocedure out of a section of code. While this idea of "hiding code" is a common place in OOP, he does admit to having little to no understanding of OOP concepts and has only ever worked with structured programming. **Is there any backing to his claim or is this merely programming dogma?**


title: Always pull out common cases and branch separately?

text: We had a disagreement in a code review. What I had written:               if(unimportantThing().isGood && previouslyCalculatedIndex != -1)     {         //Stuff     }     if(otherThing().isBad && previouslyCalculatedIndex != -1)     {         //Otherstuff     }     if(yetAnotherThing().isBad)     {         //Stuffystuff     }      The reviewer called that ugly code. This is what he expected:               if( previouslyCalculatedIndex != -1)     {         if(unimportantThing().isGood)         {             //Stuff         }         if(otherThing().isBad)         {             //Otherstuff         }     }     if(yetAnotherThing().isBad)     {         //Stuffystuff     }      I'd say it's a pretty trivial difference and that the complexity of adding another layer of branching is equivalently bad as one or two logical-ands. But just to check myself, is this really a grievous coding sin that you would take a firm stance over? Do you _always_ pull out the common cases in your if statements and branch on them separately, or do you add logical-ands to a couple of if statements?


title: What does (Lua) game scripting mean?

text: I've read that Lua is often used for embedded scripting and in particular game for scripting. I find it hard to picture how it is used exactly. Can you describe why and for which features and for which audience it is used? This questions isn't specifically addressing Lua, but rather any embedded scripting that serves a _purpose similar to Lua_ scripting. Is it used for end-users to make custom adjustments? Is it used for game developers to speed up creation of game logic (levels, AI, ...)? Is it used to script game framework code since scripting can be faster? Basically I'm wondering how deep between plain configuration and framework logic such scripting usage goes. And how much scripting is done. A few configuration lines or a considerable amount?


title: Reconstruct a file from a TCP stream

text: I have a client and a server and a third box which sees all packets from the server to the client (but not the other way around). Now when the client requests a file from the server (over HTTP), the third box sees the response. I am trying to reconstruct the file there. I am using `libpcap` to capture TCP datagrams and trying to reconstruct the file there. Here is what I did   1. Listen for packets on an interface   2. Group all packets which have the same ACK number   3. Sort the group based on SEQ number   4. Extract data from each packet and combine them and write to the disk The problem is, the file thus generated is not exactly the same as the original file. Their sizes are the same each, but when I open the images in an image viewer, they look different. time Does everything sound correct here? **EDIT**   Hexdump of first 512 bytes of the recovered file               0000000 009a 0095 0090 008b 0086 0081 007c 0077     0000010 0072 006d 0068 0063 005e 0059 0054 004f     0000020 004a 0045 0040 003b 0037 0032 002d 0028     0000030 0023 001e 0019 0014 000f 000a 0005 0000     0000040 0400 0000 0000 0000 7276 6375 5420 4352     0000050 0000 0000 6720 7369 0000 0000 0000 0000     0000060 0000 0000 0002 0000 028f 0000 0000 0000     0000070 0001 0000 0000 0000 6173 6d65 1fe7 0057     0000080 0000 0050 0956 004c 0000 0000 5a20 5859     0000090 0001 0000 5c9e 0003 130b 0004 edcc 0003     00000a0 cf14 0010 5f2e 0014 a4fe 0013 0000 0000     00000b0 6577 7669 0000 0000 0000 0000 0000 0000     00000c0 0000 0000 0000 0000 0000 0000 2e31 2d32     00000d0 3636 3139 4336 4945 6e20 2069 6f6e 7469     00000e0 6469 6f6e 2043 6e67 7769 6965 2056 6365     00000f0 656e 6572 6566 2c52 0000 0000 0000 0000     0000100 0000 3100 322e 362d 3936 3631 4543 2049     0000110 696e 6e20 696f 6974 6e64 436f 6720 696e     0000120 6577 5669 6520 6e63 7265 6665 5265 002c     0000130 0000 0000 0000 7363 6465 0000 0000 0000     0000140 0000 0000 0000 0000 0000 0000 0000 0000     0000150 4742 7352 2d20 6520 6163 7370 7220 6f75     0000160 6f6c 2063 4742 2052 6c74 6175 6566 2044     0000170 2e31 2d32 3636 3139 2036 4543 2e49 0000     0000180 0000 0000 0000 0000 4200 5247 2073 202d     0000190 6365 7061 2073 7572 6c6f 636f 4220 5247     00001a0 7420 756c 6661 4465 3120 322e 362d 3936     00001b0 3631 4320 4945 002e 0000 0000 0000 7363     00001c0 6465 0000 0000 0000 0000 0000 0000 0000     00001d0 0000 0000 0000 0000 0000 0000 0000 0000     *     00001f0 6368 632e 6965 772e 7777 2f2f 703a 7474     0000200      Hexdump of first 512 bytes of the original file:               0000000 d8ff e0ff 1000 464a 4649 0100 0101 2c01     0000010 2c01 0000 e2ff 6d1c 4349 5f43 5250 464f     0000020 4c49 0045 0101 0000 5d1c 694c 6f6e 1002     0000030 0000 6e6d 7274 4752 2042 5958 205a ce07     0000040 0200 0900 0600 3100 0000 6361 7073 534d     0000050 5446 0000 0000 4549 2043 5273 4247 0000     0000060 0000 0000 0000 0000 0000 0000 d6f6 0100     0000070 0000 0000 2dd3 5048 2020 0000 0000 0000     0000080 0000 0000 0000 0000 0000 0000 0000 0000     *     00000a0 0000 0000 0000 0000 1100 7063 7472 0000     00000b0 5001 0000 3300 6564 6373 0000 8301 0000     00000c0 6c00 7477 7470 0000 ef01 0000 1400 6b62     00000d0 7470 0000 0302 0000 1400 5872 5a59 0000     00000e0 1702 0000 1400 5867 5a59 0000 2b02 0000     00000f0 1400 5862 5a59 0000 3f02 0000 1400 6d64     0000100 646e 0000 5302 0000 7000 6d64 6464 0000     0000110 c302 0000 8800 7576 6465 0000 4b03 0000     0000120 8600 6976 7765 0000 d103 0000 2400 756c     0000130 696d 0000 f503 0000 1400 656d 7361 0000     0000140 0904 0000 2400 6574 6863 0000 2d04 0000     0000150 0c00 5472 4352 0000 3904 0000 0c08 5467     0000160 4352 0000 450c 0000 0c08 5462 4352 0000     0000170 5114 0000 0c08 6574 7478 0000 0000 6f43     0000180 7970 6972 6867 2074 6328 2029 3931 3839     0000190 4820 7765 656c 7474 502d 6361 616b 6472     00001a0 4320 6d6f 6170 796e 6400 7365 0063 0000     00001b0 0000 0000 7312 4752 2042 4549 3643 3931     00001c0 3636 322d 312e 0000 0000 0000 0000 0000     00001d0 1200 5273 4247 4920 4345 3136 3639 2d36     00001e0 2e32 0031 0000 0000 0000 0000 0000 0000     00001f0 0000 0000 0000 0000 0000 0000 0000 0000     0000200      Some more details:   1. I am using C++   2. The packet data is being stored as `std::vector<char>`   3. I did change the byte order while reading the ack number and seq number from the packet using `ntohl`   4. I am not sure if I need to change the byte order for the data as well. I tried to reverse the data from each packet before combining them, even that did not work. Is there something I am missing? **EDIT**   Original file:   ![Original](http://i.stack.imgur.com/rlLU4.jpg) Recovered file:   ![Recovered](http://i.stack.imgur.com/8blIG.jpg)


title: Physical effects of long term keyboard use- what does the science say and what factors affect it?

text: This question asks about the ergonomics of a particular keyboard for long programming hours, what I would like to know is about the ergonomics of using a keyboard in general. What are the most significant risks associated with it and how can they best be mitigated? Do the "ergonomic" keyboard designs make a difference and if so which design is most effective? If not do other factors such as wrist-rests, regular exercise or having a suitable height of chair or desk make a difference? Do you have any direct experience of problems deriving from keyboard use and if so how did you resolve them? Is there any good science on this and if so what does it indicate? Edited to add: Wikipedia suggests that there are no proven advantages to "ergonomic" keyboards, but their citation seems pretty old- is that still the current state of play?


title: How to setup the c++ rule of three in a virtual base class

text: I am trying to create a pure virtual base class (or simulated pure virtual) my goal:   1. User can't create instances of BaseClass.   2. Derived classes have to implement default constructor, copy constructor, copy assignment operator and destructor. My attempt:               class Base     {     public:         virtual ~Base() {};         /* some pure virtual functions */     private:         Base() = default;         Base(const Base& base) = default;         Base& operator=(const Base& base) = default;     }      This gives some errors complaining that (for one) the copy constructor is private. But i don't want this mimicked constructor to be called.   Can anyone give me the correct construction to do this if this is at all possible?


title: Which Internet places are popular for commercial Java product announcements?

text: For Java libraries (which I wrote in the past years) I found not so many places iin the Internet where developers could announce new releases. So I use paid advertising (banner campaigns) at the moment. Are there known and popular online forums or newsgroups which welcome advertising for products for the Java platform?


title: How to handle manipulation of data after a db record is written from outside my program

text: I have written a warehouse management web app. The application handles batch picking, warehouse routing, packing, and the final piece is handled by UPS worldship to "ship" the packages. Worldship will write a record to my postgres db after every shipment or void. I need a way to cleanly see that the record was written/deleted and then "do stuff". The easy answer is to have a program just monitor the database and when it sees a record written to do its thing but something is nagging at me that there is probably a better way to go about this that doesn't have a program polling the table and comparing it to what was there last. EDIT: How i was going to approach this... The table is setup with a status field. My program would on intervals read the table for any records that have a null status, if records are found "do stuff" then mark the status as complete. TIA


title: randomized management?

text: I saw an article a few months ago that explain a company's practice of randomly choosing management via lottery. The employee would manage his peers for some fixed amount of time until the next management raffle. The writer went on to explain in detail why this worked better than the traditional expert-manager model. I'm completely unable to remember where I read this, and unable to get useful results from Google. Does anyone recall seeing this? I'd really like to find it again. \--buck


title: Shouldn't we count characters of code and comments instead of lines of code and comments?

text: Counting lines of code and comments is sometimes bogus, since most of what we write may be written in one or more lines, depending column count limitations, screen size, style and so forth. Since the commonly used languages (say C, C++, C# and Java) are free-form, wouldn't it be more clever to count characters instead? **Edit:** I'm not considering LOC-oriented programming where coders try to artificially match requirements by adding irrelevant comments or using multiple lines where less would be enough (or the opposite). I'm interested in better metrics that would be independent of coding style, to be used by honest programmers.


title: What makes for a good JIRA workflow with a software development team?

text: I am migrating my team from a snarl of poorly managed excel documents, individual checklists, and personal emails to manage our application issues and development tasks to a new JIRA project. My team and I are new to JIRA (and issue tracking software in general). My team is skeptical of the transition at best, so I am also trying not to scare them off by introducing something overly complex at the start. I understand one of JIRA's strengths to be the customized workflows that can be created for a project. I've looked over the JIRA documentation and a number of tutorials, and am comfortable with the how in creating workflows, but I need some contextual What to go along with it.   * _What makes a particular workflow work well?_   * _What does a poorly designed workflow look like?_   * _What are the benefits/drawbacks of a strict workflow with very specific states and transitions to a looser workflow, with fewer, broader defined states and transitions_


title: Are there any specific workflows or design patterns that are commonly used to create large functional programming applications?

text: I have been exploring Clojure for a while now, although I haven't used it on any nontrivial projects. Basically, I have just been getting comfortable with the syntax and some of the idioms. Coming from an OOP background, with Clojure being the first functional language that I have looked very much into, I'm naturally not as comfortable with the functional way of doing things. That said, are there any specific workflows or design patterns that are common with creating large functional applications? I'd really like to start using functional programming "for real", but I'm afraid that with my current lack of expertise, it would result in an epic fail. The "Gang of Four" is such a standard for OO programmers, but is there anything similar that is more directed at the functional paradigm? Most of the resources that I have found have great programming nuggets, but they don't step back to give a broader, more architectural look.


title: Javascript behavior depends only on browser or browser + OS?

text: Generally for a javascript application, compatibility is mentioned in terms of browser types and browser versions it supports. Frameworks/Libraries like ExtJs also mention about the browser versions they are compatible with. **Does this mean that if my javascript application can run on Google Chrome 10+ version, then any operating system where Google Chrome 10+ can be installed will be able to run my javascript application without any glitches?** Or does type of operating system also have an effect on Javascript execution? The reason behind asking this is to evaluate the scope of testing of javascript applications before making any commitment to the end user. Thanks in advance for any guidance provided.


title: How do most sync programs monitor file changes?

text: Do sync programs like Dropbox typically track file changes by doing byte by byte comparisons, or using hashes, or using `diff` / keeping local commit logs like version control, or what?


title: Idea of the binary search main theorem

text: This link really provided some insights into the idea that binary search implications into the optimization problems by giving the main theorem. I am not really confident that I get the idea of the main theorem suggested there. Are there any easy explanations, for the ideas, expressed in that tutorial?


title: Pair programming when driver and observer have different skill level and experience

text: I know pair programming is an agile software development technique in which two programmers work together at one workstation. One, the driver, writes code while the other, the observer, reviews each line of code as it is typed in. But I just wonder the strategy still work in the case. For example   * if they have a very different programming skill level.    * if one never experience in the problem domain while another have.   * Is it still OK if they have low programming skill level? Could you suggest the pair programming strategy in the case above?


title: Which design pattern would be best for this case?

text: I have a class, called PolicyProvider, at present with the following (abridged) interface:               public interface IPolicyProvider     {         List<Policy> GetRenewalPolicies(Client client, int financialYear);     }      The purpose is quite obvious - every year, the insurance renews for the client, and they will get a number of new policies. The thing is, the policies change year by year. Therefore, a concrete implementation of the class needs to be changed every year (or amended with lots of ugly little "if's" evaluating the financial year). I can see that over time this will become horrendous. In this case, what design pattern is most appropriate?


title: What do you say in a code review when the other person built an over complicated solution?

text: The other day I reviewed code someone on my team wrote. The solution wasn't fully functional and the design was way over complicated-- meaning stored unnecessary information, built unnecessary features, and basically the code had lots of unnecessary complexity like gold plating and it tried to solve problems that do not exist. In this situation I ask "why was it done this way?" The answer is the other person felt like doing it that way. Then I ask if any of these features were part of the project spec, or if they have any use to the end user, or if any of the extra data would be presented to the end user. The answer is no. So then I suggest that he delete all the unnecessary complexity. The answer I usually get is "well it's already done". My view is that it is not done, it's buggy, it doesn't do what the users want, and maintenance cost will be higher than if it were done in the simpler way I suggested. An equivalent scenario is:   Colleague spends 8 hours refactoring code by hand which could have been automatically done in Resharper in 10 seconds. Naturally I don't trust the refactoring by hand as it is of dubious quality and not fully tested.   Again the response I get is "well it's already done." What is an appropriate response to this attitude?


title: DDD - Domain Object calling a web service

text: Is it ok to call a webservice from a Domain object?. As I write the question I am thinking that you should never do that, as it is poor design, but the situation is the following: I have a domain object called Postman that works very closely with a Message object. This Message is provided by a web service. Without the Message, the Postman object could not do its business logic. I understand that this code doesn't smell good but, since the Postman depends on the Message, it seems logical to call the web service in order to get the Message. There is no other way to get the Message without the web service.


title: Can I use select2 in my website?

text: I am working on project that deals in customer support. This website actually sells products ( so it is commerical ), and provides customer support. So in this project/website I was about to use select2 . Select2 License: > This software is licensed under the Apache License, Version 2.0 (the "Apache > License") or the GNU General Public License version 2 (the "GPL License"). > You may choose either license to govern your use of this software only upon > the condition that you accept all of the terms of either the Apache License > or the GPL License. Can I use this in the website?   Ask me if any other info is also required.


title: What is the best way to construct your CSS documents?

text: Normally I start a project working on a site, I'd do the basic html skeleton and then start tweaking the styles using CSS. Slowly I'd just add one CSS rule after another with no "organized structure" or groupings in the CSS rules. And at the end of the project I look at the CSS document and the abomination I have created. Often spending quite some time trying to search for the spot in the document where I added a certain style. Is there some type of 'rule-of-thumb' that one can use in laying out and getting more organized in your CSS documents? And I'm not just talking about adding comments...


title: How do I make a cloud based web app accessible internally in the event of an internet outage?

text: I have a Java Web application backed by a database. Both are hosted in Amazon EC2. If the Internet is down, I need to allow internal users to be able to continue to work and somehow update the hosted service when the Internet is available again. Is this possible? How would I design such a solution.


title: Why is there usually a reference to Java when when people talk about C#?

text: I don't know much about C# but I've been programming in Java for a few months now. I had always heard what C and C++ were, but was a little curious about where C# came from. I'm a little confused about the C# language since even though it's one of the 'C' languages (C, C++, C#), on the other hand all of my professors seem to line it up against Java, and not the others. If anyone can clarify that would be great :)


title: BitBucket - what's the catch? (TANSTAAFL, right?)

text: The BitBucket capabilities, and pricing (up to 5 users for free) left me wondering what the catch was... there is no such thing as a free lunch, after all. What is BitBucket getting out of my unpaid participation, besides a handsome man to freely include in their promotional materials (per the TOS)?


title: How to hire a good C# developer if I don't know C#?

text: I'm a C++ developer. I know how Windows works on the native level, but I'm not a big expert in C# and .NET. Now I need a C# developer in my team (all my developers are C++). How can I hire a great C# developer if I don't know C# at good level? How to ask questions, how to test whether answers are great or are with silly mistakes?


title: Besides Waterfall, what are other plan-driven software development methodologies?

text: I just read Balancing Agility and Discipline. Poor title aside, it contrasted a plan-driven project team that was employing PSP/TSP and an agile team using Extreme Programming. When the authors provided an example of a plan-driven methodology, they used Personal Software Process/Team Software Process. Although, out-of-the-box, these are plan-driven methodologies, they are also designed to be used as process frameworks and ultimately only specify what types of things to do and not how to do them, whi ch makes them potentially useful even in an agile environment. It's possible to be agile and still adhere to the PSP principles, and I'm not familiar enough with the TSP to say for sure, but my understanding is that it is very similar. At one point in the book, they list a number of methodologies and rank them in terms of agility. Methods like Scrum, Lean, Crystal, and XP are at the top. The bottom (from most to least agile) consists of the Rational Unified Process, the Team Software Process, Feature-Driven Development, CMMI, Software CMM, the Personal Software Process, and Cleanroom. Watts Humphrey, in PSP: A Self-Improvement Process for Software Engineers, dedicates a chapter to process definition, and specifically modifying the Personal Software Process. The common theme is that processes are prescriptive (they say what to do) and not descriptive (how to do it). I would surmise that the TSP is very much the same way. CMMI has also been used in conjunction with agile methods, and the SEI has a book on it (which I have not yet read). Feature-Driven Development is often touted as an agile approach to project management, yet the authors choose to rank it as a less agile methodology. RUP is an iterative framework. Although I'm not incredibly familiar with it, the fact that it's a framework lends me to group it with SW-CMM, CMMI, and PSP/TSP in that it could be implemented either as an agile or as a plan-driven methodology. The only other example that the book provides that I agree with is Cleanroom Software Engineering. The key components of Cleanroom are the use of formal methods, statistical quality control, and statistically-sound testing. I don't see why these couldn't be used in an agile (iterative/incremental) method, with added the time and cost overhead. Just to clarify what I'm looking for, the family of agile methods includes specific implementations of an abstract idea in the form of Scrum and Extreme Programming. These realize the concepts of iterative and incremental development, responding to change, people (individuals and teams), frequent delivery of working software, collaborating with the customer, and so forth. They clearly specify roles, artifacts, meetings, timeboxes, and other practices and to "do Scrum" or "do Extreme Programming" means to take the package. Even so, they allow for tailorability and the creation of new processes (but then you aren't "doing Scrum" or "doing XP"). However, I haven't found the "do X" of plan-driven methodologies - most of the work appears to be toward frameworks that could be agile or plan-driven. So, my question: What are examples of more plan-driven software development methodologies? A number of the process frameworks (PSP/TSP, SW-CMM, CMMI, RUP) allow for plan-driven or agile development, as well, but none are descriptive. But are there any truly plan-driven methodologies, that are, for example, direct counterparts to Scrum and Extreme Programming?


title: How do you organize an ASP.NET MVC 3 application with potentially hundreds of views but with only a few entry points?

text: **Assumptions:**   * Minimalist ASP.NET MVC 3 application for sending emails where the view represents the contents of an email.   * Over 500+ email types. I would NOT like to have 500+ actions in my controller corresponding to each email type.   * Email types are stored in an enum named MailType, so we could have:      * MailType.ThankYouForYourPurchase, MailType.OrderShipped, etc.   * The view name is the same as the mailType name:      * MailType.OrderShipped would have a corresponding view: OrderShipped.cshtml   * Some views would directly use an Entity while others would use a ViewModel. So, given that I have 500+ email types, what is the best way/pattern to organize my application? Here is what I was thinking, **Controller:**                   public class MailController : Controller         {             public ActionResult ViewEmail(MailType mailType, int customerId)             {                 string viewName = mailType.ToString();                      var model = _mailRepository.GetViewModel(mailType, customerId);                      return View(viewName, model);             }                  public ActionResult SendEmail(MailType mailType, int customerId)             {                 ...             }         }      **MailRepository Class:**                   public class MailRepository         {             private readonly CustomerRepository _customerRepository;             private readonly OrderRepository _orderRepository;                  //pretend we're using dependency injection             public MailRepository()             {                 _customerRepository = new CustomerRepository();                 _orderRepository = new OrderRepository();             }                  public object GetViewModel(MailType mailType, int customerId)             {                 switch (mailType)                 {                     case MailType.OrderShipped:                         return OrderShipped(customerId);                     case MailType.ThankYouForYourPurchase:                         return ThankYouForYourPurchase(customerId);                 }                      return _customerRepository.Get(customerId);             }                  public Order OrderShipped(int customerId)             {                 //Possibly 30 lines to build up the model...                 return _orderRepository.GetByCustomerId(customerId);             }                  public Customer ThankYouForYourPurchase(int customerId)             {                 return _customerRepository.Get(customerId);             }         }      But then this would lead to my MailRepository class becoming extremely large unless I somehow broke it up...


title: Tool that can do semantic search in a body of C code

text: I'm looking for a tool that can do semantic search in a body of C code.   Example query: "give me all references to field y in struct x defined in file z.h". I would prefer an open source, command line driven tool. C++ support is an advantage. Is there such a tool other than cscope? cscope doesn't preserve the type of tags. In hostapd for example there are more than 900 references to the tag "ifname". However, I'm only interested in the ifname field of a specific struct. cscope can't filter tags according to type.


title: Should UTF-16 be considered harmful?

text: I'm going to ask what is probably quite a controversial question: "Should one of the most popular encodings, UTF-16, be considered harmful?" Why do I ask this question? How many programmers are aware of the fact that UTF-16 is actually a variable length encoding? By this I mean that there are code points that, represented as surrogate pairs, take more than one element. I know; lots of applications, frameworks and APIs use UTF-16, such as Java's String, C#'s String, Win32 APIs, Qt GUI libraries, the ICU Unicode library, etc. However, with all of that, there are lots of basic bugs in the processing of characters out of BMP (characters that should be encoded using two UTF-16 elements). For example, try to edit one of these characters:   * 𝄞 (U+1D11E) _MUSICAL SYMBOL G CLEF_   * 𝕥 (U+1D565) _MATHEMATICAL DOUBLE-STRUCK SMALL T_   * 𝟶 (U+1D7F6) _MATHEMATICAL MONOSPACE DIGIT ZERO_   * 𠂊 (U+2008A) _Han Character_ You may miss some, depending on what fonts you have installed. These characters are all outside of the BMP (Basic Multilingual Plane). If you cannot see these characters, you can also try looking at them in the Unicode Character reference. For example, try to create file names in Windows that include these characters; try to delete these characters with a "backspace" to see how they behave in different applications that use UTF-16. I did some tests and the results are quite bad:   * Opera has problem with editing them (delete required 2 presses on backspace)   * Notepad can't deal with them correctly (delete required 2 presses on backspace)   * File names editing in Window dialogs in broken (delete required 2 presses on backspace)   * All QT3 applications can't deal with them - show _two_ empty squares instead of one symbol.   * Python encodes such characters incorrectly when used directly `u'X'!=unicode('X','utf-16')` on some platforms when X in character outside of BMP.   * Python 2.5 unicodedata fails to get properties on such characters when python compiled with UTF-16 Unicode strings.   * StackOverflow seems to remove these characters from the text if edited directly in as Unicode characters (these characters are shown using HTML Unicode escapes).   * WinForms TextBox may generate invalid string when limited with MaxLength. It seems that such bugs are extremely easy to find in many applications that use UTF-16. So... Do you think that UTF-16 should be considered harmful?


title: Clarification of pseudo random number generator

text: I am asked to create a pseudo-random number generator using the following algorithm: > The generator will generate every integer from `1` to `N-1` exactly once > > The algorithm for `N=2^n` > >   * Initialize an integer `R` to be equal to `1` every time the tabling > routine is called and then on each successive call for a random number: >   * set `R=R*5` >   * mask out all but the low-order `n+2` bits of the product and place the > result in R >   * set `p=R/4` > What does the algorithm mean when it says mask out all but the low order `n+2` bits of the product?


title: What's better than outputdebugstring for windows debugging?

text: So, before I came to my current place of employment, the windows OutputDebugString function was completely unheard of, everyone was adding debug messages to string lists and saving them to file or doing showmessage popups (not very useful for debugging drawing issues). Now everybody (all 6 of us) is like "What can I say about this OutputDebugString?" and I'm like, "with much power comes much responsibility." I kind of feel as though I've passed a silent but deadly code smell to my colleagues. Ideally we wouldn't have bugs to debug right? Ideally we'd have over 0% code coverage, eh? So as far as petty debugging is concerned (not complete rewriting of a 3 million line Delphi behemoth) what's a better way to use debug running code than just adding OutputDebugString all over?


title: REST and redirecting the response

text: I'm developing a RESTful service. Here is a map of the current feature set:               POST /api/document/file.jpg    (creates the resource)     GET /api/document/file.jpg     (retrieves the resource)     DELETE /api/document/file.jpg  (removes the resource)      So far, it does everything you might expect. I have a particular use case where I need to set up the browser to send a POST request using the multipart/form-data encoding for the document upload but when it is completed I want to redirect them back to the form. I know how to do a redirect, but I'm not certain about how the client and server should negotiate this behavior. Two approaches I'm considering:   1. On the server check for the `multipart/form-data` encoding and, if present, redirect to the referrer when the request is complete.   2. Add a service URI of `/api/document/file.jpg/redirect` to redirect to the referrer when the request is complete. I looked into setting an X header (X-myapp-redirect) but you can't tell the browser which headers to use like this. I manage the code for both the client and the server side so I'm flexible on solutions here. Is there a best practice to follow here?


title: How far should an entity take care of its properties values by itself?

text: Let's consider the following example of a class, which is an entity that I'm using through Entity Framework.               - InvoiceHeader         - BilledAmount (property, decimal)         - PaidAmount (property, decimal)         - Balance (property, decimal)      I'm trying to find the best approach to keep Balance updated, based on the values of the two other properties (BilledAmount and PaidAmount). I'm torn between two practices here:   1. Updating the balance amount every time BilledAmount and PaidAmount are updated (through their setters)   2. Having a UpdateBalance() method that the callers would run on the object when appropriate. I am aware that I can just calculate the Balance in its getter. However, it isn't really possible because this is an entity field that needs to be saved back to the database, where it has an actual column, and where the calculated amount should be persisted to. My other worry about the automatically updating approach is that the calculated values might be a little bit different from what was originally saved to the database, due to rounding values (an older version of the software, was using floats, but now decimals). So, loading, let's say 2000 entities from the database could change their status and make the ORM believe that they have changed and be persisted back to the database the next time the SaveChanges() method is called on the context. It would trigger a mass of updates that I am not really interested in, or could cause problems, if the calculation methods changed (the entities fetched would lose their old values to be replaced by freshly recalculated ones, simply by being loaded). Then, let's take the example even further. Each invoice has some related invoice details, which also have BilledAmount, PaidAmount and Balance (I'm simplifying my actual business case for the sake of the example, so let's assume the customer can pay each item of the invoice separately rather than as a whole). If we consider the entity should take care of itself, any change of the child details should cause the Invoice totals to change as well. In a fully automated approach, a simple implementation would be looping through each detail of the invoice to recalculate the header totals, every time one the property changes. It probably would be fine for just a record, but if a lot of entities were fetched at once, it could create a significant overhead, as it would perform this process every time a new invoice detail record is fetched. Possibly worse, if the details are not already loaded, it could cause the ORM to lazy-load them, just to recalculate the balances. So far, I went with the Update() method-way, mainly for the reasons I explained above, but I wonder if it was right. I'm noticing I have to keep calling these methods quite often and at different places in my code and it is potential source of bugs. It also has a detrimental effect on data-binding because when the properties of the detail or header changes, the other properties are left out of date and the method has no way to be called. What is the recommended approach in this case?


title: Where does Objective-C come from? C++ or C?

text: I am very confused about this programming language, Objective-C, which I heard is used to develop iOS applications. I know that it uses the principles of OOP. Would it be easier to learn if I already knew C++? What about it's name? is it a combination between the C programming language and the OOP principles I use in C++?


title: Is there a fundamental reason for keeping file systems and versioning systems separate?

text: I've done some work looking at Next3 and ext3cow, and a few other file systems that provide snapshots and/or file versioning. It seems a bit strange to me that file systems only go part-way with version control, though. Are there **fundamental** reasons for keeping the two separate? How challenging would it be to, for example, build a version of the ext3 file system which includes a git-like interface for managing file versions?


title: In dependency injection, is there a simple name for the counterpart of the injected object?

text: In tutorials and books, I have never seen a single word describing the object that the injected object is injected into. Instead, other terms are used, like "injection point" which don't denote the object containing the injected object. And nothing I can think of sounds right, except maybe "injection target" - but I have never read it anywhere. Is there a single word or a simple expression for it, or is it like the "He- Who-Must-Not-Be-Named" from a recent fantasy book series?


title: A small project but I want to use design patterns to do it right

text: I've got a project coming up, a very a small system, but one that needs to be extended in the future. Here's how I've designed it so far. It's 3-tier: presentation, business and data. For the presentation layer there will be ASP.NET webforms with user controls (.ascx). There are .NET validator controls on the usercontrols. In the business layer there will be a domain model, probably an Active Record- based object for _each_ type of business entity (e.g. class Trainee, class Course etc). These objects will contain the relevant data (user input or DB) in properties but also have behaviour such as CalculateCost(), Validate() and Save(). When a page passes input to a business object for processing, the object will validate the input. Any validation failures will be stored within a collection within the object. If the data is valid, the business object's Save() method can be called. Save() will call a Data Mapper which transforms the business object's data to a DTO, the Data Mapper then passes the DTO to a table data gateway. The Table Data Gateway takes the DTO and performs CRUD operations with it. Any data to be returned from the DB is tranformed into a DTO, passed to the mapper, and then returned to the relevant business object. Would you recommend the above approach for any future small TDD projects that are probably likely to be extended, or is it overkill? Any advice is appreciated. Even if it is to say "I have no idea what you're talking about" :)


title: Daily Scrum Meeting (Burndown chart)

text: Here is an example: early in the morning of the second day of the Sprint (during the stand up) I go to the board and see that the story I worked the previous day (first day of Sprint) contains a big "1 IDEAL DAY" written on it (estimate). Right now (early in the second day of Sprint) the story is not completed and I guesstimate it will take half a "REAL DAY" to complete it. Question: so to track progress and update the burndown right now, shouldn't I update that "1 IDEAL DAY" on the card with _something else_ (recap.: original estimate in 1 ideal day, remaining work in 1/2 real day)? What would be that _something else_ in this particular example?


title: Fast Learning: Is it bad?

text: As many of you must have noticed, learning to program is not an overnight thing, it takes years of hard work (I really should refer here to this wonderful article of Peter Norvig). But there's a lot you can do to make an impressive fast progress, you can use the online tutorials, websites like projecteuler or CodingBat, Stackoverflow help, or any other quickie stuff that can give you the ability to actually get something done... You may not need all the very basic things that you will get if you go to school or learn by some formal way. They might be skipped, and if nothing goes wrong, your work will be done without dealing with them (I'm not talking about making a kernel or some huge thing, but things like making a website, a program to sort files, basic database management scripting, or anything else that may actually gets you to be hired or brings money somehow)... So, the question is: To what degree can you get by fast learning?? What are the benefits of all the things that is taught in schools about programming? (and here I mean the theoretical stuff of how internal stuff works and philosophy of programming techniques or any abstraction articles, not the practical part), and is it possible for a person to keep going and up- progressing this way or he has to switch to the slow-steady way if he wish to progress?? Thank you.. Any personal experience or link to a personal experience will be highly appreciated... EDIT: and an important question: if you think fast learning makes a person a low-level or medium level, but not gonna take him to the high level or architect level, how can he catch up to what he missed of principles or theoretical sides on-the-go, while he is progressing?? like a top-down approach of learning practically then dig deeper at the principles he missed,, how can that be achieved ??


title: Is exception handling a cross-cutting concern?

text: I don't see much of a difference between the concerns of exception handling and logging in that both are cross cutting concerns. What do you think? Shouldn't it be handled separately on its own rather than interleaved with the core logic a method is implementing? **EDIT** : What I am trying to say, is that in my opinion a method implementation should only contain the logic for the successful path of execution and exceptions should be handled elsewhere. This is not about checked/unchecked exceptions. For example, a language might handle exceptions in a fully checked way by using constructs like this:               class FileReader {            public String readFile(String path) {         // implement the reading logic, avoid exception handling       }          }          handler FileReader {             handle String readFile(String path) {           when (IOException joe) {             // somehow access the FileInputStram and close it           }        }          }      In the above conceptual language, the program won't compile in the absence of `FileReader` _handler_ , because the `FileReader` _class_ 's readFile is not throwing the exception. So by declaring the `FileReader` _handler_ , the compiler can ensure that it is being handled and the program then compiles. This way we have the best of both of checked and unchecked exception problems: robustness and readability.


title: What happens when a company says/pretends that it uses a version control system (or any other tool/methodology), but doesn't?

text: This question might look like a mix of Is it unusual for a small company (15 developers) not to use managed source/version control? and How to convince a teammate, who sees oneself as senior, to learn SVN conceptual basics?. My interest is purely academical, since the company mentioned here does not exist any more, but it keeps popping up in discussions, so I would really like to hear the community's thoughts on how to behave in such situation. It has happened to me twice, with the most recent example being more interesting: I visited a company for a interview and was being asked for subversion experience. After that I got into an extensive QnA related concepts such as branching/merging, access rights etc. At the end I got the job. From my first day there, I saw that everyone was using a shared drive where they coded. Because subversion was used as a backup, people had to commit from their local machines, on a windows shared drive, which made each commit sometimes to last more than 30 minutes (I do not know the internals of why), while sometimes encountering locks or any othere issues where encountered. There was a template project from which we did a "branch". No merges anywhere. So once confronting my line manager about it I got told that we have an svn installation and that we use it properly, obviously we did not. So what should the appropriate action for developer/employee do in such case(s)?   * Nothing, accept it as a difference in perspective,   * Leave   * Try to educate the team


title: Java Application for handling records(CRUD)

text: I am new to JavaEE and am faced with a tight situation here. I have to develop a Java application for (CRUD) handling records and saving and loading an XML concerning that record. Obviously, I won't be asking you to do this for me. What I would be asking you is to give me some hints/pointer. Initially I thought JAXB would be enough for this but after putting a lot of time learning it and implementing the program I realized that it just can create the XML and read it but for update, delete I would have to do something else. Even if it wasn't for update and delete features requirement for my project I would still think that by just using JAXB is not a good implementation. I was wondering if "REST with Java (JAX-RS) using Jersey" should do the trick for me. ?


title: What's the point of those technique detailed interview question for Senior dev?

text: I've had an internal promotion interview for gain a higher level programmer title, something like Senior plus. And I've been interviewed by around 7 people using different technology, and people using the same technology with me(.Net) tend to ask very technique detailed question which can actually easily been found via Google, like what is JIT, how GC works, difference between List and Array, abstract class and interface, delegate and event, even what is the class name when you process Upload file, etc. And I've got only one question asked about one of my design idea in my project and just simple discussion. But for most other my design choice they seems just not interested. I didn't get the result yet and it would be about late this week, but here is my concern: I personally think when I play as a senior programmer, I mainly solving problems, and I just need to know there are some certain way can make it happen but I may not remember every detailed thing, and that's should be why we have those detailed reference documentation like MSDN. I feel it fine if you found I've not too much experiences around this area like Junior to Intermediate level, but when tend to interview higher level guy, isn't you should more focus to see how this guy logical thinking is and how good is he/she at solving problems? Does everybody just think if you know every detailed small point tech stuff then you are a Senior+. And by checking those interview question books I found there are more those kind of questions. If I spend 5 days go through those interview question list book I can easily make those guys feel a wow, but does that really mean anything? This kind of interview can easily let those guys good at remember things gain higher salary even they have no idea how to solve difficulty problem. So why is this happening on the world, is that just cause problem solving skills, design skills are hard to measure? I've serve this company for years and only had few interview with other companies so I wonder is that every company doing the same thing? Or is this actually just my own problem that I should try harder to remember everything in MSDN in my mind so that I can work even without it and internet? **EDIT** For better explain my situation regarding Frank's concern about job tasks. Sorry it's my bad didn't clarify those background. There actually will be no specifically job's task changes, I personally think what I've done already played as a senior, like code review, mentor members, review BA's doc and give technique opinions, design architecture of new projects, it's just my title still stayed without senior and I asked to get one to reflect pay slip and lead to such an interview. This is a Saas company so people stay in one project as long as that product is still alive, this leads they need people be able to design more new features based on current product, fixing technique difficulty on live servers, design/code review/mentoring members And higher level title based on technique would be Architect and we do not have any job similar with Technical Expert. And I agree if you want to play Technical Expert role you should know more detail about the tech you use. Sorry it's my bad didn't clarify those background.


title: Is this awkward spacing some type of style?

text: In reading another programmers code, he uses a format I have never seen. E.G.                   namespace MyNs.HereWeAre              {//tab here for some reason              public class SomeClass                    {//here's another tab                    public string Method()                         {//yet another tab                         string _variable = "";//no tab implementation                         return _variable;                         }                    }//eof - class  (Yes these eof comments are on every file)             }//eof - namespace     // eof - file      I'll admit...this code makes me angry. It is difficult to achieve this style. One needs to fight the default formatting provided by the IDE, visual studio. I could swallow this pill a little easier if I knew that there was a good reason for this style. Does this style stem from some other programming language/IDE?


title: Encapsulating a class within another class to hide its exposed properties and details

text: I have essentially a data model class that represents an XML data structure that we use to model our system. The model class is in a shared project that is used by a number of different solutions in order to generate a common XML data structure for usage by any number of applications. In one application I am involved in we have provided a wrapper class for one of these XML model classes as we wish to perform a number of operations on the model data. However other parts of my program also needs to access this data for calculations they need to do. At the moment I have this setup (note this is an example only but represents my code structure) 1)               public class ModelWrapper     {         private readonly ModelClass _model;              public int PropertyX          {            get            {               return _model.PropertyX;           }         }              public ModelWrapper(ModelClass model)         {            _model = model;           }              // and other methods we need that uses the properties we have exposed e.g         public void PerformOperation()         {             if(this.PropertyX > 10)                // do something             else                // do something else         }     }      This appears ok, but I've run into the problem where I or another programmer has un-intentially used the private _model variable. It seems to me that we could end up with hidden issues in this method in the fact that there are two ways to get to the same data and if we put some logic in the public exposed get property then we could miss that if we directly reference the private variable. The other alternative I thought of was 2)               public class ModelWrapper     {         public readonly int PropertyX;              public ModelWrapper(ModelClass model)         {            PropertyX = model.PropertyX;              // set other properties here we wish to expose on the ModelClass ...         }              // and other methods we need that uses the properties we have exposed e.g         public void PerformOperation()         {             if(this.PropertyX > 10)                // do something             else                // do something else         }     }      Or another option after reading some posts about this is: 3)               public class ModelWrapper     {         private readonly int _propertyX;         public int PropertyX          {            get { return _propertyX; }         }              public ModelWrapper(ModelClass model)         {            _propertyX = model.PropertyX;           }              // and other methods we need that uses the properties we have exposed e.g         public void PerformOperation()         {             if(this.PropertyX > 10)                // do something             else                // do something else         }     }      Why do this? I thought it would be a good idea to hide the model from the our code as we wanted a wrapper class anyway to do the methods so why then expose the model as well? I thought it might be overkill but it does save in other parts of the code going something like **ModelWrapper.Model.PropertyX** etc So to the question. Which method if any would be a better solution. Is it overkill or are there better practices out there for this? EDIT: I added another option (3) as it there is no need to set the properties I am exposing so I didn't necessarily want to have a private set as it's only being set in the constructor. Hence the readonly private variable that is used in the get part of the exposed property? I've also found a stack overflow question about this at http://stackoverflow.com/questions/2249980/c-immutability-and-public-readonly- fields but it doesn't necessarilly say which was better/preferred solution with the current c# limitations. Any ideas on the 3 implementations as to the best practice?


title: Rails solution for mobile-specific content filter?

text: To note, I'm not interested in simply 'hiding' content for mobile devices, I want to filter out that content completely. I'm also not trying to address the issue by building a mobile specific interface (mob.example.com). There was another question regarding something similar: How do I prevent useless content load on the page in responsive design? The solution, in that post, was to set a session during the initial request, and then use the session to filter content on subsequent requests. I primarily develop in Rails, and I'm wondering if there are any gems or ruby- specific solutions to this problem?


title: Business Objects within a Data Access Layer

text: So I've been creating a data access layer via TDD and have approached somewhat of a concern. I'd rather not start down the wrong path, so I figured I'd ask you guys to see if my thoughts were in line with a clean architecture. The methods within my Data Access Layer (DAL for short), are pretty simple. They are in line with the stored procedures in the database (no other way to call into it to keep things clean), and they contain those same parameters that the procedures do. They then just connect to the database, and return the query result. Here's one example:               public int DeleteRecord(int recordId)     {         recordId.RequireThat("recordId").NotZeroOrLess();              List<SqlParameter> parameters = new List<SqlParameter>();         parameters.Add(new SqlParameter { ParameterName = "@RecordId", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Input, Value = recordId});              return this.ExecuteNonQuery("DeleteRecord", parameters.ToArray());     }      This works perfectly for this type of method because I am not doing anything meaningful with the result set. I just want to make sure the command worked, so I will return the result of the non-query, which is just the rows affected, and I can verify the logic using that number. However, say in another DAL method, I want to load a record. My load procedure is going to be executing `selects` against a bunch of tables and returning a `DataSet`, but I am battling with whether my DAL should create the Business Objects within the method using the `DataSet`, _or_ if my Business Objects themselves should just have a `Load()` method that gets the `DataSet` from the DAL, and then basically fills itself in. Doing it through the DAL would result in less logic in the Business Objects (even though this is just select logic, it's still logic), but would crowd the DAL a little bit and make it feel like it really is doing something that it shouldn't be doing. What do you guys think?


title: Difference between Controller and Dispatcher in MVC for web frameworks?

text: In MVC applied to WSGI or Java EE, is the Servlet a controller, dispatcher, or both? I think I've seen system diagrams where the controller and the dispatcher are different. Could the controller control SQL statements which should not be in the dispatcher? Thank you


title: Advice on whether to use scripting, run time compile or something else

text: I work in the prodution area at my works and I design and create the software to run our automated test equipment for testing our products. Everytime I get involved with a new machine I end up with a different and (hopefully) better design. Anyway I have come to the point where I feel I need to start standardizing all the machines with the same program. I see a problem when it comes to applying updates as at the moment the test procedures are hard coded into the program at each station. I neeed to be able to update the core program without affecting the testing section. The way I see it is that this will mean splitting the program into 2 sections.   1. Main UI - This is the core that talks to everything on the machine such as cameras, sensors, printer etc and is a standalone application.   2. Test Procedure - This is the steps that is executeted everytime the machine runs through a test. The main UI will load the test procedure and execute when ever a test is required. My question is what is the best approach to this in terms of having an application load a file and execute the code with in? Take into account that the code in the test procedure will need access to public methods on the UI/core system to communicate to sensors etc. I have heard about MS Roslyn and had a quick look, would this solve my issue?


title: How can I document someone else's past work?

text: We're in a bad situation of having very little documentation on customization our past workers made to a business critical system. Lots of changes were done to Crystal Reports, database entities, and proprietary configuration/programming files for our ERP software. The current documentation generally reads something like this: > This program is run before invoicing. Known bugs: none. > > Run this program after installing software X. > > Changed the following fields in this report: (with no explanation of how or > why) Our IT shop is small, and in the case of the ERP software, most work was lumped on one person (that's me now) so no one else here knows what all we did. The IT and accounting department know bits and pieces (occasionally quite helpful ones) but it's not enough. Another problem is our Accounting department seems to _think_ we're well documented. It's true that we kept lots of records of what went _wrong_ , but very little explains what (if anything) was done to fix these problems. We have hundreds of papers explaining bugs, but the documents explaining changes (as shown above) are almost useless. **How can I go about documenting past changes when I don't know what all was done?** I can start with documenting _what_ we've changed: Files, database tables ect which we need to have for the system to work. I can also document what we _do_ ; when reports are run, why people were told to use X report/program. But when one of these customized things has a problem, I'm always back to square one. How can I proactively document this stuff for myself and others?


title: DAO/Webservice Consumption in Web Application

text: I am currently working on converting a "legacy" web-based (Coldfusion) application from single data source (MSSQL database) to multi-tier OOP. In my current system there is a read/write database with all the usual stuff and additional "read-only" databases that are exported daily/hourly from an Enterprise Resource Planning (ERP) system by SSIS jobs with business product/item and manufacturing/SCM planning data. The reason I have the opportunity and need to convert to multi-tier OOP is a newer more modern ERP system is being implemented business wide that will be a complete replacement. This newer ERP system offers several interfaces for third party applications like mine, from direct SQL access to either a dotNet web-service or a SOAP- like web-service. I have found several suitable frameworks I would be happy to use (Coldspring, FW/1) but I am not sure what design patterns apply to my data access object/component and how to manage the connection/session tokens, with this background, my question has the following three parts:   1. Firstly I have concerns with moving from the relative safety of a SSIS job that protects me from downtime and speed of the ERP system to directly connecting with one of the web services which I note seem significantly slower than I expected (simple/small requests often take up to a whole second). Are there any design patterns I can investigate/use to cache/protect my data tier?   2. It is my understanding data access objects (the component that connects directly with the web services and convert them into the data types I can then work with in my Domain Objects) should be singletons (and will act as an Adapter/Facade), am I correct?   3. As part of the data access object I have to setup a connection by username/password (I could set up multiple users and/or connect multiple times with this) which responds with a session token that needs to be provided on every subsequent request. Do I do this once and share it across the whole application, do I setup a new "connection" for every user of my application and keep the token in their session scope (might quickly hit licensing limits), do I set the "connection" up per page request, or is there a design pattern I am missing that can manage multiple "connections" where a requests/access uses the first free "connection"? It is worth noting if the ERP system dies I will need to reset/invalidate all the connections and start from scratch, and depending on which web-service I use might need manually close the "connection/session"


title: Should I include multiply license header notice in dual license software?

text: Is it necessarily if a software released under both of LGPL3 && GPL3 terms have to include both license header notice top of each file? Or just put GPL header notice? or simply put LGPL3 license text in some file like COPYING.LESSER ? EDITED: I am the copyright holder of the project!


title: Why isn't exponentiation hardware-implemented?

text: Why is there no exponentiation operation in hardware, even though many languages have builtin operators for it? Is it because even hardware implementations would need to use the same algorithm as software (i.e. no hardware implementation could be significantly more efficient), or because it is rarely used, or another reason?


title: Lists & Collections in MVVM - which approach to take?

text: I'm currently working on a Silverlight app using Caliburn.Micro. At present, we have Views (eg: `PeopleView`) and View Models (eg: `PeopleViewModel`) that equate to 'pages' of the application. `PeopleView` might contain a `ListBox` ("`People`") which is bound to an `ObservableCollection` of `Person` objects, and has an `ItemTemplate` assigned to denote how each `Person` object should be displayed. However, one of my colleagues has begun to implement a list in another way, where each `Person` is a View Model (ie: `PersonViewModel`) and has an associated `PersonView` to determine how that `PersonViewModel` should be displayed in the `ListBox`. The latter seems more MVVM (or at least has more mention of V and VM!) but I'm not sure whether there's a particularly large advantage to doing one over the other. Are both of these ways valid? Is either better than the other?


title: What issues carry the highest risk in a software project?

text: Clearly, software projects are different from other industries in terms of many things like for instance, quality assurance, project progress measurement, and many other things. Unique characteristics of software projects also makes the risk management process unique. Lots of issues in a project might lead it to unacceptable delay or failure to deliver business value. They might even make a complete disaster in the project. What are the deadliest risk factors in a software project? How to analyze, prevent and handle them? Particularly, I'm interested in the issues that you can detect from the beginning and you should keep an eye on (for example, you might be told about a third-party API that the current application uses and lacks documentation). Please share your experiences if they are relevant.


title: Use of malloc in C

text: Is it necessary to call free function every time we use malloc in C. I am asking this because I have seen many times that it is not called . Thank you


title: Is it better to have constructors with or without parameters?

text: Is it better to have constructors with or without parameters and why?               public NewClass( String a,  String b, int c) throws IOException     {         //something     }      _OR_               public NewClass()      {         //something     }


title: Testing a codebase with sequential cohesion

text: I've this really simple program written in C with ncurses that's basically a front-end to sqlite3. I would like to implement TDD to continue the development and have found a nice C unit framework for this. However I'm totally stuck on how to implement it. Take this case for example: A user types a letter 'l' that is captured by ncurses getch(), and then an sqlite3 query is run that for every row calls a callback function. This callback function prints stuff to the screen via ncurses. So the obvious way to fully test this is to simulate a keyboard and a terminal and make sure that the output is the expected. However this sounds too complicated. I was thinking about adding an abstraction layer between the database and the UI so that the callback function will populate a list of entries and that list will later be printed. In that case I would be able to check if that list contains the expected values. However, why would I struggle with a data structure and lists in my program when sqlite3 already does this? For example, if the user wants to see the list sorted in some other way, it would be expensive to throw away the list and repopulate it. I would need to sort the list, but why should I implement sorting when sqlite3 already has that? Using my orginal design I could just do an other query sorted differently. Previously I've only done TDD with command line applications, and there it's really easy to just compare the output with what I'm expected. An other way would be to add CLI interface to the program and wrap a test program around the CLI to test everything. (The way git.git does with it's test-framework). So the question is, how to add testing to a tightly integrated database/UI.


title: WCF Data Services (OData) Vs ASP.NET Web API? Hypermedia?

text: I'm desiging a distributed application that will consist of REST services and a variety of clients (Silverlight, iOS, Windows Phone 7, etc). I was ready to decide that I would implement my REST services using WCF Data Services (OData) but now the the MVC 4 Web API has made me question that decision. What I liked about OData was the URI querying and hypermedia capabilities you get for free. What I disliked was the verbosity of the OData payload; lots of unnecessary characters coming over the wire. What I like about the Web API is that the payloads are much more concise and it has the URI querying capability of OData, however it seems to be lacking hypermedia (out of the box, at least). My boss is also pushing for the Web API because "the powers that be at Microsoft are backing it and OData hasn't been getting traction." So I have two questions: 1) Can anyone comment on the backing/traction of the Web API and OData? 2) Is the Web API expected to natively support hypermedia by release time or are there any off-the-shelf implementations or examples I should look into? Thanks!


title: Scheduling Algorithm for Scheduling Life

text: I am trying to write some code to schedule a set of real life tasks that are input by the user. These tasks are stored in an sqlite database. And at the moment, the only parameters I am taking into consideration are the, `The project to which a task belongs to --> p`   `The name of the task itself --> t`   `And the due date for this task --> d` The `project` and `due date` parameters are optional. But assuming that the user will always input at least the `task name` and `due date` for every task.. I was wondering if it is possible to schedule the set of tasks using a scheduler like the `Completely Fair Scheduler (CFS)` for example!. I realize that the CFS was written for scheduling tasks with much finer granularity(nanoseconds) than the set of tasks being proposed for this purpose... But I realized that it might be possible and maybe more efficient if I can modify it to work with tasks that are on the same time scale as our perception of time. A typical entry in the database would be in the format (p, t, d). 'p' is optional. Here are a few examples.. `(_, 'Call home', 29/2/2012)`   `(Work, 'Meet boss', 14/3/2012)`   `(Work, 'Ask for raise', 18/3/2012)`   `(_, 'Book tickets', 10/3/2012)`   `(Work, 'Quit', 14/4/2012)`   `(Personal, 'Get botox injections', 10/3/2012)`   `(Personal, 'Get breast implants', 10/10/2012)`   `(_, 'Dad bday', 7/10/2012)` Here is a situation to consider. I would like to wake up in the morning. Run this "yet to be coded" algorithm on the set of tasks.. like the ones given above.. and I would like to receive a schedule for the rest of day, that maximizes throughput. At a later stage, I would like to pass arguments to this algorithms that would allow me to control the scheduler to return a set of tasks depending on my current situation. Like if I am at work, I want to be able to pass arguments to the algorithm, to ask it to only return tasks that can be completed at work.. I hope I am able to convey the gist of it. I understand that the `due date` alone is not sufficient to schedule tasks using the CFS for example.. but if there are other parameters that I should consider, please do let me know. And any suggestions for the kind of scheduling algorithm to employ would be helpful. Thanks.


title: Is creating a separate pool for each individual png image in the same class appropriate?

text: I'm still possibly a little green about object-pooling, and I want to make sure something like this is a sound design pattern before really embarking upon it. Take the following code (which uses the Starling framework in ActionScript 3):               [Embed(source = "/../assets/images/game/misc/red_door.png")]     private const RED_DOOR:Class;          private const RED_DOOR_TEXTURE:Texture = Texture.fromBitmap(new RED_DOOR());          private const m_vRedDoorPool:Vector.<Image> = new Vector.<Image>(50, true);     .     .     .     public function produceRedDoor():Image     {         // get a Red Door image     }          public function retireRedDoor(pImage:Image):void     {         // retire a Red Door Image     }      Except that there are four colors: red, green, blue, and yellow. So now we have a separate pool for each color, a separate produce function for each color, and a separate retire function for each color. Additionally there are several items in the game that follow this 4-color pattern, so for each of them, we have four pools, four produce functions, and four retire functions. There are more colors involved in the images themselves than just their predominant one, so trying to throw all the doors, for instance, in a single pool, and then changing their color properties around isn't going to work. Also the nonexistence of the static keyword is due to its slowness in AS3. Is this the right way to do things? * * * **EDIT:** One individual piece of the puzzle is whether I should be trying to throw all of these pools into the same class, with brand new functions and everything for each and every pool. That is somewhat related to another question I asked recently. Even though the accepted answer of that question didn't necessarily address this particular scenario, getting more classes, variables, abstractions, etc. is going to create more overhead, and when you're trying to do something like object pooling, I'm not sure whether neatening up the class design like that is going to introduce "too much" overhead. This is only one individual part of what I'm asking though, as the question is ultimately much more general.


title: Advice on designing a robust program to handle a large library of meta-information & programs

text: So this might be overly vague, but here it is anyway I'm not really looking for a specific answer, but rather general design principles or direction towards resources that deal with problems like this. It's one of my first large-scale applications, and I would like to do it right. **Brief Explanation** My basic problem is that I have to write an application that handles a large library of meta-data, can easily modify the meta-data on-the-fly, is robust with respect to crashing, and is very efficient. (Sorta like the design parameters of iTunes, although sometimes iTunes performs more poorly than I would like). If you don't want to read the details, you can skip the rest **Long Explanation** Specifically I am writing a program that creates a library of image files and meta-data about these files. There is a list of tags that may or may not apply to each image. The program needs to be able to add new images, new tags, assign tags to images, and detect duplicate images, all while operating. The program contains an image Viewer which has tagging operations. The idea is that if a given image A is viewed while the library has tags T1, T2, and T3, then that image will have boolean flags for each of those tags (depending on whether the user tagged that image while it was open in the Viewer). However, prior to being viewed in the Viewer, image A would have no value for tags T1, T2, and T3. Instead it would have a "dirty" flag indicating that it is unknown whether or not A has these tags or not. The program can introduce new tags at any time (which would automatically set all images to "dirty" with respect to this new tag) This program must be fast. It must be easily able to pull up a list of images with or without a certain tag as well as images which are "dirty" with respect to a tag. It has to be crash-safe, in that if it suddenly crashes, all of the tagging information done in that session is not lost (though perhaps it's okay to loose some of it) Finally, it has to work with a lot of images (>10,000) I am a fairly experienced programmer, but I have never tried to write a program with such demanding needs and I have never worked with databases. With respect to the meta-data storage, there seem to be a few design choices: **Choice 1** : Invidual meta-data vs centralized meta-data **Individual Meta-Data** : have a separate meta-data file for each image. This way, as soon as you change the meta-data for an image, it can be written to the hard disk, without having to rewrite the information for all of the other images. **Centralized Meta-Data** : Have a single file to hold the meta-data for every file. This would probably require meta-data writes in intervals as opposed to after every change. The benefit here is that you could keep a centralized list of all images with a given tag, ect, making the task of pulling up all images with a given tag very efficient


title: Offshoring a Software Project -- Conflict Resolution

text: I had been tasked with managing a project which was outsourced to some Ukrainian developers. The company hired them through Elance at a **fixed price**. At that point my boss left me _alone_ to handle them and get the work done. I created a detailed specification of the complete thing that needed to be done. The project involved dealing with such things as XMPP, RabbitMQ, and Database. In my first meeting with them (always IM) I explained **thoroughly** what they needed to do. They seemed to understand it -- and they were very confident that it would be done easily. So far so good. But after one week, when we met again, they were full of misunderstandings about what needed to be done. When I asked one of the developers if he knew XMPP, he said he was working with it for the first time. At our first meeting I'd very specifically mentioned the complexity of the project and the technologies involved. Plus, I had repeatedly asked them to write a functional specification of exactly HOW they would do it. But they said NO, and insisted that they would rather write the code. I said OK. The project completed after 3 weeks and they delivered what was needed. At that point I started to review the code. It was okay for the most part, but there ware some important problems:   * they hard-coded some of the things that needed to be separated out into a config file   * there were multiple config files that I needed to be consolidated in one   * they wrote absolutely NO documentation   * some other minor changes I asked them to make these changes (except documentation) -- And, we had an argument. They said, since the price was fixed, I was being unfair in asking them to make any changes once they completed the working code. That they had worked for unreasonable amount of time on the project and now it was completely wrong to ask for anything. Finally now they have made the changes, and the project is over. But it leaves some questions in my mind...   * They did what was needed but I needed it **properly done** , and hence the changes. was I really unfair?   * Why did I agree on letting them code without having a functional specification?   * Why did I not make sure that they understood everything the first time? Does anyone find themself in the same position? Do you think there is a better way to manage outsourced projects? _**\-- UPDATE --_** Thanks for all the opinions -- after reflecting upon entire experience, I can conclude...   * Although I wasn't vague in the specifications from my side, I certainly didn't make them _ironclad_ as suggested. So the take away is: always be as much specific as possible -- read your specs from their perspective too and see if you missed something. Repeat it at least three times.   * Just specifying what the code should do it not enough. You must specify what the code is supposed to look like. What the directory structure will be; even the file names if possible. This will save you from lot of annoyance later. Strictly specify the coding guidelines, variable naming conventions, internal documentation format, etc. See to it that they abide by those guidelines, and if not, scream.   * Demand a functional specification from their side -- insist that it be written before any code. This will get a lot of confusions and misunderstandings out of the way.   * Review the code as it is being developed so that you identify the anomalies earlier and get them corrected. Talk to them at least once every other day.   * Lastly, try to make a good rapport with them. Make them feel that you appreciate their work. Don't push them exaggeratedly to fit your guidelines -- instead request them to do so and tell them that it would make maintaining the code so much easier for you once they complete the project.


title: Long lines of text in source code

text: > **Possible Duplicate:**   >  Is the 80 character limit still relevant in times of widescreen monitors? I used to set a vertical line set at 80 characters in my text editor and then I added carriage returns if the lines got too long. I later increased the value to 135 characters. I started using word wrap and not giving myself a limit but tried to keep lines short if I could because it took a lot of time shortening my lines. People at work use word wrap and don't give themselves a limit.. is this the correct way? What are you meant to do ? Many thanks.


title: System analysis at the begining of the project

text: When I want to develop a new application, first I'm going to design a UML and specify project details and definition. But when I start development process, I determine that I should change some parts of my idea in order to become more popular software or easier logical steps for my users or simpler process or anything else. Then, I change my code, redesign some parts of my UML and start/continue development process one time again and sure that this time I have a perfect project definition and UML, but after a while ( this time takes longer ) i determine again I should change something again ! So I get back and change my UML( sometimes not ! just continue the project without changing UML ) and so on. This process will happen over and over until I become tired or find (almost) the best state of the project or have time limitation problem! So my question is:   * _'Can I design a perfect UML at the beginning of my project so that describe the best state ever !?'_ or _\- 'Should I swear in God never ever change my UML ( and project definition ) even if there is a better one and write current state to the end!'_ Another question "Is changing some parts of a new idea, even if analyzed with hands of the best analyzer in the world, is inevitable ?( in order to find the best state )". I mean we can't fully simulate user experience, can we? We should see it in action.


title: Choosing how to approach Geocoding Requests

text: I am about to begin writing a program in c# that will read Addresses from a source file create a Geocoding request, sent it to Google Maps API, get the response choose the coordinates from the xml and then store them in a database. My question is what is the proper type of source file considering performance and easy implementation. I have the option to supply the source addresses as txt file or xml file. The number of addresses need to get geolocated is about 100.000 which is a big number so what is the proper approach to handling this kind of requests? Should i provide the addresses source file as txt or xml or something else?


title: How to keep unit tests independent?

text: I've read it at many places that unit tests should be independent. In my case I have a class that does data transformation. These steps must be done sequentially, otherwise they don't make sense. For example,               load_data     parse_float     label     normalize     add_bias     save_data      For example, I cannot normalize the data before I label it, because then values have changed and I don't have access to the original values of my data anymore. Or I cannot save the data before I actually loaded it. So my test class looks something like this               class TestTransform(Testcase):       def setUp(self):         self.trans = Transform()            def test_main():         self.load()         self.parse_float()         self.label()            def load(self):         self.trans.load()         assert ....            def parse_float(self):         self.trans.parse_float()         assert ....      In this case, my unit tests clearly depend on each other, but I can't see how else I could do it. As an alternative, I could write something like this                 def test_normalize(self):         # setup         self.trans.load()         self.trans.parse_float()         self.trans.label()         # test begins here         self.trans.normalize()         assert ....      But in this case, I run a lot of code multiple times, which is inefficient and makes my tests run a lot longer. So does the best practice of keeping unittests independent apply in this case or not?


title: Best way to create draw with limitation

text: I'm writing a program to automatically make the draw for a competition. There are four objects: `Debate` `Judge` `School` `Team` Each Debate has two teams and a judge. Each team participates in three debates. With this, there are the following rules: 1) A team cannot face someone from their same school 2) A team cannot face another team from the same other school (As in if they play a team from a school once, they cannot play again against someone from that school) 3) A judge cannot come from the same school as a team they are judging. So how would I create a draw? A draw looks like a table (I just need the data, but when you write it it looks like this) with a column for judges and then three other columns for each round of debates (the three debates each team participates in). Right now I'm basically choosing a random team, finding an opposing team that hasn't played the school of the first team before and doesn't come from the same school and then finding a judge from neither of those schools. Then I do the same thing until I have all the debates. The problem is the program sometimes gets into ruts where there is no other team/judge that fits. A human would then shift things around and try to find a way to move other judges around to figure it out, but how can I do that with a program. If I run the program again it figures it out just because it's random which teams it chooses for what. Basically, I'm wondering what the best solution is to the problem?


title: How to reduce the number of bugs when coding?

text: No one's perfect, and no matter what we do, we are going to produce code that has bugs in it from time to time. What are some methods/techniques for reducing the number of bugs you produce, both when writing new software and changing/maintaining existing code?


title: How to be more logical? (less bugs/errors)

text: I have been programming for 6 years and I am in high school (I prefer not to disclose my age). I have dabbled in many different languages. Just to list a few: Java, PHP, C++, Python, Autohotkey, Mathematica and many more. I have a very good understanding of the basics of general programming. The only problem is I _still_ create bugs all the time. I think too often. Do you have any hints _besides continuing_ to program that will help me become a better programmer and make less errors?


title: How to make code writing more accurate?

text: I am trying to practice writing code for a long period of time before compiling and write unit test (if possible) for what I wrote (the language is C++). Of course, I got the IDE support (Emacs or Eclipse for on the fly error detection and code completion) with minimal or no error. I practice this ability because the pattern "trial and error" in which a bit of code is written and then build/run to check the correctness is not productive as I feel. However, isn't what I am doing counter the purpose of testing? Maybe, the point of my practice is not to assure 100% logic correctness, but rather, 100% or close to 100% syntax correctness, in order to vastly improve productivity. I will try to practice with the small piece of code first, and then improve gradually as time passes. What's your opinion on code writing and productivity in general? Do you practice like I do or do you have much better method? (Aside from being in the "flow", or extremely concentration). I concern this matter because I heard that some people are an actual human compiler, and it seems like they can directly translate the logic to code as their natural language. **Edit:** I was a bit wrong when I mentioned not to improve logical correctness. Yes, logical correctness counts as well. What I want is to practice programming to the point where I can keep writing code for a long period of time with minimal mistakes (such as I can write 1000 lines of code,a and only a few trivial errors occur).In case of C++ or any language, using external libraries require you to understand many dependencies of the libraries to use it correctly in your code. For example, if you use Spring framework in Java, you have to make sure the xml, the server etc... are set up correctly. I consider this is also a form of syntax, and one way to achieve "syntax correctness" is to practice it frequently to the point when you can minimize the most mistakes written by hands. This is similar to when we first start learning programming, sometimes/often we miss the semicolon. Then we learn the mistake and improve it.


title: How do you stop yourself from making mistakes?

text: I used to pride myself with the high quality of the code I delivered. Today I made a mistake that wiped the grin off my face. It was a null reference exception caused by a hasty fix to an edge case that was caught during testing. I didn't have proper unit tests and I didn't regression test after making the fix. So my question is, what do you do to force yourself to follow best practices? I know you should write tests (unit, integration, acceptance, etc.) and run them to validate any changes. But when the pressure's on and you're rushing to put out a fire, how do you keep yourself focused and sticking to those best practices? Physical exercise? Religious TDD?


title: How can I learn to like C++?

text: I'm a wimpy web programmer by trade -- I enjoy programming in JavaScript, CoffeeScript, TypeScript, and Ruby. I have to program in C++ for my computer science degree, and it frustrates me. I don't much like the syntax and I feel that it's more verbose than it could be. I think I've roared "I hate C++" at least once per CS project. I don't need to _love_ C++, but I wonder if someone who adores the language can tell me what I can do to ease my pain. C++11 and Syntastic for Vim have certainly helped, but I'm wondering if there's something more than that -- a specific tool or an abstract philosophy.


title: Have you tried Usability Audit for your company's website?

text: We had a security audit and it was brilliant. Are there companies that do web usability audit?


title: Are there any studies of cross-functional teams vs. domain-based teams (e.g. project-based vs. software/mechanics/etc)?

text: I work in an organization which creates many integrated systems products - i.e. it is complete products with mechanical/system/electronics/software being designed and manufactured. At the moment most teams are organized around projects in a cross functional way. The advantage of an organization like this is that people who are working closely together for a common goal are close. The disadvantages come from the isolation of engineers from their peers. Typically a project is assigned only one software engineer. This means that the projects have a high truck factor, minimal knowledge sharing and best practices, and technical development is limited. So my question is: are there any studies comparing the cost/benefits of these two approaches?


title: Is it legal to disassemble a Microsoft dll and post the result on my blog?

text: I'm writing an article for my blog about undocumented functions which exist in the _dwmapi.dll_ library. I want to post the result of the disassembled code to explain how the names and parameters of these functions are obtained, something like the article from this blog. **This is only for educational purposes** to show a couple of samples using these undocumented functions. So the question is: _Can I post the disassembled code of this library on my blog?_ **UPDATE :** There exist a couple of applications like Aura which uses these undocumented functions (DwmGetColorizationParameters, DwmSetColorizationParameters), obviously the authors in some point disassembled the _dwmapi.dll_ file in order to get the parameters and functions names. But they (the authors) only publish the final source code to access to these functions. This makes me think that _I can disassemble in private a Microsoft dll and then publish an application or source code based in this research_. Is this correct?


title: Why do some of object oriented languages let programmer use primitive types?

text: Why do some object oriented languages let the programmer use primitive data types? Aren't classes like Integer, Boolean, etc. enough?


title: Job in other country - relocation package

text: I have the opportunity to work in an 'overseas' country. I have passed the technical interviews and I am at the 'offer' stage. Everything is ok, except for the fact that I am expected to pay for my plane ticket, which is almost 2000 EUR (an aprox 8000 km distance). I've discussed this with the possible future employer and they said that the plane ticket is my expense. What I'm asking you is: Shouldn't they pay me for the plane ticket? Or give me a relocation package? Do you accept this kind of offer? What relocation package would you have asked for if you were in my shoes? PS: Destionation country is Singapore. I am a Delphi Developer with 5 years of experience in SD, and overall 8 years in IT.