Easily moving both direction of time during a rebase

After I have written some commits, I very often `git rebase -i` over them, in order to test them, if necessary split them, take parts form one commit and `squash` them to another, more appropriate one. But there is a problem. Say, today I am hunting for a bug, that 5 recent commits are causing. I rebase interactively on the last known to work (bear with me, not using `git bisect` for a reason). The next commit introduces the bug, but is a big mess some unrelated code. So I `git reset HEAD~` and then form several internally logical commits. Here is the problem. I do not know which is the first problematic commit. So I select `edit` for all commits when rebasing. After I am done with the problematic commit, I have a couple of commits in the past, that I would like to test further. Currently, I do `git rebase --continue` many times, until the rebase is complete, and then rebase interactively again. This has a few problems:   * It is tedious. At the very least, I would like a command that rebases to the top of the branch, skipping all `edit` declared commits.   * Neverending merges. I need to merge often, and would prefer to first do the meaningful job of splitting the original commit, and only after that `git commit --ammend` the latter commits in order to be compatible with the edited hystory. * * * **TL;DR;** How can I achieve this bi-directional traversal on a branch, while at the same time, creating, removing and amending commits? Or is this workflow conceptually wrong?


Is ZeroMQ a good choice to make a Python app and a C# managed assembly work together?

I have a task that involves talking to a .NET-based API (namely AutoCAD) to retrieve data, send commands, and react to events. I want to separate the API operations and the proper program logic (largely already implemented in Python) by using natural tools for both: a C# DLL for the former and a Python app for the latter. To connect these two pieces, I began exchanging JSON in ZeroMQ messages. I'm at early development stages but having recently discovered that ZeroMQ does not guarantee message delivery/order, I have reservations about whether this is a feasible way to go. Right now my app is a very basic REQ/REP pair and I plan to handle reacting to events and executing different commands by adding some sort of 'recipient-function' field to my message format. The reason that I want to use ZMQ is that I might be able to scale the software into a larger, multi-user, distributed solution sometime. I am a lay programmer so I would ask for your advice about this architecture. Should I just go ahead with it and plan to deal with message reliability/ordering when problems appear? Should I consider developing some kind of a REST wrapper around ZMQ?


Can I use open source libraries in my project which is released into the public domain?

I am writing a Windows Phone application which I intend to release into the public domain (the source code and releated resources, that is). My application does, however, use a few third party open source libraries (statically linking to them). Does releasing my code into the public domain make any difference regarding the licenses of the open source libraries I use or would I have to make sure my (un)license is compatible with the open source licenses, the same way I would have to if I released the source code using an open source license (or kept the code closed source, for that matter)? I releasing my code into the public domain doesn't make any difference, how do I know if an open source license is usable with code released into the public domain?


Is it safe to convert Windows file paths to Unix file paths with a simple replace?

So for example say I had it so that all of my files will be transferred from a windows machine to a unix machine as such: `C:\test\myFile.txt` to `{somewhere}/test/myFile.txt` (drive letter is irrelevant at this point). Currently, our utility library that we wrote ourselves provides a method that does a simple replace of all back slashes with forward slashes:               public String normalizePath(String path) {        return path.replaceAll("\\", "/");     }      Slashes are reserved and cannot be part of a file name, so the directory structure should be preserved. However, I'm not sure if there are other complications between windows and unix paths that I may need to worry about (eg: non-ascii names, etc)


Is there any point in distributing separate .NET 3.5 and 4.0 assemblies?

I want to distribute a .NET library that is .NET 3.5 compliant. The library holds references only to external managed libraries that are targeted against .NET 3.5 client profile or lower. Is there any point in distributing my library as separate .NET 3.5 and 4.0 targeted assembly?


Exception handling in a program that needs to run 24/7

I have read that we should only catch exceptions that can be handled, which makes catching the base exception class (C# in this case) a bad idea (on top of other reasons). I am currently part of a project in which I so far have yet to see anything but the base exception being caught. I mentioned that it is considered bad practice to do so, but the response was "This service needs to run 24/7, so that is the way it is.". Since I did not have a good response for how to properly handle exceptions in a program that needs to run 24/7, I am now here. I have not managed to find any information / suggestions on how to deal with exception handling in "critical" programs / services that needs to run around the clock (and in this case I believe it may be ok if the service is down for a minute or two, so not even critical). I understand it depends on the exact nature of the program. The requirements for a program that can cause life threatening issues are quite different compared to a log scanner for an online game. Two examples: 1: A type-ahead service for customers of the Brittish railways, used when they searching online for railway stations. 2: A program that automatically controls the railway switches for the above railways based on realtime information provided from various sensors in the tracks, trains etc. The first program would probably not cause a major issue if it went down for a minute or two, wheras the latter could cause human casualties. Suggestions on how to deal with each? Pointer to where I can find more information and thoughts on this issue?


how to write safe code if you are the only developer

I have been working in a hedge fund firm for two years and I am the only person who writes almost all the codes. So far, luckily there is no software glitch or bug causing money lost. However, it is not guaranteed that it never occur. I am just wondering if there is a way to write safe code. Of course, unit test is one of the ways. But some of the tests cases are not easy to test and some situations may only occurs in a specific day e.g. busy trading day and the program cannot handle it. FYI my company will hire a less senior develop in the coming months. EDIT: Regarding the safety, the program is not allow to send numerous erroneous orders to the market like Knight Capital . To an extreme extend, program crash is far more better than it. Since I am the developer and also the tester, the software is ready to release that is based on my decision. I agree that tester is required. However, I have a concern that is the tester need to know the whole logic of the trading system which is confidential stuff.


SAP / ABAP training issues as a junior programmer

I recently got my Computer Science degree and was recruited by an SAP Partner as a "SAP NetWeaver Consultant" (at least that's what the boss calls me). The job placement stated that no previous experience in SAP nor ABAP was essential, and it also stated that the employee would be trained accordingly. I have zero background in SAP and ABAP (nor do I have any worth mentioning working experience as I'm 21 years old), I'm working with this company for one month (the only employee of the company is the boss actually). The first task I had to do was to create a new development package, including domains, data elements, structures, tables, table-types, classes, interfaces, function groups, reports, the customization of a number of BADi implementations, etc., of a system that was optimized and redesigned (by the boss). How I accomplished the above (still trying actually), was by having one or two examples by the boss of how to create each of the aforementioned things. Most of the above were no problem at all, but now that I have moved into coding, I have some huge issues. First of all, as mentioned above, I have no previous experience with SAP nor ABAP, that means that I'm ignorant when it comes to the capabilities of the language, the syntax, statements, etc., and everything around SAP NetWeaver and the ABAP Development Workbench. I have to create some simple nested loops for fetching some specific components of each of the objects contained in a structure, which structure is contained in another structure and is included in a table type. For instance... I have a function that derives all the rental objects included in a contract, and for each of the rental objects, I have to derive some specific components of all their architectural objects. While this would be easy to accomplish in a language that I already have some expertise. I have some pretty hard time trying to do it with my current skills in ABAP. I mean, even the difference in the LOOP functions messes with my ability to code, even the fact that I'm trying to comply with the naming conventions addressed by the client makes me look at everything twice for understanding what I'm actually writing. I can't even handle the debugger properly. I am sorry for all the information provided above, but I had to introduce you to the situation before asking my question. All the boss has given me is an ABAP Objects book and the access to the system of course. Is that what I should expect by training? While the boss was rather amazed at how fast I could re-create all the development objects to the new package, and make all the appropriate changes in the documentation, translation, naming etc..., he now thinks that I don't know what a structure, table or loop is. And the fact is, that I do know all the above, but not in ABAP... I do not know how to proceed or how should I approach my issue, the boss can't waste much time with me, as he is all the time running to clients and also designing and implementing add-ons by himself. Should I expect something more from his part?


A deque based on binary trees

This is a simple immutable deque based on binary trees. What do you think about it? Does this kind of data structure, or possibly an improvement thereof, seem useful? How could I improve it, preferably without getting rid of its strengths? (Not in the sense of more operations, in the sense of different design) Does this sort of thing have a name? Red nodes are newly instantiated; blue ones are reused. Nodes aren't actually red or anything, it's just for emphasis. ![http://goo.gl/KzOFR](http://i.stack.imgur.com/76kzH.png) Note that right deques do _not_ take O(n). Any access to an element in the deque depends on how long ago it was inserted. You can perform any enqueue or concat operation at O(1). You can also use the 'weight' of each non-leaf node to change the orientation of the tree, such as to make all right access costly and left access cheap, or to provide O(logn) access to either end. This process takes O(n) worst case, depending on the initial orientation of the tree. Alternatively, I could 'search' for the lightest node into which to insert a given node, turning all operations into O(logn) operations.


Closest location - Heapify or Build-heap

So lets say we have a set of gps data points and your current location. If asked to give the closest point to your current location we can utilize a heap with the distance being the key. Now if we update the current location, I suspect that only a few of the keys will change enough to violate the heap property. Would it be more efficient to rebuild the heap after recalculating the keys or to run heapify (assuming that only a few of the keys have changed enough). It is assumed that we don't jump around with the new location (new current location is close to the last current location).


Entity and pattern validation vs DB constraint

When it comes to performance: What is the better way to validate the user input? If you think about a phone number and you only want numbers in the database, but it could begin with a 0, so you will use varchar: Is it better to check it via the entity model like this:                @Size(min = 10, max = 12)      @Digits(fraction = 0, integer = 12)      @Column(name = "phone_number")      private String phoneNumber;      Or is it better to use on the database side a CHECK (and no checking in the entity model) for the same feature?


C++ and the use of old Visual Studio versions

Based on the behavior of some of our customers, I have come to wonder if many c++ development shops decided to just stop at vs2005. Is this just a quirk of the dozen or so large organizations that we deliver DLL+IMPLIB to, or is there a general groundswell of disinterest in the industry at large in upgrading? Note that there's no MFC at work here, just a Windows compile of C++ code that is also delivered on linux and whatnot. And the question is, "Is it my imagination, or is it that big companies that build things like search engines in C++ have just stopped upgrading?" **NOTE** None of the answers so far appear to report actual personal experience with making a decision to upgrade or not, but rather either offer general principles or report very vague hearsay.


Are trivial protected getters blatant overkill?

Something I really have not thought about before (AS3 syntax):               private var m_obj:Object;     protected function get obj():Object     {         return m_obj;     }          private var m_str:String;     protected function get str():String     {         return m_str;     }      At least subclasses won't be able to set m_obj or m_str (though they could still modify m_obj). **My question:** Is this just blatant overkill? * * * This Programmer's question: When or why should one use getters/setters for class properties instead of simply making them public properties? has been suggested as a duplicate. That question is different because it only addresses public vs. private properties and whether a property should be wrapped with getters & setters. For my question, I'm focusing on _protected_ variables and how inheriting classes would interact with those variables. So the alternative implementation would be:               protected var m_obj:Object; //more accessible than a private variable with a protected getter     protected var m_str:String; //more accessible than a private variable with a protected getter      My question is similar because I am talking about using _trivial_ protected getters to block _subclasses_ from writing to the variables, but to allow them all other access.   In languages like AS3, this will even allow them to make any changes to mutable object variables, as long as the references themselves are not modified.


Variable names for Contact Information bits

I am in the middle of refactoring code and would like to get some ideas on variable naming so that my new names clearly represent the data they hold. I have a class called `ContactMethod` which makes sense to me; each instance is a different way to contact someone. My problem comes when naming the properties of `ContactMethod`. For example, one instance might be a Fax number of 555-555-5555 while another could be an Email address of bob@email.com; I've got a property called `contactMethodType` to hold the values "fax" or "email", but I don't know what to call the "555-555-5555" or "bob@email.com" part. Has anyone here created a good generic name for this piece of contact information? _(PS - the old convention was to call it a "Phone" with fields "phoneType" holding the "fax"/"email" value and "phoneId" holding the number/address. Yuck.)_


Implementing objects with several equivalent representations

I am wondering if there are patterns, references or useful resources about how to implement objects that may have several equivalent representations. For example: Suppose I want to implement a `Rectangle`, and I will instantiate it using its `length` and `width`:               class Rectangle:         def __init__(self, length, width):             self.length = length             self.width = width      and suppose now I also want to have the possibility to instantiate the `Rectangle` using its `diagonal` and `area`. My main concern is that I don't want to store redundant information in the object (in this case, these four properties), only the bare minimum possible to define it. Suppose too I might want to retrieve one set of properties having created the `Rectangle` using another:               r = Rectangle(length=3, width=4)     assert r.diagonal == 5      This is what I've tried so far:               class Rectangle:         def __init__(self, **kwargs):             params = set(kwargs.keys())             if params == set(['length', 'width']):                 self._length = kwargs['length']                 self._width = kwargs['width']             elif params == set(['area', 'diagonal']):                 self._area = kwargs['area']                 self._diagonal = kwargs['diagonal']             else:                 raise ValueError('Invalid input arguments')              @property         def length(self):             if hasattr(self, '_length'):                 return self._length             elif hasattr(self, '_area') and hasattr(self, '_diagonal'):                 length, width = ad2lw(self._area, self._diagonal)                 #r = Rectangle(length=length, width=width)                 #return r._length                 return length             else:                 raise NotImplementedError('No converter available')              # Same with other three properties               def ad2lw(area, diagonal):         # Obscure math         return l, w      Is this any known pattern or is there a standard way to do it?


MVC in a desktop application - can the View ever hold a reference to the Model?

(I'm specifying this is a desktop application so people wouldn't refer specifically to web implementations of MVC). The title says it all pretty much. In an MVC structure - **can the View _ever_ hold a reference to the Model?** Or should the Controller be used as a 'middleman' for communication between the View and Model - always - and in both directions? If the answer is "no, it can't" - **why?**


Fine Line: Readability Vs Speed

Is there a line between readability vs compile or processing speed? Aside from the extreme cases, I wouldn't think it would be even worth saving that little bit extra in favor of legibility... For example; a bad idea, in my opinion would be removing all the comments on a 'finished' product to gain a little extra speed.


Have you dealt with space hardening?

I am very eager to study best practices when it comes to space hardening. For instance, I've read (though I can't find the article any longer) that some core parts of the Mars rovers did not use dynamic memory allocation, in fact it was forbidden. I've also read that old fashioned core memory may be preferable in space. I was looking at some of the projects associated with the Google Lunar Challenge and wondering what it would feel like to get code on the moon, or even just into space. I know that space hardened boards offer some sanity in such a harsh environment, however I'm wondering (as a C programmer) how I would need to adjust my thinking and code if I was writing something that would run in space? I think the next few years might show more growth in private space companies, I'd really like to at least be somewhat knowledgeable regarding best practices. What happens to a program if radiation, cold or heat bombards a board that sustained damage to its insulation? I think the goal is keeping humans inside of a space craft (as far as fixing or swapping stuff) and avoiding missions to fix things. Furthermore, if the board maintains some critical system, early warnings seem paramount. How does one gain experience in this through testing and trial & error (barring the launch of your own personal satellite?)


How does recording video and playing it back in realtime work?

I am looking to understand how recording video (and audio) and playing it back in realtime work (on the same pc or over a network)? I understand for a file stored on the disk. You read it and play it back but in recoding, you don't know how long the file is, when it will end etc. Can someone explain it, preferably using some code (or psudocode)? Thanks


Android -> Ruby Server Interface -> Mongodb

I've been wrecking my brain about this for a few days. I'll run my scenario by you and hopefully you can help me. In my head this is how it goes: I have an Android App. I want my Android App to make (function) calls to a MongoDB database via a Ruby Interface on the Server. e.g. Android app sends a HTTP GET ? with the function name, let's say getFriends for this user Ruby Interface receives this request from the app, grabs a thread from a thread pool and calls the appropriate function call implemented in Ruby, to the Mongodb. Ruby Interface gets results from Mongodb and sends a HTML POST to the Android app. So that's how I think it works. I know about the ruby driver for mongo db, and interacting with the mongodb from ruby but, how do I make a ruby back end listen for incoming messages and should these messages be done through sockets or a http interface ala Net::http in ruby?


Should we create classes just to group properties

I am designing a bit of software that will integrate with our enterprise system using web services. We are dealing with work orders that are needed to maintain equipment. We have a bit of a disagreement in regards to the structure of the contract. There are two methods on my side, I would like a single work order class with all properties related to the work order in it. example (simplified)               WO - class       Number - property       Description - property       WarrantyStatus - property       WarrantySettlementDate - property       LabourSteps<LabourStep>[] - list property       Children<WO>[] - list property      On their side, they want to create a work order class, but for each logical group of data, they want to create another class to wrap the properties. example (simplified)               WO - class       WOHeader - class         Number - property         Description - property       Warranty - class         WarrantyStatus - property         WarrantySettlementDate - property       LabourSteps<LabourStep>[] - list property       Children<WO>[] - list property      Now they will have approx 8 classes in the full definition that they want to create all with a few properties in each. This seems a bit over the top to me and has a bit of a code smell or anti pattern feel to it. For my example, I have two classes, WO and LabourStep. They have 4 classes for the same thing WO,WOHeader,Warranty,LabourStep. There will only ever be one WOHeader per WO and the same for Warranty. My one seems far simpler to manage changes (add a new property to WO and thats it), but is less human readable. On their side, The structure is a little more easier to read by a human, but it feel like its pushing a logical view onto the contract the doesn't really belong. And to add a new property potentially requires a modification to the WO and the creation of a new class if a new logical group was added. These extra classes are only there to group properties. What is the right way to go? ======EDIT========== Frank - I completely agree with your thoughts and it is the way I approach my development. Except in this case, the third party monolithic enterprise system we are integrating with has been written in a very generic way to try and cater for as many businesses as possible. The data is spread across three tables in a one to one mapping with the majority in one table. There is barely any validation. There is no concept of a "Warranty" object/thing in that system. Its just 3 properties against a WO. All the web service will do is act like a data store, with the WO persisted as a whole. e.g. getWO() updateWO() createWO(). There will never be get/updateWarranty() methods. It's all just one blob of data to read/persist. On our side, we never use the result directly from web services even if they are our own. We convert them into proper models and then use those. To us a data contract is very different to a model. There is no business logic in the data contract, its purely a container to get data from one part of the system to another without closely coupling them. That means we can easily change to persist to a database instead of a web service and all its needs to do is match the interface of the web service. This also allows us to modify our own models which may even include results from multiple web services without having to worry about being restricted to or changing the format of the data contracts. So when I think in those terms, Having the data contracts split into WOHeader or WOWarranty classes just doesn't make any sense. It will never used in that way, not even by them. Its just there for a nice logical group of properties that mean nothing by themselves. A region block around those properties would have the same net effect. Labour steps and equipment details however, make a lot of sense to be in separate classes as they are separate entities and not just properties of work orders.


Does boostrapping limit the achievable speed of the new compiler?

I have a good grasp on how the C compiler was boostrapped from itself and how that must have been very efficient, since the first pre-bootstrapping version was written in assembler, which is as low level as you can get. BUT today we have a very different situation, with languages first written on other relatively high-level languages (e.g. Clojure). Question 1: I have a hard time imagining that the **bootstrapped compiler could be _faster_ in anything than its non-bootstrapped counterpart. Is this possible?** Question 2: Especially once you take the step in which you write then new version of your compiler in your new language: **Can any inefficiencies that existed in the non-bootstrapped code be fixed or is the code generation of the new compiler haunted by those forever?** That matters even more since you can’t easily go back and fix those afterwards!


How to keep background requests in sequence

I'm faced with implementing interfaces for some rather archaic systems, for handling online deposits to stored value accounts (think campus card accounts for students). Here's my dilemma: stage 1 of the process involves passing the user off to a thrid-party site for the credit card transaction, like old-school PayPal. Step two involves using a proprietary protocol for communicating with a legacy system for conducting the actual deposit. Step two requires that each transaction have a unique sequence number, and that the requests' seqnums are in order. Since we're logging each transaction in Postgres, my first thought was to take a number from a sequence in the DB, guaranteeing uniqueness. But since we're dealing with web requests that might come in near-simultaneously, and since latency with the return from the off- ste payment processor is beyond our control, there's always the chance for a race condition in the order of requests passed back to the proprietary system, and if the seqnums are out of order, the request fails silently (brilliant, right?). I thought about enqueuing the requests in Redis and using Resque workers to process them (single worker, single process, so they are processed in order), but we need to be able to give the user feedback as to whether the transaction was processed successfully, so this seems less feasible to me. I've tried to make this application handle concurrency well (as much as possible for a Ruby on Rails app), but now we're in a situation where we have to interact with a system that is designed to be single process, single threaded, and sequential. If it at least gave an "out of order" error, I could just increment (or take the next value off the sequence), but it's designed to fail silently in the event of ANY error. We are handling timeouts in a way that blocks on I/O, but since the application uses multiple workers (Unicorn), that's no guarantee. Any ideas/suggestions would be appreciated.


Class Design and Structure Online Web Store

I hope I have asked this in the right forum. Basically, we're designing an Online Store and I am designing the class structure for ordering a product and want some clarification on what I have so far: So a customer comes, selects their product, chooses the quantity and selects 'Purchase' (I am using the Facade Pattern - So subsystems execute when this action is performed). My class structure:                  < Order >                 < Product >                    <Customer >      There is no inheritance, more Association < Order > has < Product >, < Customer > has < Order > . Does this structure look ok? I've noticed that I don't handle the "Quantity" separately, I was just going to add this into the "Product" class, but, do you think it should be a class of it's own? Hope someone can help.


How to design the relation between a Game and a Player in a game?

I am currently attempting to make a Trading Card Game and I have got a whole array of features working already, yet I am stuck now at the portion where one player can attacker another player (more strictly: the monster cards of another player on the field). The game is designed primarely to be played with two players in mind, though having it open for future extensions is never a bad idea. This is the design I have so far, shown as a minimalistic example in pseudo- code:               class Game         private final Player self         private final Player opponent          class Player         private final String name         ...      The game loops over all players and lets them do their turn, which may involve attacking another player. That method has the following structure:               class AttackMonsterAction         private final int monsterIndex         private final int targetMonsterIndex         private final Player targetPlayer              public void performAction(final Player player)      If it is of any relevance, I am coding this in Java. My concrete question is the following: How do I create my class design such that `AttackMonsterAction` called from a certain `Player` object, can reference "the other player"?


Why did Alan Kay say, "The Internet was so well done, but the web was by amateurs"?

OK, so I paraphrased. The full quote: > The Internet was done so well that most people think of it as a natural > resource like the Pacific Ocean, rather than something that was man-made. > When was the last time a technology with a scale like that was so error- > free? The Web, in comparison, is a joke. The Web was done by amateurs. -- > Alan Kay. I am trying to understand the history of the Internet and the web, and this statement is hard to understand. I have read elsewhere that the Internet is now used for very different things than it was designed for, and so perhaps that factors in. What makes the Internet so well done, and what makes the web so amateurish? _(Of course,Alan Kay is fallible, and no one here is Alan Kay, so we can't know precisely why he said that, but what are some possible explanations?)_ *See also _the original interview_ *.


Applying DDD to a simple app with a configuration twist

I’m using the light-weight PHP Fat-Free Framework as a base to form a simple MVC based app with DDD philosophy for the Model layer. I’m aware that DDD is most suitable or enterprise solutions and that applying DDD to simple, mostly data-driven apps is kind of an overkill, but there are some concepts in DDD that I find appealing (like the Repository pattern, business logic in Entities, etc.) which I’d like to apply to my app. Fat-Free Faramework has a Base class that represents the application (a Singleton) and the instance of Base holds a lot of useful tool methods and a registry of global framework variables (the hive) which is used, among other things, for configuration data. As I’m writing my app, I find myself using a lot of Base class tools inside classes in the Model layer, and I’m a bit confused by how to reference the Base instance in those classes. Do I simply call Base:instance() inside model classes or do I inject it through the constructor as a dependency? Dependency injection seems like the proper way to do it, but since most of the app will depend on it, the whole reference passing through the constructor seems unnecessary. Also, how to pass for an example database config data to data persistance classes which is stored in the hive? Should it be passed by the Controllers when instantiating Repositories or called directly from the Repository (or Data Mapper)? I’m looking for a way which won’t fire back on me, so I’m looking for any insight or advice on this. The second part of my problem is that I’m trying to write my app so that each Entity and business logic related to it is configurable from the Entity class. This is an idea inspired by Sails.js I’m still testing out, but for an example, I have a method getProperties() which returns an array of user- defined configuration data for each Entity property, e.g.:               'title' => array(         'type' => 'text',         'minLength' => 30,         ...     )      or for associations:               'children' => array(         'entity' => 'ChildClass',         'relation' => 'oneToMany'     )      It might look a bit controversial, but I’ve tested business logic functionality and so far it works OK for me, and client code communicates with entities via usual get/set/other methods. The idea behind such configuration is to be able to automatically generate scaffolding/administration interface for each Entity, and configure Data Mappers and Repositories based on the related Entity’s getProperties() method. What’s bugging me now is that if I want to have _one_ place where this configuration data exists, I’d have to place some non-business-domain logic into the Entity, such as an exceptional database table name, whether a field requires a rich-text editor or not, whether a checkbox is checked by default, a certain field used as an Entity’s print identity in the admin web interface, etc. I realise that the problem I have is a tradeoff between a clean model and the single-place configuration idea and that I’ll probably have to pollute the Entities by storing such non-business-domain data into the Entites, but I thought perhaps someone here might have an idea about how to approach this in a different, or better way? Thanks for reading.


Why does Java use so many middlemen?

For example to read data from a website we do:               HttpResponse httpResponse = httpClient.execute(httpPost);             HttpEntity httpEntity = httpResponse.getEntity();             is = httpEntity.getContent();      The method that executes the HTTP request, returns a response, then we turn the response into an entity, then we turn the entity into a input stream, then you got to use two more objects, a buffer reader and a string builder,to turn that is into a string. It just seems like a lot of repetitive code. Why can't HttpResponse have a method that returns an InputStream, or better yet a String? P.S. I'm not necessarily saying that Java is wrong, I want to find out what the reason behind it is, if any.


What are the solutions to the Distributed Queue problem?

I am trying to learn more about the various ways that the problem of a Distributed Queue may be solved. So I would like know what products, services, implementations and research papers that are already out there. An implementation will face many challenges and will be forced to make tradeoffs:   * Does it have strong or loose ordering?   * Does it have idempotent put?   * Can we have more queues than what can fit on a single machine?   * Can we have more data in a queue than what can fit on a single machine?   * How many machines can crash before we potentially lose data?   * Can it tolerate net-splits?   * Can it automatically reconcile data when a net-split is fixed?   * Can it guarantee delivery when clients can crash?   * Can it guarantee that the same message is not delivered more than once?   * Can a node crash at any given point, come back up, and not send out junk?   * Can you add nodes to, or remove nodes from, a running cluster without down time?   * Can you upgrade nodes in a running cluster without down time?   * Can it run without problems on heterogeneous servers?   * Can you “stick” queues to a group of servers? (example: “these queues are only allowed in the european datacenter”)   * Can it make sure to put data replicas in at least two datacenters, if so available? I have no illusion that any implementation will be able to say “yes” to all of that. I am merely interested in hearing about the various implementations; how they work, what tradeoffs they have made and perhaps why they decided on their particular set of tradeoffs. Also if there are any challenges that I may have missed in the above list.


Making Separate Assemblies For Different Types Of Tests For The Same Component?

I was told by a few members here that splitting up my unit tests into different assemblies for different components is the best way to structure unit tests. Now, I have a few questions about that idea.   1. What are the advantages of this? Organization, and isolation of errors?   2. Let's say I have a component named "calculator", and I create an assembly for the unit tests on "calculator". Would I create a separate assembly for the integration tests I want to run on "calculator"? Or is the definition of an integration test a test across multiple components, like "calculator" and whatever else, which would require a separate assembly to test both of them together? In that case, would I have one assembly to do all of the integration testing for every component combination?


What's the proper way to exit program in C?

There are many ways how to exit program in C. Some of them are returning zero or error code, using exit function with EXIT_SUCCESS, EXIT_FAILURE, exit(0), exit(1) or some other error code, abort and probably few more I can't think of now. My question is which option is the best and why. I'm asking here because every time I asked more experienced programmers this question, it ended up as a holy war.


MSFT released "ASP.NET Developer Guidance" PDF... What's missing in your opinion?

Microsoft created this ASP.NET documentation map that aggregates a ton of great links into a single PDF. http://blogs.msdn.com/b/jmeier/archive/2010/10/26/asp-net-developer-guidance- map.aspx?CommentPosted=true I'm interested in hearing what others have to say about this doc, and if they think other resources should be added. Perhaps MSFT will read this thread and incorporate your tips in this all-encompassing ASP.NET learning guide as well.


Does cherry-pick just pull changes into the current working tree as uncommitted changes?

My team uses Mercurial for version control. Our development / version control routine is:   1. all been committing to the same branch   2. pulling for changes and rebasing our commits locally before pushing back to the hosted repository This keeps everyone in sync. And the latest code (even unfinished code) is than grabbed from the tip of this branch and put into our test environment. I've been tasked with creating a management process where we can more cleanly extract "completed features" into the test environment. I've advocated that we begin to `branch->pull-request->merge->close branch` process, but I've been told that `branching` is not an option, and that the project director would prefer too be able to _manually select commits representing completed features/bug fixes_ and only include those commits in a deployment to testing. I am not sure what terminology besides `cherry-pick` in GIT / HG that would represent this process, and if it would even be advisable as the commits would no-longer have a proper revision history as it's my understanding that `cherry-pick` just pulls changes into the current working tree as uncommitted changes _correct_?


As a programmer, should I know low and high-level programming languages?

I been contacted to do some work remote controlling LEDs displays over TCP/IP, but my experience and preparation is mostly about high-level programming language. I said that to the person who contact me about the work and he told me that: > "if you call yourself a programmer you should know all these things" Should a programmer really know the details of low-level programming? Or can I treat it as a black box concept, as theoretical knowledge but not necessarily doing it or implementing low level language solutions, having in mind that low-level programming is not my expertise?


How to design a scriptable communication emulator?

Requirement: We need a tool that simulates a hardware device that communicates via RS232 or TCP/IP to allow us to test our main application which will communicate with the device. Current flow:   * User loads script    * Parse script into commands    * User runs script    * Execute commands Script / commands (simplified for discussion):   * Connect RS232 => RS232ConnectCommand   * Connect TCP/IP => TcpIpConnectCommand   * Send data => SendCommand   * Receive data => ReceiveCommand   * Disconnect => DisconnectCommand All commands implement the ICommand interface. The command runner simply executes a sequence of ICommand implementations sequentially thus ICommand must have an Execute exposure, pseudo code:   * void Execute(ICommunicator context) The Execute method takes a context argument which allows the command implementations to execute what they need to do. For instance SendCommand will call context.Send, etc. **The problem** RS232ConnectCommand and TcpIpConnectCommand needs to instantiate the context to be used by subsequent commands. How do you handle this elegantly? **Solution 1:** Change ICommand Execute method to:   * ICommunicator Execute(ICommunicator context) While it will work it seems like a code smell. All commands now need to return the context which for all commands except the connection ones will be the same context that is passed in. **Solution 2:** Create an ICommunicatorWrapper (ICommunicationBroker?) which follows the decorator pattern and decorates ICommunicator. It introduces a new exposure:   * void SetCommunicator(ICommunicator communicator) And ICommand is changed to use the wrapper:   * void Execute(ICommunicationWrapper context) Seems like a cleaner solution. **Question** Is this a good design? Am I on the right track?


Where to find Hg/Git technical support?

I would like to out who provides technical support (commercial) for two major DVCS's of today: Git and Mercurial. This is for a place where they've been using Subversion for some time and now they're renewing their software licences. Although they will be keeping Subversion as well, they would like to justify beginning of DVCS as an alternative system. Most people root for Mercurial since it seems simpler; mostly engineers and physicians there who are not that interested in checking Git repos for corruption and the finer workings of Git, but I believe any one of the two could "pass". The system has to have a price (can be zero; no problem there) and some sort of official technical support. It is a _pro forma_ matter, but it has to be specified. _**So, I'm asking you: do you know where could one go for commercial Git or Mercurial technical support?_** Technical forums and the like are out of the question. It has to work on the principle:   * _I have a problem._   * _I post a question with the details._   * _I get an answer in specified time. It can be "we cannot do that." but it has to be an official answer and given in agreed time._ I'm sure by now most of you understand what I'm asking, but if not — post a comment or similar. Also, if you think of any reasons which could decide justification of introducing Git/Hg from an technical and administrative viewpoint, feel free to write them down also.


iPhone development options for the [from-my-cold-dead-hands] C developer

Please forgive the humor of the title but it certainly gets my point across. I am quite familiar with C code, I can write it in my sleep and after reading through a few tutorials on iPhone development and Objective-C, I'm beginning to feel like I'd rather avoid Obj-C at all costs. It's not that it's unlearnable or "hard". I just don't like it and after reading through many of the Pros and Cons of Objective-C vs. straight C, I've determined that if I need to write an iPhone App, I want to write as much of it as C as is possible. With that said, what is the minimum amount of Objective-C that I need to be aware of or potentially write to be able to create an iPhone app? If I can't write an app 100% in C, then is there a good reference that discusses writing iPhone Apps in C and only discusses the minimal amount of Objective-C logic that needs to be written to get an application to compile and run? Also, is there any good reason why I should learn Objective-C if I don't have to use it for a C project? Specifically, are there times when Objective-C may provide a more optimal coding solution to a problem because of the way the compiler compiles and link the code? I may be a C advocate but more important than that I want to be sure that my application runs as smooth and optimally as possible. **Disclaimer** I am at an early learning stage of a project I may have to work on in the near future. If this process comes to fruition, I'll be getting a Mac as well as a developer license so I'm completely in ignorance. Even worse, _if_ this project is determined to be feasible, I will then be getting the necessary equipment to develop for the iPhone. For now, I'm trying to learn as much information as I can and explore my options. I'd appreciate any (constructive) thoughts, tips and suggestions.


When decomposing a large function, how can I avoid the complexity from the extra subfunctions?

Say I have a large function like the following:               function do_lots_of_stuff(){              { //subpart 1           ...         }              ...              { //subpart N           ...         }     }      a common pattern is to decompose it into subfunctions               function do_lots_of_stuff(){         subpart_1(...)         subpart_2(...)         ...         subpart_N(...)     }      I usually find that decomposition has two main advantages:   1. The decomposed function becomes much smaller. This can help people read it without getting lost in the details.   2. Parameters have to be explicitly passed to the underlying subfunctions, instead of being implicitly available by just being in scope. This can help readability and modularity in some situations. However, I also find that decomposition has some disadvantages:   1. There are no guarantees that the subfunctions "belong" to do_lots_of_stuff so there is nothing stopping someone from accidentally calling them from a wrong place.   2. A module's complexity grows quadratically with the number of functions we add to it. (There are more possible ways for things to call each other) **Therefore:** Are there useful convention or coding styles that help me balance the pros and cons of function decomposition or should I just use an editor with code folding and call it a day? * * * EDIT: This problem also applies to functional code (although in a less pressing manner). For example, in a functional setting we would have the subparts be returning values that are combined in the end and the decomposition problem of having lots of subfunctions being able to use each other is still present. We can't always assume that the problem domain will be able to be modeled on just some small simple types with just a few highly orthogonal functions. There will always be complicated algorithms or long lists of business rules that we still want to correctly be able to deal with.               function do_lots_of_stuff(){        p1 = subpart_1()        p2 = subpart_2()        pN = subpart_N()        return assembleStuff(p1, p2, ..., pN)     }


Looking for an example of how a software project can be managed/deployed

My company is evaluating adopting off-the-shelf ALM products to aid in our development lifecycle; we currently use our own homegrown solutions to manage requirements gathering, specification documentation, testing, etc. One of the issues I am having is understanding how to move code between stages of development. We have what we call a pipeline, which consists of particular stops: [Source] -> [QC] -> [Production] At the first stop, the developer works out a solution to some requested change and performs individual testing. When that process is complete (and peer review has been performed), our ALM system physically moves the affected programs from the [Source] runtime environment to the [QC] runtime environment. This movement of code is triggered by advancing the status of the change request to match the stage of the pipeline. I have been searching the internet for a few days trying to find how the process is accomplished elsewhere -- I have read a bit about builds, automated testing, various ALM products, etc. but nowhere does any of this state how builds interact with initial change requests, what the triggers are, how dependencies are managed, how the various forms of testing are accommodated (e.g. unit testing, integration testing, regression testing), etc. Can anyone point me to any resources detailing specific workflows or attempt to explain (generically) how a change could/should be tracked and moved though the development lifecycle? I'd be very appreciative. Note: I've cleaned up the question to hopefully make it easier to understand. Also, I found another question (which I can't find now) that referenced this book, which sounds like it might be exactly what I am looking for -- not sure if I want to shell out the cash for it, though. Additional details per @GlenH7's suggestion: Our products are built with a proprietary language and set of translation tools -- the ultimately runtime environment is similar to a web site architecture, in that we have a bunch of 'code' files sitting out on a server, which our client app accesses on-demand (not unlike a GET request) and then interprets to provide the user experience. We sell an integrated product which is made up of a set of modules (most of which are optional), each module has a team of ~4 programmers and 2 QC testers devoted to the development/bug maintenance. There are around 30 modules per product line (and 3 product lines) -- some teams maintain multiple products lines for their given module. In total, we have 700 employees devoted to development and ~200 programmers. Certainly adopting any new processes or systems is going to involve buy-in, etc. but I'm tasked with simply understanding how the code will be managed so that we can speak intelligently about things. My first task was to learn how to adopt version control into our process (we do not yet use formal version control for most of our product lines, we rely instead of keeping around multiple copies of the entire codebase). We follow the waterfall method pretty closely (which sucks, but the company has been producing software since 1969, so it was probably the natural fit back then and until now, there has been no need to change anything). Some folks are intrigued by the various offerings of the agile methodologies, but as has been noted by @Chad below, we're likely going to need to take incremental steps towards any such end goals (though if we adopt an ALM system, it might be the time to just force a whole new way to do things on everyone). Now for a specific example of our current process, let's say we have a product called HIS, which has an MIS and ITS module (what these are/could be is not important -- think of them as just a collection of files) -- in our current process, if someone requests a change to ITS, a coder will modify some files (effectively) on the development server. When that change needs to be tested, transitioning the status of the change request from 'development needed' to 'qc needed' will trigger our tools to copy the affected files from the development server to the QC server. Now when QC testers signon to the QC testing environment, they will be able to see the effect of the changes. Once they signoff on the change, advancing the status of the request to 'production ready', our tools again copy the code files to the next stage. Once signed off there, a final copy is done to the holding location used for deliveries to customers. We manage delivery of our releases by a major release number (e.g. 6.0) followed by a service release designation (e.g. 5) and a 'priority pack' number (e.g. 1) -- customers take delivery of priority packs, e.g. 6.0.5.1. As stated above, we simply push code from place to place on multiple servers, so we end up with a project folder for each major release and service release throughout the pipeline and end up with a final resting place for each of the ppacks, e.g.:               dev6.0     qc6.0     production6.0          dev6.0.5     qc6.0.5     production6.0.5          ship6.0.5.1      I was thinking that under version control, we could simulate this kind of scheme as:               trunk     branches     --6.0.5     tags     --6.0.5.1      but that seems to cover only half of the locations, i.e. where do the qc and production sources live? Would I create a separate trunk for each major and minor release of the product? Or would I rely on something outside of version control (e.g. the ALM system) to track the revision(s) interesting for testing done at the QC and production stops? We'd need a runtime environment for each, still, but that could be 'built' on-demand as bug fixes and features are made available -- which reinforces the idea that I need not keep any special 'copy' of these stages under version control (they are simply references to revision history of the trunk or branch). Another thing that has thrown me for a loop as that a colleague is pretty adamant that you should not persist anything in branches, i.e. the branch folders should be ephemeral and used only during large changes that can't be committed directly to the trunk (with the expectation that the branch will eventually be merged into the trunk). In his scheme, the minor releases would necessitate a separate top-level with it's own set of trunk, branches and tags, e.g.:               product6.0     trunk     branches     --silly_new_feature     tags     --6.0.5          product6.0.5     trunk     branches     --crazy_bug_fix     tags     --6.0.5.1      (sorry for the delay on adding these details -- got pulled away to meetings all day)


How far back do you use your version control and for what reason?

Typically when i work on a project i only go back a few days or the last major change when i decide to do something drastic. I sometimes notice i broke a test or a feature and overlooked it for a few weeks so i may go back a month or two and see if the feature or test is broken and trace down the week i broke it. Then find what change did it. On a long term project over the span of a year. Do you actually go back 6+ months and if so why?


Design pattern for an automated mechanical test bench

**Background** I have a test fixture with a number of communication/data acquisition devices on it that is used as an end of line test for a product. Because of all the various sensors used in the bench and the need to run the test procedure in near real-time, I'm having a hard time structuring the program to be more friendly to modify later on. For example, a National Instruments USB data acquisition device is used to control an analog output (load) and monitor an analog input (current), a digital scale with a serial data interface measures position, an air pressure gauge with a different serial data interface, and the product is interfaced through a proprietary DLL that handles its own serial communication. **The hard part** The "real-time" aspect of the program is my biggest tripping point. For example, I need to time how long the product needs to go from position 0 to position 10,000 to the tenth of a second. While it's traveling, I need to ramp up an output of the NI DAQ when it reaches position 6,000 and ramp it down when it reaches position 8,000. This sort of control looks easy from browsing NI's LabVIEW docs but I'm stuck with C# for now. All external communication is done by polling which makes for lots of annoying loops. I've slapped together a loose Producer Consumer model where the Producer thread loops through reading the sensors and sets the outputs. The Consumer thread executes functions containing timed loops that poll the Producer for current data and execute movement commands as required. The UI thread polls both threads for updating some gauges indicating current test progress. **Unsure where to start** Is there a more appropriate pattern for this type of application? Are there any good resources for writing control loops in software (non- LabVIEW) that interface with external sensors and whatnot?


Bringing in New Architecture During Maintenance on Legacy Systems

I have been tasked with adding some new features to a legacy ASP.NET MVC2 project. The codebase is a disaster and I want to write these new features with some thought behind the implementation and not just throw these new features into the mess. I would like to introduce things like dependency injection and the orchestrator pattern; just to the code that I am going to write. I don't have enough time to try to refactor the entire system. Is it OK to not be consistent with the rest of the codebase and add new features following different design principles? Should I not introduce new patterns and just get the features implemented? I feel like it might be confusing to the next person to see parts of the system using a design that other parts are not following.


What are the arguments for/against Code Generation?

I'm in a position where we've got some brittle code that constructs SQL-like queries via text concatenation with parameters for inputs. The data source that it queries is fast and scalable but lacking tool support. Over time, addition entities and properties have been added to the data source that need changing or have obsoleted others, so the queries need changing. I can see that this will happen again in a few months and then again. In order to reduce errors introduced into the text queries, I suggested writing the queries into a separate e.g. .SQL file and then running some kind of code generator tool that could get the schema from the data source and generate a code wrapper around the SQL-like query which was easy to re- generate at any time and would give compile errors for any out-of-date client code. This idea was met with some skepticism and resistance, even when I offered to fund the development myself. What are the reasons against doing this? and, for balance, the reasons to go ahead and do it? (I already saw this post with a couple of answers, but its' not comprehensive)


Name for the process of prototype evolution

I'm looking for a commonly used name for the process of developing a child object from a parent object, either through clone-and-modify techniques or through the prototypal inheritance mechanisms available in a language like JavaScript. In _JavaScript: The Good Parts_ , Douglas Crockford uses the method name _beget_ for this procedure. That seems a bit too graphic for my tastes, and I've not seen it used elsewhere. ECMAScript 5 and some frameworks just use the method name _create_. E.G. _Take care when_ **———** _prototype X not to override this attribute._ My ideas are _evolving_ , which feels sort of pretentious, and _adapting_ , which just seems vague. _Deriving_ might work, but might also be confusing since it is commonly used when discussing classical inheritance. The term _extending_ might be applicable, but seems to imply that the original object is being modified, which is not the case here. Underscore.js seems to make this available via e.g. `_(o).chain().clone().extend(o2)`. Is there a succinct and widely used term for this procedure?


Why are strings so slow?

Ever since my very first programming class in high school, I've been hearing that string operations are slower -- i.e. more costly -- than the mythical "average operation." Why makes them so slow? (This question left intentionally broad.)


Scala: From concept to working

Second attempt to ask my question more concisely. I want to say I am a Scala fan, or at least I want to be. I've resigned myself to learning one of these functional languages [Scala, Haskell, Erlang]. I've dabbled in all of them, far and away I have spent the most time trying to understand Scala. I've honestly used the tutorials for Haskell and Erlang more as a tool for greater understanding in Scala. I do believe that I have on some level an understanding of the basics. But, the reason why I thought I wanted to go with Scala is proving to be the most fustrating ... The verboseness of most Java libraries are ... umm yeah, SNMP4j makes me want to rip my hair out. So here we go, does anyone know of a site or tutorial similar to "Write Yourself a Scheme in 48 hours." Something that really shows how you go from concept to working project including interpreting some third party libraries. Or is Scala truthfully just a better Java? Meaning that it's best to learn Java before attempting Scala. * * * I didn't mean to infer that Scala wasn't a language in it's own right. On the contrary, I feel that it is a very good language; however, the bill of sale for Scala _IS_ that it is better at Java than Java. So I am really trying to answer for myself how viable it is to learn Scala, while I really don't have much of an interest in learning a lot of Java. I want to use the libraries since there is the biggest advantage, as perceived by some, in using Scala. If some of these library implementations are so 'complex' that they require, not just are best benefited by, having a good grasp of Java programming idioms, then I would like to know that I've been approaching this problem from the wrong direction. I realize there are some good examples of some libraries that have been 'scalifed' or what have you.


Is it a good idea to dynamically position and size controls on a form or statically set them?

I've worked mostly with interface building tools such as xCode's Interface Builder and Visual Studio's environment to place forms and position them on screens. But I'm finding that with my latest project, placing controls on the form through a graphical interface is not going to work. This more has to do with the number of custom controls I have to create that I can't visually see before hand. When I first tackled this, I began to position all of my controls relative to the last ones that I created. Doing this had its own pros and cons. On the one hand, this gave me the opportunity to set one number (a margin for example) and when I changed the margin, the controls all sized correctly to one another (such as shortening controls in the center while keeping controls next to the margin the same). But this started to become a spiders-web of code that I knew wouldn't go very far before getting dangerous. Change one number and everything re sizes, but remove one control and you've created many more errors and size problems for all the other controls. It became more surgery then small changes to controls and layout. Is there a good way or maybe a preferred way to determine when I should be using relative or absolute positioning in forms?


Does having a higher paid technical job mean you do not get to code any more?

I work at a large company where technical people fall roughly in one of these categories:   1. A **developer** on a scrum team who develops for a single product and maybe works with other teams that are closely related to the product.    2. An **architect** who is more of a consultant on multiple teams (5-6) and tries to recognize commonalities between team efforts that could be abstracted into libraries (architects do not write the library code, however). This architect also attends many meetings with management and attempts to set technical direction. In my company the architect role is where most technical people move into as the next step in their career. My questions are: Do most companies work such a way that their highest paid technical people are far removed from writing code? Is this a natural tendency for a developer's career? Can a developer have it all (code AND set direction?)


How can I test database access methods in Java?

I want to write a test for a method that accesses a database such as following.               public class MyClass{         public String getAddress(Int id){             String query = "Select * from Address where id="+id;             //some additional statements                        resultSet = statement.executeQuery();             return result.getString(ADDRESS);                 }     }      How can I test this method? I am using Java.


What problems can happen if an XML file is not backed by a schema?

What is a XML schema in plain simple terms? What will be the problem if an XML doesn't have a schema defined? An example can be very helpful.


Where to draw the line between front end and back end

I was recently contracted to develop a smarty theme for an automated SOHO phone answering service. The team who had built the backend wouldn't allow me access to any of the back end nor tell me anything about it, their smarty set up, smarty plugins, data base interface api, server set-up, nothing. Nor could I have access to the server nor a beta domain, basically zero co-operation. So I set up a local server with Smarty and built the template based on what I guessed would be their best practice, commented my code like crazy, wrote all the needed javascript, css, and template files. Then I sent them packaged to the backend team and hoped for the best. With half of a project team failing to cooperate or even communicate I am now concerned that they may reply saying that everything is wrong and they may refuse to implement the new front end. I'm curious to know if others encounter this type of situation and what you may have done to protect yourselves.


Send stdout or stderr to a new thread

For performance issue I want the logging send to a new thread. While the main program can work, the new thread can write the error or other messages to a file without effect to the main program. How could I send all stdout to the new thread? Work to be done:   * create a new thread, ok   * open a file, ok   * create a pipe inside the thread, ok   * send stdout to the new thread, with freopen or dup? Every time the buffer gets full, or every 5 seconds the log file gets new data. Because it is an MPI program, I can't fork the whole program. It has to be a Posix thread.


What are the responsibilities of a Manager and of the Dao Layers

In several projects we have been using the following layers:   1. Action (has 1 or more managers)   2. Manager(has 1 or more Daos)   3. Dao But most of the time the manager only calls the dao. We do use the manager class to prepare the date to be sent to the db or to prepare the data to be sent to the action(is this a good practice?).   1. What are the responsibilities of a Manager and of the Dao classes?   2. Do we have to have a manager for every dao or can we just use the dao directly?   3. How do I handle situations where I need to use the functionality implemented in several Managers? PS: I know that there is no golden hammer so I'll narrow it to the types of apps we do, generally webapps for banks. Thank you


Best method for async initialization of view model in MVVM pattern (WPF)

I'm working on a business application (C#, WPF, EF, MVVM). I need to load a bunch of items from database, create view models for them and put them in a window. Is there a way to create the view model in another thread or do something similar to speed up UI?   1. The approximate average time needed to fetch all items from database = 1s    2. The approximate average time needed to instantiate all view models = 3s I'm doing the first part through Loaded event of each item. but the second part is the bottleneck. any insight would be appreciated.


What is the best practice for refactoring a static method in order to make it more testable?

Let's say you have a static method that looks something like this:               public static bool Foo()     {          var bar = new Bar();         //do some stuff here     }      This method as it stands can be a real headache to unit test. What is the best practice to refactor this so that it can be testable, without turning it into an instance method or changing the method signature?


When to build User Controls in ASP.NET

I am inheriting a legacy code. The legacy code has lot of web forms and each web form does not have much of functionality other than hosting a user control. My question is -   * Should we create a user control even if that control is not used in any other web form ?   * Are there any hard benefits in creating user controls over web forms? P.S - Web forms are .aspx files and User Controls are .ascx files.


At ping, why do we have to do array copying instead of passing on the source array that the client sent to us?

So I have been googling about this OpenSSL heart-bleed thing and somehow sees that it is caused by the heartbeat extension which requires client to ping the server to show its aliveness and it all comes to this memcpy function in C which is meant to copy from the source array to the destination array with the user specified size. If the size was a lie (which means the source contains lesser byte than the size claims) then memcpy will grab the arbitrary memory around and allocated to the destination and in this case send back to the client… Reference: Anatomy of OpenSSL's Heartbleed: Just four bytes trigger horror bug > `payload` is controlled by the attacker, and it's quite large at 64KB. If > the actual `HeartbeatMessage` sent by the attacker only has a payload of, > say, one byte, and its payload_length is a lie, then the above `memcpy()` > will read beyond the end of the received `HeartbeatMessage` and start > reading from the victim process's memory... If my understanding above is correct, then I have a question here maybe naive one, why do we have to do array (char array here) copying here? Can't we just pass on the source char array that the client sent to us? i.e. If you send me               function(char[] array)      Then I would just need to send back that very array               send(array)


Should Agile teams deliver new features daily?

My company is in the midst of a transition from waterfall-style development to Agile/Scrum. Among other things, we're told that the expectation is for us to have **new** working, **testable** (by QA) features at the end of each day. Most of our devs lose around 2 hours a day to meetings and other enterprisey overhead. This means that in any given 6-hour (at best) period, we have to design, write, unit-test, build, and deploy (with release notes) enough code to produce a complete feature for QA to play with. I understand that the build/deploy/release notes could be automated with a proper CI setup but we're not there yet. We also have a large offshore contingent writing our server-side code, and the 12-hour time difference makes this even more difficult. We attempt to task out stories into narrow, deep vertical slices in order to complete features end-to-end as fast as possible, but most days feel rather frantic and I often catch people taking stupid, fragile shortcuts to ensure QA has their build. This problem is compounded after a sprint has been in progress for a couple of days, when the inevitable defects start rolling in and have to fit into the same 6-hour window. Is this a normal pace for Agile teams? Even if we manage to implement a CI setup, I can't see how we'll be able to sustain this pace and still create quality software. **Edit:** There are several good answers here. It made me realize that what I was really asking is, should Agile teams deliver **new features** daily. I updated the title accordingly.


Teaching myself, as a physicist, to become a better programmer

I've always liked physics, and I've always liked coding, so when I got the offer for a PhD position doing numerical physics (details are not relevant, it's mostly parallel programming for a cluster) at a university, it was a no- brainer for me. However, as most physicists, I'm self taught. I don't have broad background knowledge about how to code in an object oriented way, or the name of that specific algorithm that optimizes the search in some kD tree. Since all my work so far has been more concerned about the _physics_ and the scientific results, I undoubtedly have some bad habits - more so because my coding is my own, and not really teamwork. I have mostly used C since it is very straightforward and "what you write is what you get" - no need for fancy abstractions. However, I have recently switched to C++ since I'd like to learn more about the power that comes with abstraction, and it's pretty C-like (syntax-wise at least). How do I teach myself to code in a good, abstract way like a graduate in computer science? I know my code is efficient, but I want it to be _elegant_ as well, and readable. Keep in mind that I don't have time to read several 1000-page tomes about abstract programming. I need to spend time on actual, physics related research (my supervisor would laugh at me if he knew I spent time thinking about how to program elegantly). How do I assess if my work is also good from a programmer's perspective?


Android development & hardware testing - Which handsets & tests? What are the best options/deals?

I'm quite new to Android development. I spent a few weeks, doing tutorials and developping simple apps. Now, I'm focusing on all the test aspects. I have done Junit tests before so I thought it would be OK but now I'm slightly worried about the test coverage required. First, how to test with hardware with that many different devices?? I though I would just buy one but now I'm not so sure. There are so many handsets and they are so different! hardware feature missing, different resolutions, different lib version, etc Have you guys got statistics about which handset sell the best per country? So that we can just buy the 2,3 most representative phones? Is there any developer deals where you buy 3 phones + 1 contract for a reasonable price (I'm in the UK btw). Also, to go back to emulator tests, is there a way to kind of convert a famous handset into the corresponding AVD? Is there some nice free test infrastructure available that make multi-AVDs, multi-config, multi-projects test easier? Now I know most of the programs such as adb,android,emulator, etc... Still will probably need to write some python scripts which integrate them all.. Anyway, I'm slightly puzzled here so any pointer, any comment about your own android test strategy would be much appreciated! Thanks in advance Mikael


How should a website validate a users mailing address?

This is for a site that relies on shipping items via UPS or FedEx. I know there is software out there that does it (http://en.wikipedia.org/wiki/Coding_Accuracy_Support_System), but if you are trying to build your own solution for a simple website.


Business Analyst role in development process

I work as a business analyst and I currently oversee much of the development efforts of an internal project. I'm responsible for the requirements, specs, and overall testing. I work closely with the developers (onshore and offshore). The offshore team produces all of the reports. Version 1.0 had a 9 month development cycle and I had about 4-5 months to test all the reports. There was the usual back and forth to get the implementation right. Version 2.0 had a much shorter development cycle (3 months). I received the first version of the reports about 3 weeks ago and noticed a lot of things wrong with it. Many of the requirements were wrong and the performance of the queries was horrendous at 5x - 6x longer than it should have been. The onshore lead developer was out and did not supervise the offshore development team in generating the reports. Management knew about the performance issues and I also told them I was trying to find a way to improve performance; they did not explicitly approve of sending test queries, but they were also not concerned with the fact I was doing that. I took a look at the SQL in the reports and was able to improve performance greatly (by a factor of 6x) which is acceptable for this version. I sent the updated queries as guidelines to the offshore team and told them they should look at doing X instead of Y to improve performance and also to fix some specific logic issues. I then spoke to my managers about this because it doesn't feel right that I was developing SQL queries, but given our time crunch I saw no other way. We were able to fix the issue quite fast which I'm happy with. Current situation: the onshore managers aren't too pleased that the offshore team did not code for performance. I know there are some things I could have done better throughout this process and I do not in any way consider myself a programmer. **My question is, if an offshore team that works apart from the onshore project resources fails to deliver an acceptable release, is it appropriate to clean up their work to meet a deadline? What kind of problems could this create in the future?** Update: So far management is upset with the offshore team, but have not "reprimanded" me in any way, so I'm not sure in their eyes if what I did was wrong, but I think their main source of frustration was the offshore team was not able to come up with a solution and I was, especially since this sort of performance issue had come up in the past. I am not defending my actions, but I want to give context so that the picture is a little clearer. I accepted the answer that most criticizes my actions I agree it's not something that should be done by someone in my position.


How is the build for a msdeployment project different than a regular web application project?

In our CI environment we build all the cs projects and then build the deployment projects. The deployment projects do an extra step of compiling the aspx & ascx files and often catch errors that would normally be caught at run time. 1) Is there a name for this step or process?   2) Can I get it in the regular project builds?   3) Where can I learn about the various steps of building specifically to msbuild?      Reading the logs in verbose I'd like to have a better understanding of what is actually happening. Thank you.


Declaring variables in Python and PHP

The question is how to cope with absence of variable declaration in Python, PHP, and the like. In most languages there is a way to let the compiler know whether I introduce a new variable or refer to an existing one: `my` in Perl (`use strict`) or `\newcommand` vs. `\revewcommand` in LaTeX. This prevents from two major sources of errors and headache: (1) accidentally using the same name of a variable for two different purposes, such as in (PHP)               $v = $square * $height;     <...lots of code...>     foreach ($options as $k => $v)         echo "For key $k the value is $v\n";     <...lots of code...>     echo "The volume is $v";      or a lot nastier (PHP)               $a = [1, 2, 3];     foreach ($a as $k => &$v)         $v++;     foreach ($a as $k => $v)         echo "$k => $v\n";      (can you see a bug here? try it!); and (2) prevent from typos (PHP):               $option = 1;     $numberofelements = 1;     if ($option)     {         $numberofelenents = 2;     }     echo $numberofelements;      (can you see a bug here? PHP will execute silently). Using something like `my` (Perl)               use strict;      my $option = 1;     my $numberofelements = 1;     if ($option)     {         $numberofelenents = 2;     }     say $numberofelements;      (Perl will immediately report the bug) is a tiny effort and HUGE benefit both in debug time and (much more importantly) in losses (potentially huge) from incorrect programs. However, some languages, notably Python, PHP, and JavaScript, do not give any protection from these types of bugs. My question is how can we effectively cope with this? The only way I can foresee is to create two functions (PHP):               function a ($x)     {         if (isset ($x))             die();         else             return &$x;     }      and               function the ($x)     {         if (isset ($x))             return &$x;         else             die();     }      and use them always:               a($numberofelements) = 1;     the($numberofelenents)++;     say the($numberofelements);      but of course this is extremely cumbersome. Any better way of effectively protecting from such errors? No, "use another language", "be careful and don't make errors", and "split your code in tiny functions" are not good answers (the latter may protect from the errors of type 1 but not type 2).


How do you balance the speed of Sprints with the customer's conservative adoption schedule?

I'd prefer to have sprints that last 3-4 weeks, but customers don't want to adopt new feature/function every 3-4 weeks. Existing customers are conservative and, once we meet their minimum bar for features and capabilities, they like to remain on a stable release for much longer than 4 weeks. Even a 3-month cycle would be pushing it for them. On the other hand, newer customers tend to have more feature requests, and are willing to follow sprints. But this willingness dissipates after we've met their bar. How do you balance the need for rapid sprints with the customer's conservative view of application change? I'm particularly interested in SaaS scenarios.


OAuth2 flow - does the server validate with the Auth server?

I've been reading a lot on OAuth2 trying to get my head around it, but I'm still confused about something. I understand that the client authorises with the OAuth provider (google for example) and allows the resource server to have access to the user's profile data. Then the client can send the access token to the resource server and be given back the resource. But what does not seem to be covered in any of the documentation is what happens when the client app asks the resource server for a resource and passes it the access token. Everything I have read so far states that the resource server just responds with the requested resource. But that seems like a huge hole, surely the resource server must somehow validate the access token, otherwise I could just fake up any old request and pass an old, stoken, fake, or randomly generated token and it would just accept it. Can anyone point me at a simple to follow explanation of OAuth2 because so far the ones I have read feel imcomplete. Thanks


Is it better to put an event on the top object or closer to where it's local?

Take the following basic structured code for example:               class Player     {        public QuestLog QuestLog { get; set; }     }      Let us consider that "QuestLog" has the ability to fire off some events when things are added or removed from it. Normally, I would subscribe directly to the QuestLog, such as doing something like:               player.QuestLog.AcceptedQuest += SomeHandler      However, I want to pass in some extra context (the player object). I saw a couple options.   1. Creating a lambda handler function which can resolve an extra parameter to the handler. This works but has some quirks I don't like. I'm currently using this approach.   2. I could couple the QuestLog to a Player, passing a reference of the player it belongs to in and fire events off accordingly with it. Feels like needless coupling.   3. Expose the event on the Player object itself as well as the QuestLog and 'bubble' the event up into where the context is available, thus allowing subscriptions directly onto player. Keep in mind a player may have a few collections and a few events, so moving them all up might cause a couple dozen events to be held on one class. How is this usually handled?


Why is C++ predominant in programming contests and competitions?

I understand that C++ is a very fast language, but ain't C just as fast, or faster in some cases? Then you might say that C++ has OOP, but the amount of OOP you need for most programming puzzles is not that big, and in my opinion C would be able handle that. **Here's why I am asking this** : I am very interested in programming contests and competitions, and I am used to coding in C on those. However, I noticed that the vast majority of people use C++ (e.g., 17 out of 25 finalists on Google Code Jam 2011 used it, while no one used C), so I am wondering if I am at a disadvantage going with C. Apart from the Object Orientation, what makes C++ a more suitable language for programming competitions? What are the features of the language I should learn and use to perform better on the competitions? For background, I consider myself pretty proficient in C, but I am just starting to learn C++.


Significance and role of Node.js in Web development

I have read that Node.js is a server-side javascript enviroment. This has put few thought and tinkers in my mind. Can we develop a complete data-drivent web application utilizing just JavaScript (along with node.js), HTML5 and CSS? Do we still need to use some server-side scripting language (e.g. C#, PHP)? In case we still need to use other scripting languages, what is node.js worth for, or useful? **NOTE:** _Pardon with my knowledge about node.js._


Problem with C code. Raspberry PI, HD44780 LCD

I have been writing a program for interfacing a raspberry pi with a HD44780 LCD. The code I have wrote does not seem to initialise the display, from the datasheet as far as I can tell I am doing the correct process. I know the code is not great but I am just focusing on getting it working then tidying it up and such. This is to help me learn C. I am using the bcm2835 library from mikem. The code is as follows:               #include <stdio.h>     #include <bcm2835.h>          #define RS RPI_GPIO_P1_26 //GPIO 7     #define En RPI_GPIO_P1_24 //GPIO 8     #define D4 RPI_GPIO_P1_11 //GPIO 17     #define D5 RPI_GPIO_P1_12 //GPIO 18     #define D6 RPI_GPIO_P1_13 //GPIO 27     #define D7 RPI_GPIO_P1_15 //GPIO 22          #define FUNC_4b_2L_5X8 0x28     #define DISP_ON_CURS_ON_BLINK_OFF 0x0E     #define INC_ON_SHIFT_OFF 0x06     #define CNTRL_LINES_LOW 0xFFF8     #define CURS_LEFT 0x10     #define CURS_RIGHT 0x14     #define CLR_DISP 0x01     #define SHIFT_LEFT 0x18     #define SHIFT_RIGHT 0x1C     #define ROW_0_START 0x80     #define ROW_1_START 0xC0     #define RETURN_HOME 0x2                    void lcd_gpio_low(void)     {         bcm2835_gpio_write(RS, LOW);         bcm2835_gpio_write(En, LOW);         bcm2835_gpio_write(D4, LOW);         bcm2835_gpio_write(D5, LOW);         bcm2835_gpio_write(D6, LOW);         bcm2835_gpio_write(D7, LOW);     }          void assign_bits(uint8_t data)     {         switch(data)         {             case 0:                 bcm2835_gpio_write(D4, LOW);                 bcm2835_gpio_write(D5, LOW);                 bcm2835_gpio_write(D6, LOW);                 bcm2835_gpio_write(D7, LOW);                 break;                  case 1:                 bcm2835_gpio_write(D4, HIGH);                 bcm2835_gpio_write(D5, LOW);                 bcm2835_gpio_write(D6, LOW);                 bcm2835_gpio_write(D7, LOW);                 break;                  case 2:                 bcm2835_gpio_write(D4, LOW);                 bcm2835_gpio_write(D5, HIGH);                 bcm2835_gpio_write(D6, LOW);                 bcm2835_gpio_write(D7, LOW);                 break;                  case 3:                 bcm2835_gpio_write(D4, HIGH);                 bcm2835_gpio_write(D5, HIGH);                 bcm2835_gpio_write(D6, LOW);                 bcm2835_gpio_write(D7, LOW);                 break;                  case 4:                 bcm2835_gpio_write(D4, LOW);                 bcm2835_gpio_write(D5, LOW);                 bcm2835_gpio_write(D6, HIGH);                 bcm2835_gpio_write(D7, LOW);                 break;                  case 5:                 bcm2835_gpio_write(D4, HIGH);                 bcm2835_gpio_write(D5, LOW);                 bcm2835_gpio_write(D6, HIGH);                 bcm2835_gpio_write(D7, LOW);                 break;                  case 6:                 bcm2835_gpio_write(D4, LOW);                 bcm2835_gpio_write(D5, HIGH);                 bcm2835_gpio_write(D6, HIGH);                 bcm2835_gpio_write(D7, LOW);                 break;                  case 7:                 bcm2835_gpio_write(D4, HIGH);                 bcm2835_gpio_write(D5, HIGH);                 bcm2835_gpio_write(D6, HIGH);                 bcm2835_gpio_write(D7, LOW);                 break;                  case 8:                 bcm2835_gpio_write(D4, LOW);                 bcm2835_gpio_write(D5, LOW);                 bcm2835_gpio_write(D6, LOW);                 bcm2835_gpio_write(D7, HIGH);                 break;                  case 9:                 bcm2835_gpio_write(D4, HIGH);                 bcm2835_gpio_write(D5, LOW);                 bcm2835_gpio_write(D6, LOW);                 bcm2835_gpio_write(D7, HIGH);                 break;                  case 10:                 bcm2835_gpio_write(D4, LOW);                 bcm2835_gpio_write(D5, HIGH);                 bcm2835_gpio_write(D6, LOW);                 bcm2835_gpio_write(D7, HIGH);                 break;                  case 11:                 bcm2835_gpio_write(D4, HIGH);                 bcm2835_gpio_write(D5, HIGH);                 bcm2835_gpio_write(D6, LOW);                 bcm2835_gpio_write(D7, HIGH);                 break;                  case 12:                 bcm2835_gpio_write(D4, LOW);                 bcm2835_gpio_write(D5, LOW);                 bcm2835_gpio_write(D6, HIGH);                 bcm2835_gpio_write(D7, HIGH);                 break;                  case 13:                 bcm2835_gpio_write(D4, HIGH);                 bcm2835_gpio_write(D5, LOW);                 bcm2835_gpio_write(D6, HIGH);                 bcm2835_gpio_write(D7, HIGH);                 break;                  case 14:                 bcm2835_gpio_write(D4, LOW);                 bcm2835_gpio_write(D5, HIGH);                 bcm2835_gpio_write(D6, HIGH);                 bcm2835_gpio_write(D7, HIGH);                 break;                  case 15:                 bcm2835_gpio_write(D4, HIGH);                 bcm2835_gpio_write(D5, HIGH);                 bcm2835_gpio_write(D6, HIGH);                 bcm2835_gpio_write(D7, HIGH);                 break;         }     }          void pulse_enable_line(void)     {         bcm2835_gpio_write(En, HIGH);         bcm2835_delayMicroseconds(1);              bcm2835_gpio_write(En, LOW);         bcm2835_delayMicroseconds(1);     }          void send_nyble(uint8_t data)     {         assign_bits(data);         bcm2835_delayMicroseconds(10);              pulse_enable_line();     }          void send_byte(uint8_t data)     {         send_nyble(data >> 4);         bcm2835_delayMicroseconds(10);              send_nyble(data & 0x0F);         bcm2835_delayMicroseconds(10);     }          void write_inst(uint8_t data)     {         lcd_gpio_low();         bcm2835_delayMicroseconds(1);         send_byte(data);         bcm2835_delayMicroseconds(10);     }          void clear_disp(void)     {         // Clear display         write_inst(CLR_DISP);         bcm2835_delayMicroseconds(40);     }          void write_data(uint8_t data)     {         bcm2835_gpio_write(RS, HIGH);         send_byte(data);         bcm2835_delay(5);         bcm2835_gpio_write(RS, LOW);     }          // Displays character, pass in a character      void disp_char(char *text)     {         // Set all outputs to 0         lcd_gpio_low();         // Set RS to 1         bcm2835_gpio_write(RS, HIGH);         bcm2835_delayMicroseconds(1);         // Set the passed in value          send_byte(*text);         bcm2835_delayMicroseconds(40);         // Set all outputs to 0         lcd_gpio_low();         bcm2835_delayMicroseconds(40);      }                    void lcd_init(void)     {         //Set lines as outputs         bcm2835_gpio_fsel(RS, BCM2835_GPIO_FSEL_OUTP);         bcm2835_gpio_fsel(En, BCM2835_GPIO_FSEL_OUTP);         bcm2835_gpio_fsel(D4, BCM2835_GPIO_FSEL_OUTP);         bcm2835_gpio_fsel(D5, BCM2835_GPIO_FSEL_OUTP);         bcm2835_gpio_fsel(D6, BCM2835_GPIO_FSEL_OUTP);         bcm2835_gpio_fsel(D7, BCM2835_GPIO_FSEL_OUTP);              lcd_gpio_low();              bcm2835_delay(42);                   // Send function set data as 8 bits, 2 lines and 5x8         write_inst(FUNC_4b_2L_5X8);              bcm2835_delay(5);              // Send function set data as 8 bits, 2 lines and 5x8         write_inst(FUNC_4b_2L_5X8);              bcm2835_delayMicroseconds(110);              // Send function set data as 8 bits, 2 lines and 5x8         write_inst(FUNC_4b_2L_5X8);         bcm2835_delayMicroseconds(40);              // Send function set data as 8 bits, 2 lines and 5x8         write_inst(FUNC_4b_2L_5X8);         bcm2835_delayMicroseconds(40);              // Send Display control. Disp on, cursor on and blinking off         write_inst(DISP_ON_CURS_ON_BLINK_OFF);         bcm2835_delayMicroseconds(40);              // Send Entry mode set. Increment on, shift off         write_inst(INC_ON_SHIFT_OFF);         bcm2835_delayMicroseconds(40);              // Clear Display         clear_disp();     }          int main()     {         //bcm2835_set_debug(1);              if (!bcm2835_init())             return 1;              lcd_init();              write_data(0x48);              printf("%d",'F');              bcm2835_delay(10000);              return 0;     }


Slow if use object cross referecing

In OOP, it seems that if an object cross-references another object in its property, ultimately, if such objects are used a lot, the software at the end will be slow because of this. Is this true? If yes, can we intentionally not do this by getting things done?


When to pay for C++ compilers

Recently I have began to wonder when developers should pay for compilers. Compilers come for free with most platforms or there is a free version easily obtainable. Example: OS X - GCC and Clang/LLVM come with the developer tools. No limitations here for how and what you can turn out with them. Linux - GCC and I am sure more. I dont know the current state of linux compilers. No limitations here for how and what you can turn out with them. Windows - MinGW and Microsoft does offer a free version of Visual Studio. No limitations with MinGW but I think with the free Visual Studio there are severe limitations. However, as an example, Intel produces C/C++ compilers. They are hefty in price. Educationally I think that one can get the OS X version for $49 and Windows/Linux for $129 each. They then offer a complete "Studio" product too. Obviously using the educational pricing there are imposed limitations. But what I am wondering is when should one really considering paying for compilers. One example I can think of is a video game. If you are using a compiler that works on the major platforms there would be no more switching tools for the platform. It seems there would be a level of ease in switching among platforms if the tools were the same. Can anyone shed some light on paying for compilers like the Intel compilers and the true cross-platform benefits one might get from using them? Does one's code become less portable even trying very hard to not do platform specific techniques?


What are general best practices for plugin/extension development?

I need to correlate requirements for a plugin/extension of an application with development best practices. I thought there might be best practice advice that applies to plugins and extensions available but cannot find any literature. Of course best practices are often common sense, but my task involves applying a framework to describe design choices. If any resources specific to plugins/extensions are known that would be great. Otherwise, I would like, to at least find a well respected language agnostic list of software development principles.


Global request context - anti-pattern?

I was talking today to a colleague of mine about Python web frameworks and our impressions about them. I told him I think Flask having a global request smells badly and is an anti-pattern. The docs say about request context: > In contrast, during request handling, a couple of other rules exist: > >   * while a request is active, the context local objects (flask.request and > others) point to the current request. >   * any code can get hold of these objects at any time. > I think I understand the idea behind this design decision -- to make the application simpler. It's just a compromise, like in the case of Thread Locals: > Yes it is usually not such a bright idea to use thread locals. They cause > troubles for servers that are not based on the concept of threads and make > large applications harder to maintain. However Flask is just not designed > for large applications or asynchronous servers. Flask wants to make it quick > and easy to write a traditional web application. Is patching a global object with the current request information an anti- pattern? I believe it is, because it is in the view of static code analyzer a global state, though it's not. And I as a programmer will not understand how it works without reading the docs carefully. And this has consequences on tests. Isn't it a good practice to pass the request as an argument to views? I think it's more readable, explicit and easier to debug. And avoids global state.