title: Extending a struct. Using helper classes rather than composition

text: I have a struct which I want to add static methods to. Yes, you guessed right I'm talking about `Datetime`. It's a pretty typical requirement to add MyCustomParse. It happens to return `Datetime?`, so it's not a constructor, but it's in that area, a static method that returns an instance. The content of this method has already been written and currently happy lives as a instance method of a class that uses it. I want to bring it out of that class so I can use it elsewhere. Traditionally I would put it in a **helper class** (which is what I've done here), but apparently they're evil. What I really want to do is tie `Datetime.MyCustomParse(mystring)`. But the only way I can see is **to make a new struct that composes`Datetime`**. I then add in my method, write the implicit conversions and then put in all the other `Datetime` methods etc. **This would be a pain to code** (Being verbose also causes problems wrt xml docs and naive code coverage metrics, if that counts for anything). I have considered **extension methods** , but I don't think the methods make sense on instances. **What is the strict OO position? Do I get a pass on writing methods that should belong to classes in separate helper classes** when I want to extend structs in this fashion? **What is the pragmatic position** (I'm not saying OO isn't pragmatic), is this code you would write, or have I missed a trick?               internal static class DateTimeHelper     {              public static DateTime? MyCustomParse(string utcDateTimeText, string[] formats)         {             DateTime utcDateTime;             if (DateTime.TryParseExact(utcDateTimeText, formats, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out utcDateTime))             {                 return utcDateTime;             }                  return null;         }     }      PS I know there are more nuanced views on helper classes, but I still feel I need to justify my use here.


title: "positively formulated" vs. "reads as english sentence" style logic

text: Sorry, I'd be happy to have someone improve the title of this question. What are the benefits and downsides of "positively formulated" logic vs. having it "english readable". I'm looking for a generic position that can be placed into code guidelines. Examples of what I see as "positively formulated" logic               if ($obj->isValid()){               if ($found){                    if ($first){         //do nothing     }else{         doX();     }          $this->useFields(array('a','b'));      Examples of what I see as "negatively formulated" logic               if (!$first)         doX();     }          $this->unset(array('d','e','f','g'));      Whereas if focusing on "English readable" I would see this as good:               if (isValid()){                         if ($found){      and this is not "English readable"               if ($l){                    if (isValid() || !isActive()){         doX();     }


title: Practical considerations for HTML / CSS naming conventions (syntax)

text: **Question:** _what are the practical considerations for the syntax in`class` and `id` values?_ Note that I'm not asking about the _semantics_ , i.e. the actual words that are being used, as for example described in this blogpost. There are a lot of resources on that side of naming conventions already, in fact obscuring my search for practical information on the various _syntactical_ bits: casing, use of interpunction (specifically the `-` dash), specific characters to use or avoid, etc. To sum up the reasons I'm asking this question:   * The naming _restrictions_ on id and class don't naturally lead to any conventions   * The abundance of resources on the semantic side of naming conventions obscure searches on the syntactic considerations   * I couldn't find any authorative source on this   * There wasn't any question on SE Programmers yet on this topic :) * * * Some of the conventions I've considered using:   1. `UpperCamelCase`, mainly as a cross-over habit from server side coding   2. `lowerCamelCase`, for consistency with JavaScript naming conventions   3. `css-style-classes`, which is consistent with naming of css properties (but can be annoying when Ctrl+Shift+ArrowKey selection of text)   4. `with_under_scores`, which I personally haven't seen used much   5. `alllowercase`, simple to remember but can be hard to read for longer names   6. `UPPERCASEFTW`, as a great way to annoy your fellow programmers (perhaps combined with option 4 for readability) And probably I've left out some important options or combinations as well. So: what considerations are there for naming conventions, and to which convention do they lead?


title: What is the Best Practice for creating a secure login in a client - server appllication?

text: It's been a while I have been thinking on what could be the best scenario for creating a secure login in a client-server application running on internet or any other networks ! So I became with the idea to ask this question on programmers and I hope that this question will make awareness of new aspects of threads and security here by some kind of brain storming , I am really interested in good and new anseawres . Thanks in advance for your participation .


title: What do I need to know re. Javascript frameworks?

text: I recently asked this question on SO, which quickly became downvoted and closed. Clearly I lack a deeper understanding of JS, which I'm hoping you'll help me fill here. I'm a perfectly capable web developer and have built plenty of visually and functionally pleasing websites but am struggling to get to grips with how I should be handling JS. Up until now, I've only really used jQuery for form validation or providing AJAX functionality to forms/other page elements. There seems to be a lot of hype around JS frameworks - backbonejs, emberjs, etc, but when I look into them, it looks like they're just good for if you intend to build full applications in them. I'm happy using PHP/Symfony and just want to use JS to give my web applications a nice interactive/responsive 'feel'. Are the aforementioned frameworks any use to me, or am I right in just sticking with jQuery?


title: Experience w/ eLance (and similar sites)

text: I'm considering freelancing via eLance.com (or another similar site) to help pay the bills while developing games (that will eventually pay the bills). **What's working through elance like?** Any recommendations or strategies? Any feedback is appreciated.


title: How can I best study a problem to determine whether recursion can/should be used?

text: In some cases, I fail to see that a problem could be solved by the divide and conquer method. To give a specific example, when studying the find max sub- array problem, my first approach is to brute force it by using a double loop to find the max subarray. When I saw the solution using the divide and conquer approach which is recursion-based, I understood it but ok. From my side, though, when I first read the problem statement, I did not think that recursion is applicable. When studying a problem, is there any technique or trick to see that a recursion based (i.e. divide and conquer) approach can be used or not?


title: how much time do you spend on Unit testing?

text: In a company I used to work for, executives insisted that the code coverage with unit tests must be 99% or more. This resulted in writing more tests than code. It took us literally 3 days to write tests for a single class that took a day to implement. As a result, however, I learnt a lot about TDD, testing tools, practices etc. In the company I worked for afterwards, unit testing was an unknown thing. It was something someone maybe heard before. I struggled to introduce them to concept of unit testing, but without effect. Now, as a self-employed, I wonder - how much time is **really** necessary to spend on unit testing? Being mostly iPhone/Android developer, which parts of the code should be covered in tests?


title: Is NAN suitable for communicating that an invalid parameter was involved in a calculation?

text: I am currently working on a numerical processing system that will be deployed in a performance-critical environment. It takes inputs in the form of numerical arrays (these use the `eigen` library, but for the purpose of this question that's perhaps immaterial), and performs some range of numerical computations (matrix products, concatenations, etc.) to produce outputs. All arrays are allocated statically and their sizes are known at compile time. However, some of the inputs _may_ be invalid. In these _exceptional_ cases, we still want the code to be computed and we still want outputs not "polluted" by invalid values to be used. To give an example, let's take the following trivial example (this is pseudo- code):               Matrix a = {1, 2, NAN, 4}; // this is the "input" matrix     Scalar b = 2;     Matrix output = b * a; // this results in {2, 4, NAN, 8}      The idea here is that 2, 4 and 8 are usable values, but the NAN should signal to the recipient of the data that that entry was involved in an operation that involved an invalid value, and should be discarded (this will be detected via a `std::isfinite(value)` check before the value is used). Is this a sound way of communicating and propagating unusable values, given that performance is critical and heap allocation is not an option (and neither are other resource-consuming constructs such as `boost::optional` or pointers)? Are there better ways of doing this? At this point I'm quite happy with the current setup but I was hoping to get some fresh ideas or productive criticism of the current implementation.


title: Models, collections...and then what? Processes?

text: I'm a LAMP-stack dev who's been more on the JavaScript side the last few years and really enjoying the Model + Collection approach to data entities that BackboneJS, etc. uses. It's helped me organize my code in such a way that it is extremely portable, keeping all my properties and methods in the scope (model, collection, etc.) in which they apply. One thing that keeps bugging me though is how to organize the next level up, the 'process layer' as you might call it, that can potentially operate on instances of either models or collections or whatever else. Where should methods like find() (which returns a collection) and create() (which returns a model) reside? I know some people would put a create() in the Collection prototype, but while a collection operates on models I don't think it's exactly right to create them. And while a find() would return a collection I don't think it correct to have that action within the collection prototype itself (it should be a layer up). Can anyone offer some examples of any patterns that employ some kind of OOP- friendly 'process' layer? I'm sorry if this is a fairly well-known discussion but I'm afraid I can't seem to find the terminology to search for.


title: Why is Big O taught instead of Big Theta?

text: Big O notation provides an **upper bound** to a function whereas Big Theta provides a tight bound. However I find that Big O notation is typically (and informally) taught and used when they really mean Big Theta. e.g. "Quicksort is O(N^2)" can turned into the much stronger statement "Quicksort is Θ(N^2)" While usage of Big O is technically correct, wouldn't a more prevalent use of Big Theta be more expressive and lead to less confusion? Is there some historical reason why this Big O is more commonly used? Wikipedia notes: > Informally, especially in computer science, the Big O notation often is > permitted to be somewhat abused to describe an asymptotic tight bound where > using Big Theta Θ notation might be more factually appropriate in a given > context.


title: Message Passing: How to detect and/or handle "dead ends"

text: I'm playing with a mental model for distributed actor system that communicates using messages. In this, it is possible for an actor to create another actor. I've encountered one specific situation where I'm not really sure how to resolve. Consider this sequence of events:   1. Actor 1 requests creation Actor 2. As part of the "construction", it passes its own ID.   2. Actor 1 requests its own deletion.   3. System sends KILL message to all Actors who subscribed to {Actor1|KILL}   4. Actor 2 is created, saves ID of "1" sent to it as construction parameter.   5. Actor 2 attempts to send a message to Actor 1.   6. ???   7. Actor 2 detects that Actor 1 is gone, and reacts. Since Actor 1 and 2 can be on physically different machines, querying "Does Actor X exist?" every time (or before every time) you attempt to send a message will introduce latency that shouldn't be there in the typical case. Similarly, blocking until you know "Send Success" or "Send Fail" seems like a bad idea. It also seems that litering code with `if(send() == fail) { ... }` is ugly and error-prone. Are there known solutions for robustly and cleanly handling these sorts of situations?


title: Is there an advantage for a C programmer to have read K&R?

text: This question has been haunting me because I'm now reading Kernighan & Ritchie's: The C Programming Language (K&R) but I meet a lot, and I mean A LOT, of C programmers that have never read it. So, my question is: Is there an advantage to reading K&R? Should be a necessity?


title: Online error reporting without network access

text: I have developed an application for android requiring no permissions, but the biggest downside of this is that I don't have error reporting. So, I was playing around for the past week with any alternative options which would allow error reporting without network permissions and without privacy risks. So I came up with the following: Errors could be reported through a custom Google Play API, but would only be displayed once more than n users would have triggered the same error and displayed only in the aggregate sense. This (I believe) would prevent exploitation where an app could use this as a method to communicate private data. N would be defined by something along the lines of `max(10,number_of_users * 0.001)` or something along those lines. So my question is, would such an architecture be safe or am I overlooking possible exploits? If not it seems a huge waste android lacks such an API as right now virtually every app requires network access for exactly this reason. A similar API could then also be used for rudimentary statistics, once again without the up and downsites of user identifiable analytics like with Google Analytics for android.


title: Liskov substitution principle when implementing two unrelated interfaces

text: Suppose I have two unrelated interfaces with the same method:               interface Table {         /**          * @param width (0 < width <= 100)          */         void setWidth(int width);     }          interface Square {         /**          * @param width (50 <= width <= 10000)          */         void setWidth(int width);     }      Then I create a class which implements both of these interfaces:               class SquareTable implements Square, Table {         void setWidth(int width) {             precondition = ...             if (!precondition)                 throw new PreconditionFailedException("Precondition failed: ...");         }     }      How precondition expressions should be combined to satisfy Liskov substitution principle? Should they **and** 'ed or **or** 'ed? I.e. what should be written instead of `...`:               width > 0 && width <= 10000 // using OR     width >= 50 && width <= 100 // using AND      And which rule should be used for postconditions?               interface Table {         /**          * @return width (0 < width <= 100)          */         int getWidth();     }          interface Square {         /**          * @return width (50 <= width <= 10000)          */         int getWidth();     }          class SquareTable implements Square, Table {         int getWidth() {             postcondition = ...             if (!postcondition)                 throw new PostconditionFailedException("Postcondition failed: ...");         }     }          width > 0 && width <= 10000 // using OR     width >= 50 && width <= 100 // using AND


title: What are the prerequisites for learning Go

text: I am considering learning Go. As far as I know about it, it's a systems language geared toward parallel programming. (correct me if I'm wrong)   * Should I have a very good understanding of C in order to be good Go programmer?   * How much systems concepts (*nix OS concepts) I need to master before delving into Go   * What other things I should know/learn before starting Go


title: Acceptable dependencies in a service-oriented architecture, internal to a team

text: In a service-oriented architecture, subsystems can depend on each other in different levels:   1. Database level => Foreign keys to enforce data integrity across services on deletions and updates (cascade), and views which use tables from other services to increase performance   2. Code reuse => like DLL references in .NET platform, to reduce the amount of code, and to follow DRY   3. Service usage => To enforce business centralization; Each service can use any other service in a mesh-like scheme   4. UI reuse => To facilitate consistency in UI and take UX higher Which of these dependencies are encouraged and which are not?


title: Coding style for chained function calls

text: A common thing you need to do is to take a value, do something with it by passing it to a function, and then do some more with the return value, in a chain. Whenever I run into this type of scenario, I get unsure about how best to write the code. As an example, let's say I have a number, `num`, and need to take the floored square root of it and turn it into a string. Here are a few possibilities (in JavaScript). I might simply pass `num` to one function at a time, and replace `num` with the return value:               function floorSqrt(num) {         num = Math.sqrt(num);         num = Math.floor(num);         num = String(num);         return num;     }      This is nice since I don't need the original `num` any more, but in practice it might be confusing to start with one thing (a number) and end up with something completely different (a string). I can save each step in a new variable:               function floorSqrt(num) {         var sqrtNum = Math.sqrt(num);         var floorSqrt = Math.floor(sqrtNum);         var stringNum = String(floorSqrt);         return stringNum;     }      Although it seems wasteful to declare all those variables and come up with good names for them. Or I can just do it all as a one-liner:               function floorSqrt(num) {         return String(Math.floor(Math.sqrt(num)));     }      But for more than two functions that approach gets incredibly unreadable, almost like code golf. It seems to me like the most beautiful way to do this would be with some stack-based language, which might look something like this (pseudo code):               [sqrt floor toString]      Is there a way to do something similar with JavaScript? List some functions, run one at a time, and use the return value of each one as the argument for the next? The closest is how some libraries like jQuery or Underscore.js allow you to chain methods, something like this:               function floorSqrt(num) {         return _.chain(num).sqrt().floor().toString().value();     }      I'm sure many wise people have thought wise things about this. What are some thoughts on pros and cons of the different styles?


title: Should a persisted and 'finished' by state transaction be editable to any user

text: This question has been bugging me for a while. I came from a background where I taught that when a transaction reached some state (FINISHED, PRINTED, etc) it should no longer be opened for modification even to admin users. But here I am, fixing their human-input error barbarically by deleting a row in database and/or changing the current item's state to it's previous one. At some point they even make a mistake in inputting a transaction date, and just realized it somewhere later. And it's really annoying. Should a software, especially an enterprise one, gives a user all the freedom they requested? If so, what good does a transaction state for? Update : Here, by transaction I mean a Transaction object which usually consisted a reference to Master object and it's own attributes, not database transaction.


title: Do you have regularly schedule app updates? And if so how do you handle bugs that make it out?

text: We are trying to make our releases more frequent. As part of that we have blocked out a day of the week where we told users that we'll be doing updates. Similar how Microsoft has Patch Tuesday. This is for a web app running completely server side, by the way. So updates are not a huge problem to deploy. Though they can get time consuming. Occasionally an update has a bug that needs to be fixed before the next update window rolls around. I see two real options: either undo the update and restore a backup of the previous version, or make a fix and deploy it outside the scheduled time. Making a fix sounds easy, but often times there are other changes that have been made to the code base. And the fix needs testing before it can realistically go out. Rolling back isn't a bad option, but sometimes that will remove recent features or at least delay them until the next week.


title: Software markets for solo developer

text: I want to create something useful of my own which others can use it. This can be free or it can make a little money for sustaining its development and increase income little. However, when think about the market, I don't know what market is lacking applications, what types of domain can be possible for a solo developer or small development? For example, I can develop small game for the smartphone market, with me as the programmer, another person is graphic designer and another person is music composer, to create a functional and playable game. Or what types of domain/market in web development are possible for a single developer to produce a web application? Or should I include the forth person, business man to identify this for me? If you have experience on this, I would love and highly appreciate if you share for me and everyone. _EDIT:_ I want to do this as my part time job, not the main job until it's possible.


title: Change of the complexity class through compiler optimization?

text: I am looking for an example where an algorithm is apparently changing its complexity class due to compiler and/or processor optimization strategies.


title: What default features is Windows missing that are required for programmers?

text: What features is Windows missing that can improve the productivity of a programmer. I know a lot of people would want some features from Linux and OSX ported or being created for Windows as well. What is missing for you ? An example would be the option to have multiple workspaces. When not having the possibility to use dual monitors that can come in handy.


title: One language to rule them all? (Them being platforms.)

text: I have been discussing a project with a client and they want to use a single language to deploy to as many platforms as possible. (I am not sure that it's such a good idea, because each platform offers a different user experience and UI metaphor. In some cases, screen sizes vary as well. Also, iPhone is out of the running no matter what language we use. But, I digress...) The project is going to display an arbitrary block of text each day and will track if the user has "read" it. Some other features on the table are "nags" and the ability to go to another days' text. I know Flash from the CS3 days, and I think that translates into AIR, but I dont know if AIR can do what we want. On the other hand, I have (a) little experience with Java or Python, but those seem like good contenders also. Which language should I use here? Why? **Edit:** This is going to run on desktop platforms too.


title: A design decision in composition or aggregation

text: I've recently had doubts about some design decisions that I frequently make, so this time I decided to take some time and try to analyze it to find the best solution. I will describe a simple scenario where the design decision can be easily understood. :) Suppose we are developing a game in Java where players can have any number of many different types of items.               /** Class that represent an item type existing in the game */     // you may prefer to call this ItemType,     // but for me appending the word "Type" is not necessary     class Item {         private String descrip;         private Image icon;     }      In this situation I need to keep track of how many of each item the player has in his bag, so I keep a collection of them, in each element of which I have item type and quantity. Additionally one can think of other attributes that belong to that relation (perhaps a max capacity), but the question is: how do I model this scenario in general but with a practical implementation in Java? Here are two approaches I've come up with: ### Using a List               class Slot {         private Item item;         private int quantity;              /** Auto generated */         public int hashCode()         {             int hash = 7;             hash = 13 * hash + (this.item != null ? this.item.hashCode() : 0);             return hash;         }              /** This method is also auto generated and just compares the Item,              independent of quantity */         public boolean equals(Object object)          {             if (!(object instanceof Slot))             {                 return false;             }             Slot other = (Slot) object;             if ((this.item == null && other.item != null)                   || (this.item != null && !this.item.equals(other.item)))             {                 return false;             }                  return true;         }     }      The above class relates one item with a quantity, and a collection of `Slot`s is the primary attribute of the `Inventory` class. The disadvantages of this appear as soon I design the `Inventory` interface to not expose `Slot` to the client (making `Slot` private or hiding it in some other way): in creating a simple interface but providing access to all the standard collection methods. In my humble opinion there is nothing wrong with this:               /** Class that represent the bag that holds the player's items */     class Inventory {        // this collection holds only one element for each type of item        private ArrayList<Slot> slots;               public Inventory()         {             slots = new ArrayList<Slot>(10);         }              public void add(Item item, int quantity)         {             Slot slot = new Slot(item, quantity);             // if we don't already have a Slot for the added Item, add it             if (!slots.contains(slot))             {                 slots.addElement(slot);             }             // if we already have a Slot for the added Item, increase the quantity             else             {                 Slot _slot = slots.elementAt(slots.indexOf(slot));                 _slot.addQuantity(quantity);             }         }              public void subtract(Item item, int quantity)         {             Slot slot = new Slot(item, 0);              int index = slots.indexOf(slot);                  // only if we actually have this item             if (index != -1)              {                 Slot _slot = (Slot) slots.elementAt(index);                 _slot.quantity -= quantity;                      // if we have fewer of the Item than the number to remove,                  // remove the slot from the collection                 if (_slot.quantity <= 0)                 {                     slots.removeElementAt(index);                 }             }         }              public void remove(Item item)         {             Slot slot = new Slot(item,0);             slots.removeElement(slot);         }              public boolean hasItem(Item item)         {             Slot slot = new Slot(item,0);             return slots.contains(slot);         }     }      As you see, we have to jump through some hoops to implement certain collection methods: in `hasItem` we have to create a `Slot` element just for that operation. In the add and subtract methods, we have to create the `Slot` object just to check if it's there. I wonder if this really necessary. I suppose that it is if we desire to provide an interface to the standard collection methods. Perhaps we can move all this logic to another class (for example: `Slots`), exposing a cleaner interface that lets us search by item without the need of creating a Slot, but we are just moving the same problem to another class. We will face the same problem there, besides the fact that `Inventory` is basically a set of `Slot`s, we're really just creating another class to be exactly the same thing, which doesn't make a lot of sense to me. Would it be more correct to change the interface of this class to work directly with `Slot` class instead? This implies moving from composition (having `Slot`s created within Inventory) to an aggregation (having `Slot` creation outside of Inventory). The result might look like:               /** Class that represent the bag that holds the player's items */     class Inventory {        private ArrayList<Slot> slots;              public Inventory()         {             slots = new ArrayList<Slot>(10);         }              public void add(Slot slot)         {             if (!slots.contains(slot))             {                 slots.addElement(slot);             }             else             {                 Slot _slot = slots.elementAt(slots.indexOf(slot));                 _slot.addQuantity(slot.getQuantity());             }         }              public void subtract(Slot slot, int quantity) // how would the client get the Slot?         {             int index = slots.indexOf(slot);                  // only if we actually have this item             if (index != -1)              {                 Slot _slot = (Slot) slots.elementAt(index);                 _slot.quantity -= quantity;                      // if we have fewer of the Item than the number to remove,                  // remove the slot from the collection                 if (_slot.quantity <= 0)                 {                     slots.removeElementAt(index);                 }             }         }              public void remove(Slot slot) // again, how would the client get the Slot?         {             slots.removeElement(slot);         }              // Hard to change a parameter type here. This strongly suggest there is         // a flaw in the design. I only keep this here to communicate the observation         public boolean hasItem(Item item)          {             Slot slot = new Slot(item, 0); // here we have no choice but to create it             return slots.contains(slot);         }     }      But again, is this convenient? I don't often put this approach into practice, so I'm not sure. ### Using a lookup Another approach is to use something like a Hashtable with `Item` objects as keys quantities as values, so only quantity is associated with Items, without the need for a `Slot` class. An `Inventory` implementation using Hashtable might look like:               public class Inventory     {         private Hashtable items;              public Inventory()         {             items = new Hashtable(10);         }              public void add(Item item, int amount)         {             int stock = amount;             if (items.containsKey(item))             {                 stock += ((Integer) items.get(item)).intValue();             }             items.put(item, new Integer(stock));         }              public void subtract(Item item, int amount)         {             if (items.containsKey(item))             {                 int stock = ((Integer) items.get(item)).intValue();                 stock -= amount;                 if (stock > 0)                 {                     items.put(item, new Integer(stock));                 }                 else                 {                     items.remove(item);                 }             }         }              public void remove(Item item)         {             this.items.remove(item);         }              public boolean hasItem(Item item)         {             return this.items.containsKey(item);         }     }      To me this seems much better than using a List because there is no need of the `Slot` class, and all interactions with the `Item` collection are much simpler, but I'm not sure if I'm right. The same type of problem is also evident in this scenario: Suppose that we are implementing an order application for a pizza shop; every order consists of types of pizzas and quantities.               /** Type of pizza */     class Pizza {         private String descrip;         private Image icon;     }          /** Customer request for pizza */     class Request {         // for each type of pizza we have to keep a count of how many the customer ordered     }          /** A pizza order */     class Order {         private Pizza pizza;         private int   amount;         privete BigDecimal price;     }      Knowing how to solve the first problem, I have a pattern to use for this similar situation; so the question is, what solution is best? I try to convince myself that I'm not the only person with this concern, that ordinary people like me face this problem on a regular basis, so I hope to find how other people solve this problem. On the other hand, I know that this question is quite big and maybe a little elaborate, so maybe I need to split it into several more specific questions. Maybe the answer to this problem is simple I'm over-complicating things, or even worse, my doubts about how to handle this situation arise because I really don't understand some basic design principle, like a captain on a ship using a spyglass in order to sight land but doesn't realize that his ship has been beached on solid ground that was close at the moment he draw his spyglass to look. Okay, enough cheap poetry (but it was hard to describe my feelings without it hehehe). I apologize for the length of the question, and would very much appreciate anyone's help with this problem.


title: Want to know performance issues of Class types & access modifiers

text: Someone suggested me to mark classes as SEALED that are not being inherited anywhere. I was using default style and was not concerned with the type of class. At present I don't have a benchmark tool to study the performance gains but read somewhere that Sealed Classes give performance benefits. Is this performance issue applicable to other class types like: Abstract, Static, New etc. and also with access modifiers like public, protected, internal, protected-internal and virtual? If it does make difference in performance, what type of optimization is done internally?


title: Is there a point to unit tests that stub and mock everything public?

text: When doing unit tests the "proper" way, i.e. stubbing every public call and return preset values or mocks, I feel like I'm not actually testing anything. I'm literally looking at my code and creating examples based on the flow of logic through my public methods. And every time the implementation changes, I have to go and change those tests, again, not really feeling that I'm accomplishing anything useful (be it mid- or long-term). I also do integration tests (including non-happy-paths) and I don't really mind the increased testing times. With those, I feel like I'm actually testing for regressions, because they have caught multiple, while all that unit tests do is show me that the implementation of my public method changed, which I already know. Unit testing is a vast topic, and I feel like I'm the one not understanding something here. What's the decisive advantage of unit testing vs integration testing (excluding the time overhead)?


title: Designing an scalable message queue architecture

text: I have recently started learning the nuances of scalable and enterprise computer architecture, and one of the central components is a messaging queue. In order to learn the most I can from any programming paradigm, I am trying to implement my own version of a messaging queue service. So far, my initial design runs on a threaded socket listener, but in order to prevent the same message being downloaded twice by two separate processing nodes, the message queue index register is locked when a read is initiated, and unlocked after the register has been updated. As such, this negates the need for it to be threaded, and means that there is a ceiling for the size of a scalable system based on the processing speed of the server the messaging queue service is running on. The way to get around this would be run the message queue service on multiple servers, but this will increase the likelihood of the same message being downloaded twice. The only way to prevent such issues occurring would be to include a revocation callback that (after the servers, or even the threads on a single server, have synchronized their information and detected such a re- issuance) would command the processing node to stop its current job, and re- query the message queue for the next message, but again, there would be a ceiling where most of the traffic being sent would be synchronizations, and revocation callbacks, causing a bottleneck and slowing the processing of information so that a lot of the processing nodes would be performing null operations and wasting time. The last way I can think of to get around this problem is to have each message queue server (and each thread on each server) would have a specific offset as to where in the queue it is looking, but that might have issues based upon the type of application, especially if the processing is required to be done in a specific order. So, all that being said, are there any designs of message queue architecture's that could show me how existing enterprise grade message queue services avoid these problems?


title: Is there a cleaner way of caching data

text: We've started implementing some caching code in our MVC project. We've derived from .Net's ObjectCache to store it in a SQL database. What we do right now is in each method we want to cache we have code like this:               public StatusCounts GetCounts()     {        var cache = new SqlCache<StatusCounts>("mykey");        if(cache.HasCachedData())           return cache.GetCachedData();             var data = StatusRepository.GetCounts();             cache.SetData(data, DateTime.Now.AddHours(2));     }      As far as caching goes, it works. But my concern is it seems like now GetCounts has multiple responsibilities. It's no longer just calculating counts, it's getting them from a cache (if they exist) and saving them to a cache before returning. Is there a cleaner way to do this?


title: Examples and resources for writing a development proposal for a client

text: We're looking into our processes and client relationships at work and part of this is creating a standardised template for our development proposals that we send to clients. The development areas we cover are mainly web development and design and mobile application development. On top of this we also offer native software developments for small to large companies. What we are aiming for is a template for each development area, something we can base future proposals on. How do you go about writing something like this? Are the resources to help on the internet? More importantly maybe, what would you guys say is important to include in a proposal? This is normally pre-"indepth technical spec", but I would suggest (for instance) including a wireframe or mockup of the finished product. How detailed must you be in order to portray the project to the client and understand the needs of the project yourself in order to charge accordingly?


title: Windows Phone 7 dev: C# or silverlight for a simple app?

text: I'm about to hire a programmer to develop Windows Phone 7 apps. The current app that shall be developed is quite simple.   * The app will download content from a Web-API.    * There are two lists to select content.    * There is a single item content page.    * Users can rate the content and upload photos. The screens will be produced by our artist. I am pretty sure that most of the available programmers haven't touched WP7 development yet. **Now the questions are:**   1. What technology is suitable for this kind of app?   2. What technology requires less research, learning and production time?   3. Do you already have experience of limitations of silverlight compared to C#? (I am also thinking of future projects)   4. My guess is that silverlight programmers are more experienced in UI programming than C# coders. Do you feel the same way?


title: For very short programming jobs, how should one approach the concept of a contract?

text: I am wondering what other contractors in the field of software development do when a potential client approaches them with a spec.. in terms of contracts. In my experience, clients will often be happy to proceed with no formal agreement. I know this is quite an open ended question, so I will break it down into a series of subquestions that can be actually answered. If the client does not have a contract for you to sign, do you present a physical contract to them? If you have such a contract to present to clients, how did you acquire such a thing? Obviously you can pay through the nose to have a lawyer write it, and other obvious answers, but are there other reasonable (cost effective?) solutions to acquiring such a contract? At what stage, if any, would you require the client to physically sign such a contract? (what if the job is just one day?) In some cases, the software you are providing to the client is a customized version of an off-the-shelf, open-source, or proprietary in-house software, how does this affect things? _I realise that the best answer is probably "It depends on the client, and other factors..", you don't need to tell me that. But what are your experiences and opinions about 'best practices' in this area? Or to put a programming slant on it, do you have a reliable algorithm for managing the contract side of things, ie keeping both sides happy, most of the time?_


title: Prefer algorithms to hand-written loops?

text: Which of the following to you find more readable? The hand-written loop:               for (std::vector<Foo>::const_iterator it = vec.begin(); it != vec.end(); ++it)     {         bar.process(*it);     }      Or the algorithm invocation:               #include <algorithm>     #include <functional>          std::for_each(vec.begin(), vec.end(),                   std::bind1st(std::mem_fun_ref(&Bar::process), bar));      I wonder if `std::for_each` is really worth it, given such a simple example already requires so much code. What are your thoughts on this matter?


title: When to skip solving the general problem and settling for the specific problem?

text: I've been working hard on trying to develop a general solution to my problem, but I cannot seem to formulate a proper algorithm for it, at least one that doesn't take a ton of inaccurate grunt work building a lookup table. I have a solution already for the specific requirement, but it requires the software's configuration to be changed every time the software is loaded with a different geographic area's datasets. So is it better to be finished and move on for now, or to keep attempting to solve the general problem knowing that the specific problems will keep popping up?


title: Are there any compilers that attempt to fix syntax errors on their own?

text: I heard a while back that there used to be a compiler that attempted to fix syntax errors by analyzing context and inferring what was intended. Does such a compiler really exist? Obviously it has little practical value, but would be very interesting to play with and learn from.


title: Should selenium tests be written in imperative style?

text: Is an automation tester supposed to know concepts of OOPS and design patterns to write Tests in a way where changes & code re-use are possible? For example, I pick up Java to write cucumber step definitions that instruct a selenium webdriver. Should I be using a lot of inheritance, interfaces, delegation etc. to make life easier or would that be overly complicated for something that should just line by line instructions?


title: For performance critical situations is storing file metadata in a database better?

text: As per the title of this question, for extremely performance critical situations, is storing a file's metadata (e.g. location, size, download on, etc) in a database going to allow for better performance than attempting to get it from the file system itself? Have there been any case studies into this problem? To provide a bit more detail on a specific situation, the application needs to mirror terabytes of data (hundreds of files) between a remote site on a continual basis and the current program architecture uses Unix commands (i.e. `ls`) to determine which files needed to be updated. The file themselves are split between Isilon IQ clusters and Sun Thumper clusters which I have been told good throughput but poor metadata performance. As the application will be the only process to have write permissions to the files we aren't concerned with things getting out of sync, but we are concerned with performance as it currently takes between six and ten hours to transfer the data.


title: Can an open source solution match or surpass Team Foundation Server's features?

text: Team Foundation Server offers a version control system, but with many more side features, such as bug tracking, user stories, project planning, and it is all integrated into visual studio. Someone put a more complete list of features over here: Over the past year I have been working with Mercurial and from the moment I typed "hg init" I was in love. My new colleagues are convinced that even though other scm solutions are probably better, TFS provides a better complete package for teams. What I would like to know is whether it is better to just use TFS, or to go the open source route and select various solutions and integrate them to get a better result, and if its even possible to get that level of integration? So in summation: Can it be done and is it better to go for various OSS tools?


title: What is a reasonable and secure password requirement for user registration?

text: This is the password policy I just got from UPS (just for package status checking): > Your password must be between 8 and 26 characters long. It must contain at > least three of the following character types: lowercase letters, capital > letters, numerals, special characters, or spaces. The password may not > contain your User ID, your name, or your e-mail address. (SSO_1007) I actually have to wrack my brain somewhat to generate this password, but not only that, most importantly, I am sure that after 3 days I will forget what this password is. Users won't be so happy. Password reset can be frequent. I think users will try to avoid using the site unless they have to. What is a reasonable and secure password policy when setting up a website? I think some companies may fear some hackers trying passwords a million times or more, so they add all those requirements for "special characters, lower case, upper case", but won't it be reasonable to turn off the account or just disable the password and require a password reset if a user has tried 30 times or 100 times? Or, add a 5 second delay each time after the user tried 30 times? If so, then those special characters won't be that much needed.


title: In need of a more technical answer for an interview question about how the internet works from beginning to end

text: I've had interviews with 5 separate people over the past two weeks and three of those five have all asked me this question: _Explain what happens between hitting "Google.com" and the page coming up on the screen._ Basically, how the Internet works. I figure after three times that I better be prepared if I ever get this question again. I know _some_ things, but I'm not fully convinced that my answer is good enough. Basically, I mention that the DNS server translates "google.com" into an IP address. I kinda gloss over TCP/IP, then talk about the web server literally serving up requested pages that get sent back to the browser which the browser then interprets and displays. As I said before, I'm not convinced my answer is technical enough. What are the steps that I'm leaving out? For what it's worth, two of those three times have been with the same company and I'm being called back for a third interview with them, so I can't have bombed it _too_ hard.


title: Why aren't design patterns added to the languages constructs?

text: Recently I was talking with a colleague who mentioned that his company was working on adding the MVC design pattern as a PHP extension. He explained that they wrote C code for adding `Controllers, Models and Views` to the language constructs to increase performance. Now I know that MVC is an architectural design pattern that is used widely in web applications, but I still have to come across languages that have a language construct for Controllers for example. IMHO integrating design patterns into a language can emphasize the importance of good OO design. So, **Why aren't the most used design patterns (MVC, Factory, Strategy,...etc.) added to the language constructs?** If the question sounds too broad then you may limit the question to PHP only. **Edit:** I'm not implying that one **must** use a design pattern when developing a project. Actually I promote the methodology of keep it simple as long as it works.


title: Issue with scrum adaptation by team

text: I have been playing with Scrum methodology since year and half. I am using VersionOne as scrum tool. I have tried to follow most of the scrum principles. Sometimes, I feel like there is an issue with transparency of the stories. As of now, the whole team can get an access to all stories defined for the project. This creates issues with different levels of developers like junior and senior level developer. People's complains are about the work distribution or type of work they are assigned to. There is an issue of comparison among the developers. I don't know if I am following scrum properly or not. In scrum, should we give access of the all stories to everyone? or only assigned person can view his/her story?


title: What makes a great user management interface great?

text: I'm currently working on user management for a project and while thinking about how I should design this I realised that there's really no standard in how these things look as it often vary a lot from application to application. So what makes an great user management interface great? What do the best ones have in common?


title: Why does Java not do type inference?

text: I have always wondered why Java does not do type inference given that the language is what it is, and its VM is very mature. Google's Go is an example of a language with excellent type inference and it reduces the amount of typing one has to do. Is there any special reason behind this feature not being a part of Java?


title: Do integrated systems increase development time and cause inflexibility?

text: I work for a large financial company that manages money for thousands of clients. This company has very complex business processes and they operate in a very dynamic environment. This is a fairly old company and over the years they have implemented many heterogeneous systems to automate processes within the company. There are rumors in the company that there may be an effort to move to "a system" (re-written from scratch) that consolidates the many disparate systems in place now. Debate has arisen that questions the value of such a move:   One side claims a single system is easier and cheaper to maintain due to greatly reduced redundancy i.e. properly factored business logic, unified data model, reusable UI components, etc. Other side claims that the company, clients, and products (financial instruments) are too complex and too dynamic to be pigeonholed by one system. Single system will risk breakages in one component when another is modified. There is no way and no reason to consolidate business logic because it is too client- and product-specific. Time to implement changes will increase because multiple higher level components will be affected by changes to lower level components. Question: Should the company seek to invest time and resources in creating a unified data model, factoring business logic and creating reusable code at all layers? Or should they "copy and modify" in order to speed development time, reduce the chance of regression, and reduce complexity? Is there a false dilemma presented here (i.e will there be a net change one way or the other and does one answer necessarily preclude another)? To be clear, this really a matter of **long term goals and priorities** , not about a specific product design. The company will never eliminate a certain amount of redundancy and it would not be desirable for them to do so.


title: How important is an in-depth knowledge of the Common Language Runtime to a .NET developer?

text: I wonder how many .NET developers have a working knowledge of CIL and where it has been useful to them. In case you are missing my meaning, here is a simple CIL example to add two locations together:               ldloc.0     ldloc.1     add     stloc.0    // a = a + b or a += b;


title: How do I Integrate a Former Team Member into the Current Team

text: Is it possible to re-integrate a former team member into a software project? We have a product with a looming customer deadline and we don't have enough hours to get it done! We have a former employee who left on excellent terms and wants to come back. They are familiar with the codebase and architecture (which has not changed significantly since they left). Can we use this situation to avoid Brooks Law? It seems like an ideal situation, team member up to speed with processes, tools, etc. What do we need to be careful of? Are there any dragons in the water? Or should we expect smooth sailing?


title: Is Rule 9 of Object Calisthenics applicable in Objective C?

text: Rule 9 in Object Calisthenics by Jeff Bay (RTF) is: > **Rule 9: No getters/setters/properties** > > The last sentence of the previous rule leads almost directly to this rule. > If your objects are now encapsulating the appropriate set of instance > variables but the design is still awkward, it is time to examine some more > direct violations of encapsulation. The behavior will not follow the > instance variable if it can simply ask for the value in its current > location. The idea behind strong encapsulation boundaries is to force > programmers working on the code after you leave it to _look for_ and _place_ > behavior into a single place in the object model. This has many beneficial > downstream effects, such as a dramatic reduction in duplication errors and a > better localization of changes to implement new features. > > Another way this rule is commonly stated is “Tell, don’t ask”. I get the point of the rule. But I find it only useful in garbage collected environments where modifying a reference is very simple. Will this be of any help in Objective C? Because it's always important to let only setter change the ivar and let it also take care of retaining new value and releasing the old one. and use the setter anywhere inside methods to alter ivars which are pointers.


title: How to let  teammates know what  changes I made to an object?

text: Suppose I have a PHP object, let's say: companyObj.               class companyObj     {       private company_name;       private company_address;            public function print_contact()       {         //logic       }     }      This is the object I wrote, and shared with the teammates. Now I would like to make it more powerful, like this:               class companyObj     {       private company_name;       private company_address;       private company_contact_person;            public function print_contact()       {         //logic updated       }     }      Now, how can I notify my teammates that my object had more attributes that they can set? Instead of sending e-mail to everyone in the development team, how do I make the team know what's going on, when I don't want my teammates to waste their time to look at what is changed at the source code level?


title: NP complete or NP hard problems in real life

text: Does anybody have real life examples where they regularly solve NP complete or NP hard problems (by heuristics, or chasing a suboptimal solution or whatever) in their job? I know they occur in scheduling, planning, VLSI design, etc., but I am trying to get an idea of the major industries employing programmers or engineers today that regularly do this. If one were to develop expertise or a library, in say, combinatorial optimization where could one use that as part of a programming job? Any personal accounts?


title: Components under what licenses can I use in my paid app?

text: I'm working on an application and I need to use some existing components such as libraries and JavaScript frameworks that are covered by licenses. My application will be paid (not free) and closed-source. Can I use components in my app that are under one of following licenses:   * MIT   * Apache   * BSD


title: Why does gmail use java? Is there really a advantage over something like php or python?

text: Note: I know that none of you (probably) work for google, so this is a lot more of a conceptual question. So yeah, i discovered that Gmail uses java and that got me thinking, Why? I personally never really learned java and am familiar with C/C++, Python, Php e.t.c But what i dont understand is why do some websites use languages such as java? (Note: This is in no way a thread saying one language is better than the other). What i want to know is why do some websites such as Gmail use java and similar languages?What advantages/disadvantages come with using java/similar languages over languages such as php/python/ruby for web development? Ps: I know that some sites prefer to compile their code for optimization(Like facebook's hiphop)


title: Recommendations on what technology to use to call REST API

text: I'm creating a small web-site that needs to call a REST API to retrieve some JSON and display it. What is the best tool for this job? There are so many Javascript libraries available now it is difficult to decide which one to choose. Is there are particular library that people would recommend that will do what I want both efficiently and without extensive development effort.


title: Given a situation, and some conditions, verify is that situation is possible

text: Well it's a problem me and my friend had thought of, and well, haven't come up with anything to solve the following problem(I'll try to phrase it in the best way I can): > Given that there are `n` number of teams, and the number of matches each > team has played, and that no team can play more than 2 matches with any > other team, predict if the distribution of matches played by each team is > possible. P.S. : I am a Python Programmer, so (if possible) post only python code for explaining..


title: Does keeping a journal help in your job?

text: Years ago, in my first real programming job, my boss encouraged me to keep a journal of my daily activities. I still do so, although no longer a paper and hand-written one. Do you keep a journal, if so, what do you write in it, and how does it help you in your job? Or, does it just take time that is not ever recovered?


title: Should code and data be treated seperately?

text: Is it really necessary to differentiate between code and data ? Is there any language where such differentiation is not there ?


title: What is the Best Collation for Use in MySQL Tables?

text: I'm curious what is considered the standard today for use as the Collation of MySQL Tables? I was told that Latin-1 was the best choice when I was beginning with MySQL, but came across this post from 2009. It states that US-ASCII and LATIN-1 Character Sets are on the way out, and that UTF-8 is on the way in and should be made the default by MSQ version 6. Does this gel with what you know, or with what you think, or with what you do? For this question, let's assume there is no specific need for non-english characters.


title: Hibernate building HQL queries

text: I just read hibernate reference and they say that you should use constans for HQL queries. However that is not always possible, for example if you do search function and have 10 criterias (not jpa criterias, just columns you are searching by). I bet you can do some hacky HQL that is transformed into badly performing SQL, but I feel that is not the best choice. I do know you can use The Criteria API, but its not as powerfull as HQL and some people just don't like it (I'm one of them). How you do it in Yours applications? I mean code like (its just an example!)               String hql = "from Biuro where ";     List parameters = ...     if (dateFrom!=null){        hql += " dateFrom>=? ";        parameters.add(dateFrom);     }


title: Strategy/algorithm to divide pot to chips

text: I want to split poker pot to chips. Example: Pot = $17.500. I have the endless piles of chips. I have the following types of chips: ChipsTypes = [$1, $5, $10, $25, $100, $500, $1.000, $5.000, $10.000, and so on]. Index starts from 0. I want to get an array that says which chips I have to take to divide the pot and in which order to have minimum number of denominations and chips after pot-to-chips conversion. For example Result = [7, 5] means that I have to take 3 * $5.000 + 5 * $500 which $17.500. Is there is any strategy or algorithm that would suit my need?


title: Starting developer fighting with webforms, is moving to MVC a good idea?

text: A young developer frequently hits me up for help with Asp.net web forms. Usually his problems revolve around the actual controls and how to manipulate them, rather than pure middleware type code. Since I work with Asp.Net MVC quite a bit I usually see simpler solutions to his problems, but he can not implement them because of the structure he is working in. I have discussed this with fellow developer, and he feels that it would not be a good move. His reasoning is that if you remove the structure that web forms provides, the young developer will flounder and not be able to do anything. I, on the other hand, feel that by removing the built in abstraction of web forms and their associated controls, and just focus on HTML and the code he will be more successful in his projects. Would it be a wise move for a developer in this situation to move away from web forms and start to learn Asp.net MVC?


title: Understanding comparison using Big O notation

text: I was going through this heavily discussed and highly voted question on SO and stumbled across one comment that got 5 upvotes. So I assume this was a great comment.But it got my head spinning at the same time. Can any one explain this comment? The comment says: > You can't compare big-O values directly without thinking about constant > factors. For small lists (and most lists are small), ArrayList's O(N) is > faster than LinkedList's O(1).


title: Testing-related methodologies except TDD/BDD

text: Are there any testing-related methodologies except TDD/BDD? I see a lot of people who practice their own testing approaches (e. g., see Ayende post), but I don't see any formalization for it, no naming for these approaches.


title: Is functional intellisense and code browsing more beneficial than the use of dependency injection containers

text: This question is really based on PHP, but could be valid for other dynamically typed, interpreted languages and specifically the methods of generating code insight and object browsing in development environments. We use PHPStorm, and find intellisense invaluable, but it is provided by some limited static analysis and parsing of doc comments. Obviously this does not lend well to obtaining dependencies through a container, as the IDE has no idea of the type returned, so the developer loses out on a plethora of (in the case of our framework anyway) rich documentation provided through the doc comments. So we start to see stuff like this:               $widget = $dic->YieldInstance('WidgetA', $arg1, $arg2, $arg3, $arg4...));     /**      * @var $widget WidgetA      */      So that code insight works. In effect the comments are tightly bound, but worse they come out of sync when code is modified but not the comments:               $widget = $dic->YieldInstance('WidgetB', $arg1, $arg2, $arg3, $arg4...));     /**      * @var $widget WidgetA      */      Obviously the comment could be improved by referencing a Widget interface, but then we might as well use a factory and avoid the requirement for the extra typing hints in the comments, and dic complexity / boiler plating. Which is more important to the average developer, code insight / intellisense or 'nirvana' decouplement?


title: C++ project organization to reduce unit testing build time

text: I want to organize tests for a project large enough that build time matters (especially for the CI server). Say I have this code that I would like to test :               //foo/greet.cpp     #include <stdio.h>     #include "foo/greet.h"     int greet() { return printf("Hello, World!\n"); }      And I have this main program that is boilerplate that I will not test.               //main.cpp     #include "foo/greet.h"     int main() { return greet(); }      I will use this code to generate a unittest program               //testgreet.cpp     #include <some_test_framework.h>     SOME_TEST_FRAMEWORK("Testing greet")         SOME_TEST_FRAMEWORK_ASSERT(greet() > 0)     SOME_TEST_FRAMEWORK_END()      I thought of the following   * Skipping the build of `greet.cpp` for the unittest target, and linking with the objects   * Create a separate project structure for the tests, but share the output folder   * Pile everything in one place, maybe with a new folder named test   * Make a `greeting` library and link both main and unittests targets to it How can I organize my project so that I can build `greet.cpp` only once, yet reduce confusion caused by having two targets that share a lot of code ? This question is related, but not duplicate (IMHO). (+I tried making my question generic, reusable and future proof. If you think that this is too opinion based, vote to close and I will not repost)


title: What are the most efficient code review processes?

text: I am looking for an efficient code review process where nothing can be pushed without being reviewed by another dev. For instance (we are using Mercurial):   * push to another branch and the reviewer will merge with the 'head'   * push directly to the reviewer The main issue here is that everybody can push to the default branch, so it doesn't enforce the code review.


title: Any basic difference between Unix and Linux in design and other aspects?

text: I keep reading this sentence: > Linux is a Unix-like system, but it is not Unix. I don't know what's the real difference between the two. I know Linux got a lot of ideas from Unix and the licenses of the two are different. Apart from that, as I am not an expert in either one of them, I want to know whether there are basic differences between them in design or other significant aspects.


title: How to learn microcontroller programming?

text: I am interested in learning how to program microcontrollers. It seems to be quite interesting, but I don't know, where to start. I am particularly interested in:   * What platform is worth learning?   * Are there any cheap systems that make it easy to write own programs for them?   * Pointers to good books / tutorials


title: What are good books for learning C++11?

text: I'm just starting to get interested in C++11 (late I know). Does anyone have any recommendations for books available that cover the new features in depth?


title: Python - 'if foo in dict' vs 'try: dict[foo]'

text: This is less a question about the nature of duck typing and more about staying pythonic, I suppose. First of all - when dealing with dicts, in particular when the structure of the dict is fairly predictable and a given key is not _typically_ present but sometimes is, I first think of two approaches:               if myKey in dict:         do_some_work(dict[myKey])     else:         pass      And of course Ye Olde 'forgiveness vs permission' approach.               try:         do_some_work(dict[myKey])     except KeyError:         pass      As a journeyman Python guy, I feel like I see the latter preferred a lot, which only feels odd I guess because in the Python docs `try/excepts` seem to be preferred when there is an actual mistake, as opposed to an, um… _absence of success?_ If the occasional dict does not have key in myDict, and it is _known that it will not always have that key,_ is a try/except contextually misleading? This isn't a programming error, it's just a fact of the data - this dict just didn't have that particular key. This seems particularly important when you look at the try/except/else syntax, which looks to be really useful when it comes to making sure that try isn't catching too many errors. You're able to do something like:               try:         foo += bar     except TypeError:         pass     else:         return some_more_work(foo)      Isn't that going to lead to swallowing all kinds of weird errors that are probably the result of some bad code? The above code might just be preventing you from seeing that you're trying to add `2 + {}` and you may never realize that some part of your code has gone horribly wrong. I don't suggest that we should Check All The Types, that's why it's Python and not JavaScript - but again with the context of try/except, it seems like it's supposed to catch the program doing something it shouldn't be doing, instead of enabling it to carry on. I realize the above example is something of a straw-man argument, and is in fact intentionally bad. But given the pythonic creed of `better to ask forgiveness than permission` I can't help but feel like it begs the question of where the line in the sand actually is between correct application of if/else vs try/except is, in particular when you know what to expect out of the data you're working with. I'm not even talking about speed concerns or best practice here, I'm just sort of quietly confused by the perceived Venn diagram of cases where it looks like it could go either way, but people err on the side of a try/except because 'someone somewhere said it was Pythonic'. Have I drawn the wrong conclusions about the application of this syntax?


title: Module vs. Package?

text: Whenever I do `from 'x' import 'y'` I was wondering which one is considered the 'module' and which is the 'package', and why it isn't the other way around?


title: Why is it recommended to close all programs before installing a new program?

text: What kind of problems arise from installing a new program while other programs are running? I'd imagine the GAC solved a lot of the old problems of shared dll's being locked. So what kind of issues still arise? I can see issues with upgrading a single program for sure, but outside of this its hard to see why apps would stomp on eachother's toe's.


title: What is involved in learning Eclipse-RCP, from zero Java background?

text: I've not yet started working on a new project where everything is done with "Eclipse RCP" which I never heard of until last week. We'll use lots of Java and SWT for GUI. I'd like to get up to speed on this new technology ASAP. (Or else I'll be the company "coffee boy" for the next several months...) Given a starting point of zero Java experience, zero use of Eclipse and zero use of SWT, zero computer science background (I'm into physics, engineering and art) and only modest experience working on the applications level in any sense, but OTOH, years of low-level programming and doing various neat cutting-edge things in areas that don't overlap at all with the Java or Eclipse worlds, how big a chunk of learning curve do I need to climb? To be clear, while I need to become more fluent in Java, and learn the end user basics of Eclipse and beyond, I don't need to learn the fundamentals of programming, OO, what a "compiler" is, etc. and am an old pro at Linux, C++, event-driven GUIs and much more. How to guesstimate how many days I'll need to become competent at working on Eclipse-RCP based apps? (No need to become a master guru. Of course that comes with time.) How to judge my level of skill along the way? How might I come up with a checklist of topics I should cover? What to tell the boss about when I'll be ready to work on this thing? What books, tutorials, etc are good for this learning curve climb? (No budget for classes, workshops, or books pricier than what I can get at Barnes & Noble.) (Actually I do have some modest experience in Java, but let's pretend it's zero, to make the question and answers more fun and useful to others.)


title: Handling requests RESTfully?

text: There is a push in modern scripting frameworks to use RESTful request routing instead of a one-size-fits-all URL path routing.               respond('GET',    '/posts',       callback);     respond('POST',   '/post/create', callback);     respond('PUT',    '/post/[i:id]', callback);     respond('DELETE', '/post/[i:id]', callback);      vs               respond('/posts',       callback);     respond('/post/create', callback);     respond('/post/[i:id]', callback);     respond('/post/[i:id]', callback);      I must confess that I am still using the old-and-busted method where the resource is accessible at the given URL regardless of the request type. **Is there anything I'm missing by using the old format?**


title: Ruby module namespacing advice

text: in my current project have:               module Stats            class Site         ...       end            class Product         def initialize(product_id)           @product_id = product_id         end       end            class Profile         ...       end          end      now in my `Product` class have methods to get/set product `views`(day, week, month) and methods to get/set product `sales`(day, week, months) is better to namespace like `Stats::Product::Views` and `Stats::Product::Sales` or simply prefix methods like `sale_add` and `view_add`? example calls with namespace:               Stats::Product::Sales.add(product_id) # increment sales counter      Stats::Product::Sales.today(product_id) # get n. today sales       Stats::Product::Sales.week(product_id) # get n. week sales            Stats::Product::Views.add(product_id) #increment product page view counter     Stats::Product::Views.today(product_id) #get n. today product page views     Stats::Product::Views.week(product_id) #get n. week product page views      example with current structure:               Stats::Product(product_id).sale_add # increment sales counter      Stats::Product(product_id).sales_today  # get n. today sales      Stats::Product(product_id).sales_week # get n. week sales           Stats::Product(product_id).view_add #increment product page view counter     Stats::Product(product_id).views_today #get n. today product page views     Stats::Product(product_id).views_week #get n. week product page views      Now, what you think is more elegant solution? and why?


title: Manual memory allocation and purity

text: Language like Haskell have concept of _purity_. In pure function, I can't mutate any state globally. Anyway Haskell fully abstracts memory management, so memory allocation is not a problem here. But if languages can handle memory directly like C++, it's very ambiguous to me. In these languages, memory allocation makes visible mutation. But if I treat making new object as impure action, actually, almost nothing can be pure. So purity concept becomes almost useless. How should I handle purity in languages have memory as visible global object?


title: Adding Methods In Addition to an Interface

text: Let's say I have `ThingImpl` and `IThing`. The former is an implementation of the latter, which is an interface. IThing has 1 method: `do(arg1)` Is it considered a hack/bad practice to add a method in addition to do()? Example: `do(arg1, arg2)`


title: The bracketless if statement is frowned upon, but is it still bad style if your IDE is equipped for it?

text: This type of conditional statement is generally frowned upon               if(condition)       statement;      because if you add another statement, like this               if(condition)       statement;       statement;      it gives the impression that the second `statement` is part of the `if` block when it isn't. That said, my IDE does automatic indentation, which I think makes this problem moot. Furthermore, when I want to add another statement, it automatically does the bracket completion--which makes the issue about having to manually add brackets when you want to add another statement moot. Is there any reason why this would still be bad style?


title: If I am developing a hosted payments page, what should the infrastructure look like?

text: If I am not storing credit card info, do I have to be concerned with PCI- compliance? I will be using a payment processor with a bank in my country. Literally just taking the credit card info and passing it to the gateway and processor. I would love to get an idea of the various technologies I might need to consider from an software architectural point of view. What are the best practices in terms of accepting credit cards and reducing fraud risk on my end? I will be creating the app in Rails.


title: What to do if I hate C++ header files?

text: I was always confused about header files. They are so strange: you include .h file which doesn't include .cpp but .cpp are somehow compiled too. Recently I joined a team project, and of course, both .h and .cpp are used.   I understand that this is very important, but I can't live with copy-pasting every function declaration in each of multiple classes we have. How do I handle the 2-file convention efficiently?   Are there any tools to help with that, or automatically change one file that looks like example below to .h and .cpp? (specifically for MS VC++ 2010)               class A     {     ...         Type f(Type a,Type b)         {             //implementation here, not in another file!         }     ...     };          Type f(Type a)     {          //implementation here     }     ...


title: Is api user authentication with oauth possible for both email/pw and 3rd party services

text: I have an api only application (rails-api) and I'm looking to authorize a user on both email/password or 3rd party services like facebook or twitter etc, so I know I will have to use Oauth at some point. My question is, can I solely use Oauth, or do I have to implement my own authentication (or something like Devise) to do the manual email auth. I don't understand Oauth well enough to know whether I can do manual authentication with my single endpoint, it seems like it only works with 2 endpoints (my server and a 3rd party service). I would much rather not use Devise is not built for an api and adds alot of overhead IMO.


title: How to deploy C# application to be used in branch / remote office(s)

text: Have very recently started a new position. One of my key challenges is a C# WinForms application (let's call it AppX) that causes a lot of non-planned work. The main reason for this is that it needs to be deployed to several hundred branch offices. Currently, this is done via GP update or bespoke application. Both of these methods are unreliable and means we can't effectively deploy version upgrades. Bit of background to what the software needs to do and some of the technical issues / background:-   1. AppX needs to produce results in real time    2. AppX needs to connect to a SQL server (express or full edition) which is physically located in the branch office    3. AppX needs to ensure that after a version upgrade all remote sites are on the same version    4. AppX can't be deployed via a thin client solution such as Citrix or Remote Desktop services    5. The headquarters network can see the entire branch office network and connect into their SQL servers My initial thoughts were ClickOnce deployment -- however there seems to be some suggestions that there may be some issues with conflicts of the .Net framework with other software Deploy the solution as a web app at the headquarters which connects back into the remote SQL server - technically I'm not sure how I would go about this I guess that this is something that others may have come across so I would be interested to know if there are any other suggestions on how to approach this Thanks


title: equals and hashcode methods autogenerated, is it always a good practice?

text: Preamble: Let's say I aim to cover all my classes with test coverage. Despite the common opinion (expecially in Java community) to "not pay too much attention to Cyclomatic Complexity (CC) and code coverage", I really think that these information are extremely useful: When you have a very high CC, or an uncovered zone in your code, very likely you wrote a dead code, or either is a smell that you have problems in design. In my personal experience I can say that many time dead code _is_ code smell. This problem become a little tricky when you have to deal with auto-generated code, and that's the point, how can I easily deal with `hashcode` and `equals` autogenerated methods? I came across this question in StackOverflow and I realized some very good point: http://stackoverflow.com/questions/5764380/unit-testing-equals-and-hashcode-a- complexity-story But this question is not a duplicate because I want to use a different approach: The best options available in the answers of that question are, as far as I can see, EqualsBuilder of Apache Commons Lang or Guava. Both uses reflection (correct me if I'm wrong) and that could be a problem for performance in some situations. But my actual question is: Since most of the times both `equals` and `hashcode` methods are **not** covered, is that a hint that this particular class does **not** need those 2 methods? Since many Java developers a lot of time generate equals and hashcode even when not needed, what am I missing? Shouldn't be a better solution to generate those methods only when you need, for instance, to sort objects of that class, to use that objects as an Hashtable key, and so on? As I said, I think that goals of low complexity and high coverage are admirable, but the solution of using EqualsTester , seems to me like "Force to cover code that you don't actually need in your program".


title: Code review guidelines for CSS, JS and HTML

text: I have been asked to create guidelines for review CSS, JS and HTML. I know there are coding guidelines for JS but I don't know any about HTML and CSS. To review JS I will certainly follow those guidelines and mention them. But what about CSS and HTML? Apart from logical errors and indentation issues, are there any specific things I need to check when I review markup and or CSS?


title: What are the advantages to developing with outdated technologies?

text: **A little background** : I am working at a large company, using Windows XP and coding Winforms in VB6/VB.Net and some WebForms in VB.Net (95% maintenance code). I have one 4:3 19" screen. A more modern version of Windows isn't happening soon, neither is any greenfield work by the sounds of it! I wasn't told about any of this when I joined the company, I was mislead to think I would be working with much more up to date technologies and frameworks. I have much more up to date experience from previous jobs, both with more modern frameworks and other programming languages, and when I am catching up with developer friends from other companies all I hear about is how they are using the latest ASP MVC framework, or Vagrant/Ruby on Rails/etc and I am getting the green eyes! I could sort myself out with another job pretty quickly, but I feel as though I should give this one more of a chance. **The question** : I am trying to convince myself that my current job isn't that bad. So what are the advantages to this sort of role? Are there advantages to working with outdated technologies? Maybe some techniques that I wouldn't pick up working with more modern ones? Or is this the sort of place where careers go to die, and I should get out while I still have my soul?


title: Functional as a first language

text: What are some pros and cons to learning functional programming before other paradigms?


title: Exchanging program results in Java

text: I wrote a calculator similar to the windows calculator using Java. And now I want to integrate this calculator into other projects as a separate package and use results obtained with the calculator in these projects with a single click (not using copy and pasting). How can I do this. (I'm using Netbeans to code Java)


title: Transforming theoretical knowledge into practical knowledge

text: I have got good grades and ~ 10 years of professional embedded s/w development. However I have come to realize that and also been pointed out in performance appraisals that although I have good theoretical knowledge and have even read lots of programming books - Code complete, pragmatic programmer etc.. , my hands on practical knowledge is weak and I am unable to translate my theoretical ability into practical expertise. I need to figure out a plan on how to do this. Any ideas in this regard? EDIT : I take too long in understanding specs and in developing code and and miss some aspects in development particularly domain knowledge.


title: About clean code

text: Example: I have a method that formats the output based on a parameter from an object. The question is, should I pass the object that holds the parameter to the method, or just the required param? Still trying to grasp clean coding so I might be wrong, my take is that the 2nd approach is cleaner because it doesn't require you to pass the entire object, and is easy to test.   However, it makes calling the method ugly now since I have to check for the param every time when I call the method. And its used very very often. In contrast, the first approach while not that easy to test, because I have to mock the requestObject, is much easier to use. So which method should I go with? Or is there an even better approach?               // The output method with object as input     public function outputResponse($message, $requestObject) {         if (isset($resquestObject->param['response_type']) && $requestObject->param['response_type'] == 'json') return json_ecode($message);         return xmlOutput($message);     }          // So you call it like     $this->outputResponse($message, $requestObject);      The other approach...               // The output method with just the param as input     public function outputResponse($message, $responseType) {         if (responseType == 'json') return json_ecode($message);         return xmlOutput($message);     }          // So you call it like     $responseType = (isset($resquestObject->param['response_type']) && $requestObject->param['response_type'] == 'json') ? 'json' : '';     $this->outputResponse($message, $responseType);


title: What *are* the programming concepts I should master to have a deep understanding of my craft (programming)?

text: In order of importance, if its possible to do so and it may not be, what are the most important foundations of knowing how to program. Algorithms, iteration, recursion, etc? Note that where I put etc. is where my question lies. I recently read an Internet post that said 9 out 10 programmers can't _gasp_ program! http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html I want to have a deep knowledge of what it is I am actually trying to accomplish when programming and an exhaustive comprehension of the basic tools at my disposal. Basically I want to be able to paint with all the colors of the wind.


title: What is the point of using lists over vectors, in C++?

text: I've run 3 different experiments involving C++ lists and vectors. Those with vectors proved more efficient, even when a lot of insertions in the middle were involved. Hence the question: in which case do lists make more sense than vectors? If vectors seem more efficient in most cases, and considering how alike their members are, then which advantages are left for lists?   1. Generate N integers and put them in a container so that the container remains sorted. The insertion has been performed naively, by reading elements one by one and inserting the new one right before the first larger one.   With a list, time goes through the roof when dimension increases, compared to vectors.   2. Insert N integers at the end of the container.   For lists and vectors, time increased by the same order of magnitude, though it was 3 times faster with vectors.   3. Insert N integers in a container.   Start timer.   Sort the container using list.sort for lists, and std::sort for vectors. Stop timer.   Again, time increases by the same order of magnitude, but it is in average 5 times faster with vectors. I might continue to perform tests and figure out a couple of examples where lists would prove better. But the joint experience of you guys reading this message might provide more productive answers. You might have come across situations where lists were more convenient to use, or performed better?


title: Different Project Type in a Single Website

text: I have developed a website in asp.net and I have some additional tasks, improvements to develop. In order to get experience in asp.net/mvc, I want to create an admin panel using asp.net mvc. **Is this a logical next step?** * * * P.S. The project is small and 20% of the website is mine, so there are not any restrictions. There is no problem if I do not meet deadlines! :)


title: Dealing with Feature Intersections

text: I have recently witnessed more and more problems similar to the ones explained in this article on feature intersections. Another term for it would be product lines, though I tend to attribute these to actually different products, whereas I usually encounter these problems in the form of possible product configurations. The basic idea of this type of problem is simple: You add a feature to a product, but somehow things get complicated due to a combination of other existing features. Eventually, QA finds a problem with a rare combination of features that no one thought of before and what should have been a simple bugfix may even turn into requiring major design changes. The dimensions of this feature intersection problem are of a mind-blowing complexity. Let's say the current software version has `N` features and you add one new feature. Let's also simplify things by saying that each of the features can turned on or off only, then you already have `2^(N+1)` possible feature combinations to consider. Due to a lack of better wording / search terms, I refer to the existence of these combinations as _feature intersection problem_. (Bonus points for an answer including reference(s) for a more established term.) Now the question I struggle with is how to deal with this complexity problem on each level of the development process. For obvious cost reasons, it is impractical up to the point of being utopian, to want to address each combination individually. After all, we try to stay away from exponential complexity algorithms for a good reason, but to turn the very development process itself into an exponentially sized monster is bound to lead to utter failure. So how do you get the best result in a systematic fashion that does not explode any budgets and is complete in a decent, useful, and professionally acceptable way.   * Specification: When you specify a new feature - how do you ensure that it plays well with all the other children?  I can see that one could systematically examine each existing feature in combination with the new feature - but that would be in isolation of the other features. Given the complex nature of some features, this isolated view is often already so involved that it needs a structured approach all in itself, let alone the `2^(N-1)` factor caused by the other features that one willingly ignored.   * Implementation: When you implement a feature - how do you ensure your code interacts / intersects properly in all cases. Again, I am wondering about the sheer complexity. I know of various techniques to reduce the error potential of two intersecting features, but none that would scale in any reasonable fashion. I do assume though, that a good strategy during the specification should keep the problem at bay during implementation.   * Verification: When you test a feature - how do you deal with the fact, that you can only test a fraction of this feature intersection space?  It is tough enough to know that testing a single feature in isolation guarantees nothing anywhere near error-free code, but when you reduce that to a fraction of `2^-N` it seems like hundreds of tests are not even covering a single drop of water in all oceans combined. Even worse, the most problematic errors are those that stem from the intersection of features, which one might not expect to lead to any problems - but how do you test for these if you don't expect such a strong intersection? While I would like to hear how others deal with this problem, I am primarily interested in literature or articles analyzing the topic in greater depth. So if you personally follow a certain strategy it would be nice to include corresponding sources in your answer.


title: Solving Scrabble board?

text: I recently saw a question on SO about solving the scramble/boggle game, where the letters are in a 4x4 grid and you have to find as many words as possible. I looked at some of the solutions, tried it myself, and would now like to move onto solving a scrabble game. The boggle solving code is rather simple; store the board state in a matrix and iterate over every move from every position and checking if words exist with the current letter chain. With scrabble, the idea is similar, but I'm still having trouble figuring it out. My currently thinking of:   1. Storing the board in 2 dimensional array.   2. Iterating over each position and skipping if the position is empty.   3. Creating some sort of regex pattern for the letters on the rack and the letter at the position... I'm still really iffy on what to do at step 3 because I know the tile at the position could be the beginning end, or some point in the middle of a word. And then there's the matter of making sure that if a word does fit that it also makes words with other tiles it touches.. I'm not asking for code samples, just the thought process from more experienced programmers. To clarify, my goal is: > Given the current state of a board and a person's tiles, calculate the legal > moves and the points for that move. For anyone following this and waiting for an answer, I found this: http://www.chaddington.com/portfolio/project.html#scrabble I might look through what he wrote, but I do want to try to figure it out myself first.


title: Logistics of becoming a iOS development Firm

text: We've had a lot of success in our company with the iOS apps that we have made that we are now looking at branching out and offering our services to people who want iPhone/iPad applications made for them or their company. What options do we have for deployment scenarios? If they want it up on the app store than this is quite easy and we will just submit it in the normal process. But what clauses do people put on these contracts because I know Apple still holds all the cards and could decline an app in the end if it doesnt suit their guidelines (which can be unclear sometimes). What if the customer does not want to deploy it to the app store but just want an in-house app? Is it on the customer than to purchase an Apple developer/enterprise license allowing them to do Ad hoc deployments to devices and we just supply them the application?


title: Scrum, is there a Critical Path for release planning?

text: Mike Cohn in Agile Estimating and Planning, page 154, defines a "natural order" for implementing user stories - this, according to him, is a intuitive sequence that makes sense to both developers and the team. I understand and endorse this idea. Though, I am having trouble letting go the concept of "critical path"; I see the value of ordering stories based on their dependencies. Even if the backlog is an always evolving tool, we could derive the "critical path" of the current backlog to prioritize and derive for 3-6 months worth of releases. It just does not sound right considering all I know about Agile. How do you apply the concept of critical path in Scrum? Your personal opinion would be much appreciated!