ResourceSerializable: an alternate to ORM and ActiveRecord

A few opinionated reasons I don't like the traditional ORM and ActiveRecord patterns:   * **They work only with a database.** Sometimes I'm dealing with objects from an API and other objects from a database. All the implementations I have seen don't allow for that. _Feel free to clue me in if I'm wrong on this._     * **They are brittle.** Changes in the database will likely break your implemenation. Some implementations can help reduce this, but a few of the ones I've seen don't.     * **Their very design is influenced by the database.** If I want to switch to using an API, I'll have to redesign the object to get it to work (likely).   * **It seems to violate the single-responsibility pattern.** They know what they are and how they act, but they also know how they are created, destroyed and saved? Seems a bit much. **What about an approach that is somewhat more familiar in PHP: implementing an interface?** In php 5.4, we'll have the `JsonSerializable` interface that defines the data to be `json_encode`d, so users will become accustomed to this type of thing. What if there was a `ResourceSerializable` interface? This is still an ORM by name, but certainly not by tradition.               interface ResourceSerializable {         /**          * Returns the id that identifies the resource.          */         function resourceId();              /**          * Returns the 'type' of the resource.          */         function resourceType();              /**          * Returns the data to be serialized.          */         function resourceSerialize();     }      _Things might be poorly named, I'll take suggestions._ **Notes:**   * **`ResourceId` will work for API's and databases.** As long as your primary key in the database is the same as the resource ID in the API, there is no conflict. All of the API's I've worked with have a unique ID for the resource, so I don't see any issues there.   * **`ResourceType` is the group or type associated with the resource.** You can use this to map the resource to an API call or a database table. If the `ResourceType` was `person`, it could map to `/api/1/person/{resourceId}` and the table `persons` (or `people`, if it's smart enough).   * **resourceSerialize() returns the data to be stored.** Keys would identify API parameters and database table columns.   * **This also seems easier to test than ActiveRecord / Orm implemenations.** I haven't done much automated testing on traditional ActiveRecord/ORM implemenations, so this is merely a guess. But it seems that I being able to create objects independently of the library helps me. I don't have to use `load()` to get an existing resource, I can simply create one and set all the right properties. This is not so easy in the ActiveRecord / Orm implemenations I've dealt with. **Downsides:**   * **You need another object to serialize it.** This also means you have more code in general as you have to use more objects.   * **You have to map resource types to API calls and database tables.** This is even more work, but some ORMs and ActiveRecord implementations require you to map objects to table names anyway. **Are there other downsides that you see?** **Does this seem feasible to you?** **How would you improve it?** _Note: I almost asked this on StackOverflow because it might be too vague for their standards, but I'm still not really familiar with programmers.stackexchange.com, so please help me improve my question if it doesn't shape up to standards here._


Is there a formal anti-pattern to describe the scenerio?

Some code is written to generate Excel Spreadsheets (Office Interop).   * The code performs very poorly.       * A subsystem is designed to generate the files at night. Performance isn't a concern at night.        * A function is created to pick the correct file from the 100 different files available depending on a chosen set of parameters.       * Because physical files exist, an archival system is added to backup these files (There is no reason to archive. These files should be generated on the fly).       * This system doesn't include a configuration file, instead it has a hard coded "server picker" function that simply reflects upon the server the code is running upon.       * A scheduled task is necessary to support and run this service. This boils down to a single problem. The original code performs far too poorly to run in a production environment. Had the performance problem been resolved, the subsystem and subsequently archiving system, "file picker factory function", hard coded failure point and the maintenance of the scheduled task and its added point of failure have no need to exist. This is a "cascading failure" if you will. The original problem led to more bad code, more bad solutions and unnecessary overhead. Is there a formal anti- pattern or general term to describe it?


Should i expect real world questions from interviewing agency ?

I started coding almost a year ago. By "coding" I mean HTML(5), CSS(3), and only few times I implemented some AJAX and JavaScript. I am interviewing for a position that expects me to know HTML, CSS, JS, JQuery, and AJAX. I feel confident in HTML5/CSS3 subject area and somewhat ok with javascript. Will agency expect from me to write some code during the interview? I do have a live website as an example which contains snapshots of past projects which were sent to them. I am little nervous, so any tips or recommendations are welcome.


Would PMP or CEH(Certified Ethical Hacker) course be more useful to a junior ASP.Net web developer?

Only recently i moved into doing Asp.net web development work, with quite a fair bit on Asp.net MVC. I'm thinking of taking up some courses to further build up my profile. I'm having a touch decision between taking PMP or CEH. Would course would benefit my current career more or maybe in the upcoming 1-2 years? Thanks.


How to handle hidden folders on deployed website

Our security team at work did a security scan of our soon-to-be-deployed website and one of the items that was found was "Hidden Directory Detected". It shows up for 3 different folders, aspnet_client, scripts, and content. The software recommends to throw a 404 instead of a 403, or to remove the folders completely. First, are the folders actually needed? How can I determine which folders in my visual studio project are actually needed in order for the site to actually run (without removing folders one-at-a-time and trying to access the site)? What is the proper way to handle this/resolve the security scan alert? Do I need to add special routing rules in the routeconfig.cs for when these paths are accessed? Edit, I should note that this is WebApi/REST service, not a regular MVC site. (Therefore, using the CustomErrors configuration section will not work)


How do you handle measuring Code Coverage in JavaScript

In order to measure Code Coverage for JavaScript unit tests, one needs to instrument the code, run the tests and then perform post-processing. My concern is that, as a result, you are unit testing code that will never be run in production. Since JavaScript isn't compiled, what you test should be precisely what you execute. So here's my question, how do you handle this? One thought I had was to run Unit Testing on the production code and use that for my pass fail. I would then create a shadow of my production code, with instrumentation and run my unit tests again; this would give me my code coverage stats. Has anyone come across a method that is a little more graceful than this? **EDIT** I don't want to use browser plugins, because I then need to use a browser in order to run my unit tests.


What's the real benefit of meta-modeling?

After reading several texts about meta-modeling I still do not really get the practical benefit. Sometimes I think it is only an interesting mind game but no useful tool. Sure it is wise to clarify your modeling vocabulary: some may say _class_ where others say _entity_ or _concept_ , but this is just simple documentation your modeling terminology. Meta-modeling, as I understand it, is more complex, as it tries to formalize and abstract modeling. Some good examples are Keet's formal comparison of conceptual data modeling languages (UML, ERM and ORM) from academia and the Meta Object Facility (MOF) from industry. To me MOF looks as impractical as CORBA, which was also created by OMG. In theory you could use meta-modeling to transform and integrate models in different modeling languages, but is anyone actually doing this?


Questions and Concerns About Using Java/Tomcat and Apache

I am having to use Java due to needing one backend library. Is it still considered good practice to set up Apache as the front-facing server and have Tomcat behind it? I am spending a lot of time configuring mod_jk. Also, what do people usually use for CMS or web-page templating in such a setup? I wanted to use Drupal, but was advised that since I'd have to set up mod_jk and jump through extra hoops configuring it, it might not be a good approach. Could you guys please suggest some common considerations or good approaches in this sort of a situation? Thanks, Alex


How to handle a 'bad code' interview?

A 'bad code' interview is one where the interviewee is shown a snippet of 'bad code' and asked to correct it or point out things that are wrong with it. I have trouble with these interviews because it takes me some time to read the code, figure out what its doing, and point out the flaws. In a situation where there's time pressure, I tend to freeze up and I see that the code 'should' work, even when it doesn't. What's a good way to handle this sort of interview, and, more generally, what are some good techniques to read and understand code _quickly_?


Clojure Web Application: EC2 or GAE?

I am developing a web application written in Clojure using the Compojure framework. My question is, should I deploy to Amazon EC2 or Google App Engine? I've read this article on running Clojure code on GAE, but I am still a bit concerned about the limitations on GAE. I am going to be running sandboxed Clojure code, which means I might end up needing to tinker with the JVM security policies. With EC2, I'll obviously have full control of everything. The downside is that this means more of an effort from a sys admin perspective. I'm not sure which option makes more fiscal sense. I am not expecting too much traffic initially, and suspect that I'll operate pretty close to the "free" tier/quotas on either service. I've had a lot of success working with EC2 in the past, but at the same time I'd love to get some experience with Google App Engine (which I've never used). So whats your vote: Amazon EC2 or Google App Engine?


Setting up a development standardization guide for in-house/vendor programmers

I was recently hired by a large multi-national corporation to head up mobile development for their sales operation/support team. In a company of close to 10,000 people I am, at least in the America's, the only mobile developer. They are testing the waters and phase 1 (temp-to-hire) went well enough for them. Now they are considering expanding to other developers for their other sales operations/support teams and I've been tasked with assisting/leading the writing of a standardization guide for iOS programming. I am a big believer in giving people the freedom to work in the manner they most feel comfortable in but at the same time, I have been the creator of and on the receiving ends of big balls of mud applications. Having learned through experience I have several standards that I follow religiously such as commenting, at times almost every line - just short things but enough to let someone else know what is going on and using #pragma mark - DESCRIPTION to block off like minded methods, indentation, naming classes with a prefix to avoid name space conflicts, etc. etc. So I guess what I am looking for is not to tell another programmer how they should iterate through an array but rather some basic standardization so anyone can jump into anyone else's project and find their way around with little learning curve. I'd love to see what other means people use to maintain control over a software development group.


Real world Agile practices and estimates

In a perfect world, we tell the client we follow an agile methodology where we allow the scope to increase/decrease as the requirements change and we bill per hour for each iteration. In reality, estimates need to be delivered before the project starts, and there is always pressure to hit that estimate number while being flexible with scope changes. I'm wondering what sort of real-word agile practices people have applied to the de-facto waterfall based billing/estimating that we sometimes get stuck in. Can you "break-in" a client to agile mid project, after you have acquired trust, or are there any other techniques to transition a client to agile. *side note: in my "real world" situation I run a recently founded development company that does not have the luxury of forcing clients to use our method and process. Many times we have to bend our backs to use theirs, but I see it as a burden all businesses face when starting. I'm wondering how best to deal with it.


Is it possible to use a "non-commercial" REST API in a for-pay app?

I am interested in integrating the results of 3rd-party news API's into my for-pay application. The APIs would be a very small part of the app (e. g. the app is not just reselling the APIs). I have found that many APIs such as Yahoo have "non-commercial" conditions like the following: > YOU SHALL NOT: Sell, lease, share, transfer, or sublicense the Yahoo! APIs > or access or access codes thereto or derive income from the use or provision > of the Yahoo! APIs, whether for direct commercial or monetary gain or > otherwise, unless the API Documents specifically permit otherwise or Yahoo! > gives prior, express, written permission... (from Yahoo Local Search API page) Does this prevent the API from being used as part of any app which costs money to use? For example, if I charge you to get into my site, and then display some content from this API, is that OK? If I let you see the content from the API for free, but then charge you to do something else on the site, is that OK? I'm obviously not expecting specific legal advice. Instead, I'd like to know about either: (1) a good reference on this topic that can answer my question (2) an "answer by example", i. e. an example of a real-world app that does something similar


Should a method do one thing and be good at it?

"Extract Till You Drop" is someting I've read in Uncle Bob's blog, meaning that a method should do one thing alone be good at it. **What is that one thing?** When should you stop extracting methods? Let's say I have a login class with the following methods:                public string getAssistantsPassword()      public string getAdministratorsPassword()      These retrieve the respective accounts password in the database. Then:                public bool isLogInOk()      The method compares the password that has been called or selected, and sees if the password the user provided is in the database. Is this an example of "Extract Till You Drop"? **When will you know when you are doing too much of extracting?**


Why are we supposed to use short functions to sectionalize our code?

I've seen an increasing trend in the programming world saying that it is good practice to separate code blocks into their own functions. Obviously, if that code block is reusable, you should do that. What I do not understand is this trend of using a function call as essentially a comment that you hide your code behind if the code is not reusable. That's what code folding is for. Personally, I also hate reading code like this because it feels like it has the same problem as the GOTO statement - it becomes spaghetti code where if I'm trying to follow the program's flow I'm constantly jumping around and can't logically follow the code. It is much easier to me to follow code that is linear but has a single comment over sections of code labeling what it does. With code folding, this is essentially the same exact thing, except the code stays in a nice linear fashion. When I try to explain this to my colleagues, they say comments are evil and clutter - how is a comment on top of a block of folded code any different from a function call that will never get called more than once? How is overusing functions different than overusing comments? How are frequent use of functions different from the problems with GOTO statements? Can someone please explain the value of the programming paradigm to me?


Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?

Lately I've been trying to split long methods into several short ones. **For example:** I have a `process_url()` function which splits URLs into components and then assigns them to some objects via their methods. Instead of implementing all this in one function, I only prepare the URL for splitting in `process_url()`, and then pass it over to `process_components()` function, which then passes the components to `assign_components()` function. At first, this seemed to improve readability, because instead of huge 'God' methods and functions I had smaller ones with more descriptive names. However, looking through some code I've written that way, I've found that I now have no idea whether these smaller functions are called by any other functions or methods. **Continuing previous example:** someone looking at the code might think that `process_components()` functionality is abstracted into a function because it's called by various methods and functions, when in fact it's only called by `process_url()`. This seems somewhat wrong. The alternative is to still write long methods and functions, but indicate their sections with comments. Is the function-splitting technique I described wrong? What is the preferred way of managing large functions and methods? **UPDATE:** My main concern is that abstracting code into a function might imply that it could be called by multiple other functions. **SEE ALSO:** discussions on reddit at /r/programming (provides a different perspective rather than most of the answers here) and /r/readablecode.


How to avoid peppering the code with IFs

I need to add a new payment type to an existing code base. That means that I'm going to have a few methods looking like this:               if (old payment type)         process old type of payment     else         process new type of payment      Now, if this could have been determined beforehand, I would have this method point to an interface implementing a common Pay method and then that interface would be implemented by one of two classes. Unfortunately, I only know which method the customer chooses at runtime, which means I need a way to determine which branch to use. Is there another way except for just having `if`s spread through the code?


Are too many if-else statements for validation bad?

From the book Professional Enterprise .Net, which has 5 star rating on Amazon that I am doubting after having a read through. Here is a Borrower class (In C# but it's pretty basic; anyone can understand it) that is part of a Mortgage application the authors built:                   public List<BrokenBusinessRule> GetBrokenRules()         {             List<BrokenBusinessRule> brokenRules = new List<BrokenBusinessRule>();                  if (Age < 18)                 brokenRules.Add(new BrokenBusinessRule("Age", "A borrower must be over 18 years of age"));                  if (String.IsNullOrEmpty(FirstName))                 brokenRules.Add(new BrokenBusinessRule("FirstName", "A borrower must have a first name"));                  if (String.IsNullOrEmpty(LastName))                 brokenRules.Add(new BrokenBusinessRule("LastName", "A borrower must have a last name"));                  if (CreditScore == null)                 brokenRules.Add(new BrokenBusinessRule("CreditScore", "A borrower must have a credit score"));             else if (CreditScore.GetBrokenRules().Count > 0)             {                 AddToBrokenRulesList(brokenRules, CreditScore.GetBrokenRules());             }                  if (BankAccount == null)                 brokenRules.Add(new BrokenBusinessRule("BankAccount", "A borrower must have a bank account defined"));             else if (BankAccount.GetBrokenRules().Count > 0)             {                 AddToBrokenRulesList(brokenRules, BankAccount.GetBrokenRules());             }             // ... more rules here ...             return brokenRules;         }      Full code listing on snipt.org . What is confusing me is that the book is supposed to be about professional enterprise design. Maybe I am a bit biased because the author confesses in chapter 1 that he didn't genuinely know what decoupling was, or what SOLID meant until the 8th year of his programming career (and I think he wrote the book in year 8.1) I am no expert but I don't feel comfortable with:   1. Too many if else statements.    2. The class both serves as an entity _and_ has validation. Isn't that a smelly design? (You might need to view the full class to get some context) Maybe I am wrong, but I don't want to pick up bad practices from a book which is supposed to be teaching an enterprise design. The book is full of similar code snippets and it is really bugging me now. If it _is_ bad design, how could you avoid using too many if else statements. I obviously do not expect you to rewrite the class, just provide a general idea of what could be done.


Style for control flow with validation checks

I find myself writing a lot of code like this:               int myFunction(Person* person) {       int personIsValid = !(person==NULL);       if (personIsValid) {          // do some stuff; might be lengthy          int myresult = whatever;          return myResult;       }       else {         return -1;       }     }      It can get pretty messy, especially if multiple checks are involved. In such cases, I've experimented with alternate styles, such as this one:               int netWorth(Person* person) {       if (Person==NULL) {         return -1;       }       if (!(person->isAlive))  {         return -1;       }       int assets = person->assets;       if (assets==-1)  {         return -1;       }       int liabilities = person->liabilities;       if (liabilities==-1) {         return -1;       }       return assets - liabilities;     }      I'm interested in comments about the stylistic choices here. [Don't worry too much about the details of individual statements; it's the overall control flow that interests me.]


Is it a good practice to write a method that gets something and checks the value?

Occassinally I have to write methods like this:               string GetReportOutputDirectoryAndMakeSureExist()     {         string path = Path.Combine ( ... ) //whatever logic          if(!Directory.Exists(path)) Directory.Create(path);         return path;     }      or               string GetAndVerifyExistenceOfReportConfigurationPath()     {         string path = Path.Combine ( ... ) //whatever logic to find the configuration         if(!File.Exists(path)) throw new Exception("Report configuration not found");         return path;     }      or               Customer GetCustomerAndVerifyActive(int id)     {         Customer customer = Db.GetCustomerById(id);         if(!customer.IsActive) throw new Exception("Customer is not active");         return customer;     }      Is it a good practice? I am told that it is normally not a good idea for a method to do more than one things, or for a method to have side-effects (like creating directory). But if I split, for example the last metod to GetCustomer(id) and VerifyActive(customer), I will have to do:               var customer = GetCustomer(id);     VerifyActive(customer);      consecutively at several places, and I think it counts as violation of DRY. Is this a good idea? Any idea how to help with the long method names?


How to do a clean refactoring of an If Else Code without leaving any free blocks?

if(condition1)     {        Statement1A;        Statement1B;     }     else if(condition2)     {       Statement2;     }     else if(condition3)     {       Statement3;     }     else      {        Statement1A;        Statement1B;     }             return;      I would like to refactor that code so that I do not duplicate Statements. I **always** need to check condition1 before any other condition. (So I cannot just change the order of the conditions). I also do not want to write `&&!condition1` after every other condition. I solved it like this               if(condition1)     {     }     else if(condition2)     {       Statement2;       return;     }     else if(condition3)     {       Statement3;       return;     }          Statement1A;     Statement1B;     return;      However I do not think an empty if condition will be easily understandable by others (even by me after a while). What is a better approach?


Until what point should I refactor?

What do you think until what point should a programmer refactor the code? Basically having               def method       do_something     end      Pieces of code would be handy, but they increase spaghetti code until the point where you have to remember the path of more than 8-10 methods. So wouldn't be easier to have no more than 3 methods spaghetti code, despite the fact that the method is longer than it suppose to be


Approaches to checking multiple conditions?

What is the best practice for checking multiple conditions, in no particular order? The example in question needs to check four distinct conditions, in any order, and fail showing the correct error message. The examples below use a C-like syntax. ## Option 1: Check all at once This method isn't preferred because the reasons why the condition failed aren't easy to discern.               if (A && B && C && D) {         // continue here...     } else {         return "A, B, C, or D failed";     }      ## Option 2: Nested Conditions In the past, I used to use nested conditional statements, like so. This can get really confusing.               if (A) {         if (B) {             if (C) {                 if (D) {                     // continue here...                 } else {                     return "D failed"                 }             } else {                 return "C failed";             }         } else {             return "B failed";         }     } else {         return "A failed";     }      ## Option 3: Fail-early This is the current method I use, which I like to call _fail-early_. As soon as a "bad" condition is hit, it returns.               if (!A) {         return "A failed";     }          if (!B) {         return "B failed";     }          if (!B) {         return "C failed";     }          if (!D) {         return "D failed";     }          // continue here...      # Option 4: Collect Errors One last approach I can think of is a sort of _collection_ of errors. If the conditions to test for are completely separate, one might want to use this approach.               String errors = "";     if (!A) {          errors += "A failed\n";     }          if (!B) {         errors += "B failed\n";     }          if (!C) {         errors += "C failed\n";     }          if (!D) {         errors += "D failed\n";     }          if (errors.isEmpty()) {         // continue here...     } else {         return errors;     }      What are the best practices for checking multiple conditions? In terms of expectations, it ideally behaves like example 4, where details of all the failures are returned.


Avoid Code Repetition in Condition Statements

I have been programming for over 15 years now. I consider myself a very good programmer, but I understand (like all of us) there are things that I need to work on. One of these things is code repetition when dealing with conditions. I will give a generic sample:               if(condition1)     {          //perform some logic          if(condition2)          {               //perform some logic               if(condition3)               {                    //Perform logic               }               else               {                    //MethodA(param)               }          }          else          {               //MethodA(param)          }     }     else     {          //MethodA()     }      Now, I cannot make it easy by doing the following:               if(condition1 && condition2)     {          }     else     {          }      I cannot do this since I need to perform some logic if condition1 is true and before I test condition2. Is there a way to structure if...else blocks to where if you need to call a method in each else blocks, you are not repeating yourself?


Eliminate duplicate code in nested IFs without creating a function

Let's say we have two ifs that depend on each other:               if var exists {         if var is array {             //Do stuff with var         } else {             //Resolve the problem         }     } else {         //Resolve the problem in the exact same way as above     }     //Continue execution with the assumption that var is in the appropriate state      How can I refactor this to remove the duplicated code without using gotos or functions/methods?


Refactoring into lots of methods - is this considered clean or not?

So, I watched as my colleague complained a bit about a project he has inherited from someone who is, shall we say, not very experienced as a programmer (intern left to his own devices on a project). At one point there was duplicate code, about 7-8 lines of code duplicated (so 14-16 lines total) in a method of say 70-80 lines of code. We were discussing the code, and he spotted a way to refactor this to remove the duplication by simply altering the structure a bit. I said great, and then we should also move the code out to a separate method so the large method gets a little more readable. He said 'no, I would never create a method for just 7-8 lines of code'. Performance issues aside, what are **your** input on this? Do you lean against using more methods (which in c# pads code with about 3 lines) or larger methods, when that particular code will probably not be used anywhere else? So it is purely a readability issue, not a code-reuse one. Cheers :)


How would you refactor nested IF Statements?

I was cruising around the programming blogosphere when I happened upon this post about GOTO's: http://giuliozambon.blogspot.com/2010/12/programmers-tabu.html Here the writer talks about how "one must come to the conclusion that there are situations where GOTOs make for more readable and more maintainable code" and then goes on to show an example similar to this:               if (Check#1)     {         CodeBlock#1         if (Check#2)         {             CodeBlock#2             if (Check#3)             {                 CodeBlock#3                 if (Check#4)                 {                     CodeBlock#4                     if (Check#5)                     {                         CodeBlock#5                         if (Check#6)                         {                             CodeBlock#6                             if (Check#7)                             {                                 CodeBlock#7                             }                             else                             {                                 rest - of - the - program                             }                         }                     }                 }             }         }     }      The writer then proposes that using GOTO's would make this code much easier to read and maintain. I personally can think of at least 3 different ways to flatten it out and make this code more readable without resorting to flow-breaking GOTO's. Here are my two favorites. 1 - Nested Small Functions. Take each if and its code block and turn it into a function. If the boolean check fails, just return. If it passes, then call the next function in the chain. (Boy, that sounds a lot like recursion, could you do it in a single loop with function pointers?) 2 - Sentinal Variable. To me this is the easyest. Just use a blnContinueProcessing variable and check to see if it is still true in your if check. Then if the check fails, set the variable to false. How many different ways can this type of coding problem be refactored to reduce nesting and increase maintainability?


Making some methods mostly contain method calls, while others doing "the lowest level" work

So I thought about this, and I don't know if it's included or not in any methodology. I think the advantages of this coding style is that, at the lowest level, the code is extremely testable, and then the integration tests should also be very easy to build. I also think this would make the code more readable and the UML would be understood faster. So here's my example:               class CoolObject{     var member1; //needed for instance in lifecycle events     var member2; //same comment             //This method could be for instance an event handler        //Notice this contains only assignments and method calls. No library calls or lower level stuff        [public] method high_level(params...){          var local_var1;         var local_var2;         local_var1 = call method lower_level1(param1,param2);         local_var2 = call method lower_level2(param1, local_var1);         member1 = call method lower_level3(local_var2);        }             //Notice this contains only library calls and lower level processing        [private] method lower_level1(param1, param2){         return param1 + param2 + libraryXXY123.function142(current_date);        }             //Notice this contains only library calls and lower level processing        [private] method lower_level2(param1, param2){          var return_value;          loop over param2{             if(condition){                add param1 to return_value;             }          }          return return_value + libraryASDF123.function3132(system_user);             }          }      Please note that this is not written in any specific language, as I only wanted to illustrate the concept. So do you know some methodologies that use this, or that warn against it? Please elaborate on the answer, as I think this would be a good idea, and would like this either confirmed, or the opposite.


How to tackle a 'branched' arrow head anti-pattern?

I recently read this question that features, the arrow anti-pattern. I have something similar in code I'm trying to refactor except that it branches. It looks a little something like this:               if(fooSuccess==true&&barSuccess!=true){         if(mooSuccess==true){                .....         }else if (mooSuccess!=true){                .....         }     }else if(fooSuccess!=true&&barSuccess==true){         if(mooSuccess==true){                .....         }else if (mooSuccess!=true){             if(cowSuccess==true){                         .....             }else if (cowSuccess!=true){                         .....             }         }     }     ......      In short it looks like this               if        if          if            if              do something            endif         else if          if            if              do something             endif         endif         else if          if            if              do something             endif         endif      endif      Outline borrowed from Coding Horror article on the subject And the code goes on through different permutations of true and false for various flags. These flags are set somewhere 'up' in the code elsewhere, either by user input or by the result of some method. How can I make this kind of code more readable? My intention is that eventually I will have a Bean-type object that contains all the choices the previous programmer tried to capture with this branching anti-pattern. For instance, if in the outline of the code above we really do only have three, I have an enum set inside that bean:               enum ProgramRouteEnum{         OPTION_ONE,OPTION_TWO,OPTION_THREE;              boolean choice;         void setChoice(boolean myChoice){             choice = myChoice;         }         boolean getChoice(){             return choice;         }     }      Is this an acceptable cure? Or is there a better one?


Using Functions for Never-Repeated Code

What are some best practices for using functions to break up large blocks of code into discrete chunks of logic when those functions are only ever going to be used once within the lifetime of a function? The canonical example for web development is the initialization of a home page. When the page loads, you might do something like check some credentials and authentication, make an API call to get some data, and parse that data. Naturally, this could all be written in a procedural format within a large function called initialize(). None of the logic will foreseeably be re-used anywhere else within the program. When I'm confronted with such scenarios, my initial instinct is to divide each piece of logic into a discrete function and simply call the functions from an initialize() function, with a few lines of code within initialize() performing some clean up and tear down duties. So I'd have something like an authenticate(), get_data(), and parse_data() function, as well as perhaps a few helper functions for the main functions. In my opinion, that makes the code easier to understand from a high level, makes unit tests more meaningful, and helps organize your thinking as you're writing your code. However, I recently clashed with a guy who essentially thinks the opposite. He feels too many functions lead to "annoying jumping around", functions should never be used if code is not going to be re-used, and that the over-use of functions/classes/modules/any kind of modularity amounts to over-engineering. I was put off by his argument and felt that it leads to the shitty procedural PHP that so often makes web development a nightmare, but perhaps there is some validity in what he's saying?


Should I repeat condition checking code or put it in a function?

I have a bunch of calls to a method that may or may not need to be made depending on whether certain features are enabled or not. As such, I've wrapped these calls in `if` blocks checking the enabled statuses. The arguments to the method in each of these calls use some long variable names, so I've broken them out into different lines for readability / to adhere to our line-length coding standard. These large method-call blocks, combined with the condition checks to see if they should be run (exacerbated by the mandate that we enclose all `if` blocks in braces), are quite noisy. So I have something like this:               if (FeatureSettings.FeatureXIsEnalbed)     {         this.TheMethodImCalling(             FeatureSettings.ReallyLongFeatureXSettingAName,             FeatureSettings.ReallyLongFeatureXSettingBName,             ...);     }          if (FeatureSettings.FeatureYIsEnalbed)     {         this.TheMethodImCalling(             FeatureSettings.ReallyLongFeatureYSettingAName,             FeatureSettings.ReallyLongFeatureYSettingBName,             ...);     }          if (FeatureSettings.FeatureZIsEnalbed)     {         this.TheMethodImCalling(             FeatureSettings.ReallyLongFeatureZSettingAName,             FeatureSettings.ReallyLongFeatureZSettingBName,             ...);     }      To reduce the noise and redundancy in this code I was thinking of taking the `if` block structure and putting it _inside_ `TheMethodImCalling`, then passing in the `...IsEnabled` value along with the rest of the arguments. This seems somewhat silly though as I would effectively be calling the method and telling it "Don't do anything." when a feature wasn't enabled. Now, I could probably make the code a bit more readable by assigning the long settings to shorter temporary variables or even fields of an `Arguments` class that I would then pass to the method, but those don't address the core question: **Should I repeat the condition checking code or put it in the function?** Or is there an alternative I should consider? (Both options seem somewhat smelly...)


Which is a better pattern (coding style) for validating arguments - hurdle (barrier) or fence?

I don't know if there are any accepted names for these patterns (or anti- patterns), but I like to call them what I call them here. Actually, that would be **Question 1:** What are accepted names for these patterns, if any? Suppose there is a method that accepts a bunch of parameters, and you need to check for invalid input before executing actual method code:               public static void myMethod (String param1, String param2, String param3)      ## Hurdle Style I call it so because it's like hurdles a track runner has to jump over to get to the finish line. You can also think of them as conditional barriers.               {         if (param1 == null || param1.equals("")) {             // some logging if necessary             return; // or throw some Exception or change to a default value         }              if (param2 == null || param2.equals("")) {             // I'll leave the comments out             return;         }              if (param3 == null || param3.equals("")) {             return;         }              // actual method code goes here.     }      When the checks are for a certain small section in a larger method (and the section cannot be moved to a smaller private method), labelled blocks with `break` statements can be used:               {         // method code before block              myLabel:         {             if (param1 ... // I'll leave out the rest for brevity                 break myLabel;             if (param2 ...                 break myLabel;             ...                  // code working on valid input goes here              } // 'break myLabel' will exit here              // method code after block     }      ## Fence Style This surrounds the code with a fence that has a conditional gate that must be opened before the code can be accessed. Nested fences would mean more gates to reach the code (like a Russian doll).               {         if (param1 != null && !param1.equals("")) {             if (param2 != null && !param2.equals("")) {                 if (param3 != null && !param3.equals("")) {                          // actual method code goes here.                      } else {                     // some logging here                 }             } else {                 // some logging here             }         } else {             // some logging here         }     }      It could be re-written as follows too. The logging statements are right beside the checks, rather than being after the actual method code.               {         if (param1 == null || param1.equals("")) {             // some logging here              } else if (param2 == null || param2.equals("")) {             // some logging here              } else if (param3 == null || param3.equals("")) {             // some logging here              } else {                  // actual method code goes here.              }     }      **Question 2:** Which style is better, and why? **Question 3:** Are there any other styles? > I personally prefer _hurdle style_ because it looks easier on the eyes and > does not keep indenting the code to the right every time there's a new > parameter. It allows intermittent code between checks, and it's neat, but > it's also a little difficult to maintain (several exit points). > > The first version of _fence style_ quickly gets really ugly when adding > parameters, but I suppose it's also easier to understand. While the second > version is better, it can be broken accidentally by a future coder, and does > not allow intermittent code between conditional checks.


Is this pattern bad?

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?


How to handle complex conditions?

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?


calling methods if previous call success

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?


One-line functions that are called only once

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...


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

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        }     }


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

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?**


Always pull out common cases and branch separately?

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?


What does (Lua) game scripting mean?

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?


Reconstruct a file from a TCP stream

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)


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

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?


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

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?


Which Internet places are popular for commercial Java product announcements?

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?


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

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


randomized management?

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


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

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.


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

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_


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

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.


Javascript behavior depends only on browser or browser + OS?

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.


How do most sync programs monitor file changes?

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?


Idea of the binary search main theorem

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?


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

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?


Which design pattern would be best for this case?

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?


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

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?


DDD - Domain Object calling a web service

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.


Can I use select2 in my website?

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.


What is the best way to construct your CSS documents?

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...


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

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.


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

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 :)


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

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)?


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

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?


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

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?


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

**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...


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

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.


Should UTF-16 be considered harmful?

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?


Clarification of pseudo random number generator

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?


What's better than outputdebugstring for windows debugging?

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?


REST and redirecting the response

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?


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

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?


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

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++?


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

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?


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

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?


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

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" :)


Daily Scrum Meeting (Burndown chart)

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?


Fast Learning: Is it bad?

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 ??


Is exception handling a cross-cutting concern?

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.


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

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


Java Application for handling records(CRUD)

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. ?


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

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.


Is this awkward spacing some type of style?

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?