Erlang or 'x'.. Is it worth it (vs. Python w/ GIL)?

So, I've finally gotten myself to a point where I'm comfortable enough with Python (using Pyramid as my framework of choice) to undertake a rather large personal project. As it's a personal project, I have the luxury of taking my time having absolutely no deadlines other than self-imposed ones. I love learning new frameworks, languages, etc. so if given a reason, I don't mind pushing back on development for a month or so while learning a new language and framework (takes longer when you're doing it on your own time ;)). I recently learned about CPython's GIL (Global Interpreter Lock), which raised my eyebrow a bit. If I understand it correctly, this means that if I have a `Queue` in my web app and have threads that complete jobs in the queue, then the code is locked until the thread for that request is complete, meaning that any subsequent request is locked while the previous thread is executing. **Question:** Has anyone in "real world" applications found this to be a problem? Is it worthwhile to learn a language that supports _real_ concurrency out of the box, such as Erlang? I'm most interested in any benchmarks that anyone has done in real world apps and whether or not anyone has seen any real noticeable issues with the GIL.


What advice would you give to someone going freelance?

I'm trying to get out of the Corporate game and go indie. I've always prided myself on being a jack of all trades so I think it suits me. If you're a freelancer or independent, what's the best advice you could give me as I start down this road?


How can proprietary code be protected when collaborating with an external company?

Imagine I have a code base and I'm obsessively concerned about the protection and privacy of that code. If I were to hire a freelancer to work on that code base, I'd probably have the freelancer sign a nondisclosure agreement and hopefully I'd build up a relationship with him/her over time and gain some confidence that he/she can be trusted. However, if I wanted to collaborate with an external company, company X, what steps can I take to protect my code? I assume a nondisclosure agreement would offer some protection in the case that company X steals my code, but what could I do to protect against the code being stolen from a rogue company X employee with access to the code base? Should I require that all employees at company X sign a nondisclosure agreement? In general, what steps can be taken by a company like company X to encourage a trusting collaboration with their clients? How can company X assure me that the code they have access to won't be stolen? Are such collaborations even possible? **Postscript:** I'm not really confident in the protective power of most non-disclosure agreements. In general, I believe that all I can do is work with people that I trust and hope for the best. However, for the purposes of this question I'm interested in hearing if _any_ form of protection is available even if it isn't particularly robust.


Best practices in Application's flow diagram

I make web applications, mostly MVC, object oriented and database enabled. I always have trouble going back to project after a few months of release and work again. I don't even remember what I made on that project. How should I overcome this problem? I can't afford too much time consuming documentations and so many diagrams. Any quick way you guys practice to avoid this?


How to properly structure a collection of immutable constants

I'm in the design stages of a program that based upon input received, would select a particular category, and action within that category. The category, the action within in, and the value(s) related to that action are all immutable values, along with the relationship between category and action. Normally I'd just assign it all into a multidimensional array or collection, but that strikes me as both messy and unnecessarily complex to search and sort. Constants don't allow me the luxury of defining relationships between them (aka you can't have constant A bound to subConstant B for example), and being a desktop app, having a user setting up a database server isn't appealing. Was thinking of having everything in xml files, but core rules of the application isn't appealing due to being able to easily edit, and hence change the primary functionality of the program that I wouldn't wish to be editable. Anyone ever ran into something like this, and if so, what was the setup that you used for your solution? EDIT: Let me see if I can explain this better with an example. Say I have the following structure               category A       -- action AB           -- result 1           -- result 2           -- result 3           -- result 4           -- result 5           -- result 6      where if I selected category A, and action AB, a one dice roll would select the result to be returned. The category, action, and result will never change both in name and in relationship (action AB will always be bound to category A, results within action AB will be bound to action AB, and the result contents will never change) EDIT: No network usage would be expected for this application, as it was asked in one of the responses.


Legality of collaborative reverse-engineering

I have been disassembling a large software project on my own, as a hobby. It is an educational exercise and I have learned a lot in the process. That said, I feel that my progress would be considerably quicker if I was to collaborate on the project with other like-minded individuals. Herein lies the problem -- maybe. I am reversing this software for personal interest and potentially (but unlikely; given the magnitude of the codebase in question) implementing an interoperable service to interact with this software, replacing the vendor's own service. My (very limited) understanding is that this particular use-case is protected under copyright law. However, my wish is to collaborate with others freely on the Internet, in a similar system employed by open source projects: version control repositories of assembly files, wikis to coordinate and share knowledge, public mailing lists, et cetera. I have a feeling this may be iffy at best. Is what I want to do blatantly illegal, a gray area or even legally defensible? Would the situation be any different if the collaboration was in private rather than public? If it has any bearing on the answer, I am located in Australia and the software vendor in located in the USA.


Should I use AND or should I use OR

An order can be in the "status" of Completed, Corrected or some other status. I saw some code that is checking it like this, the purpose is to disable some stuff when the status is in Completed or Corrected status.                if (model.CurrentStatus != DSRHelper.OrderStatusEnum.Complete && model.CurrentStatus != DSRHelper.OrderStatusEnum.Corrected)      I can't get it why the engineer has used "AND" for this, shouldn't it be an "OR"?


What kind of programs/solutions can only be written with OOP or are too hard to achieve without it?

Paraphrasing a recent question: What is Object Oriented Programming ill-suited for? I would like to ask the opposite question: What kind of programs cannot be written unless you use OOP?   What kind of programs are not recommended to be written using non-OOP techniques?   What kind of programs need OOP in order to even be written? What kind of programs would be too hard to write without OOP ? The answer to this question can help sell the idea of OOP to project leaders that have no special interest in code quality. At least they could buy the idea if one shows them the kind of things that are not even possible unless you use OOP.


Inventory / Stock in multiple locations

I am working on a warehouse management system (WMS) that needs to support having stock in multiple locations. Could be in a different building, could be stored in n* places in a building (quick example would be stock, overflow, or fast moving slots all containing a qty of the same item). Where I am, they have always used one SKU assigned to one bin with paper notes pointing to overflow. Obviously they have grown beyond this and it's causing some serious issues. No one here can help me when I try to get what the best practice should be. I am having trouble conceptualizing how to setup the structure. I am thinking ...   * Warehouse (virtual or physical) Warehouses can belong to warehouses.   * Location - Anything really could be a pallet, box, or just a taped off area on the floor. Locations belong to warehouses.   * Rows - can be in locations   * Shelves can be in rows   * slots(traditionally called a bin here) the smallest unit that can be a location. Then a SKU could be in any one or many of these locations (except the virtual warehouse - used only from grouping physical locations but allowing a sales order to process them internally as if it shipping from one space). Locations (are their children) could be given priority. So if a SKU is in 2 locations, the systems knows which slot(bin) to empty first before routing to the next. I code it so that the structures above can be handled by the warehouse since i don't care physically about them only that the process makes sense and then give them a tool to mark a sort order so that they can determine the best routes through the warehouse with batch picking an order. I guess I just wanted to get this out of my head and get someone elses eyes on it before I wrote a single line of code. Does this structure make sense? Is it a best practice? If not what is and if that question is outside the realm of the site could someone point me to it?


Learn a NoSQL or become a badass with traditional RDMS - Where is/will the work be?

New Question Version: I've got the opportunity to spend 3 months getting good at something, its going to be either a NoSQL technology like Cassandra or optimising relational database systems. I slightly prefer trying the 'flavour of the month' cassandra but would also love to improve my relational database skills which would be very practical. This isn't about which is better, its about my employment prospects and where I am going to get work. I know there is going to be more work in relational databases, but are we going to see a bump in the level of jobs wanting/requiring NoSQL experience? Thanks guys, I'm really impressed with the amount of advice people have given so far. Old version: I'm half way through my MSc and am thinking about my dissertation which I get 3 months to work on full time. Im very comfortable with the traditional Relational Database, the question is should I work on a project where I get a good understanding of something like Cassandra, or should I really push my RDMS knowledge to the limit. Getting great at something like MySQL is a solid safe option, will there really be much work for me with Cassandra in my tool belt? I would love to do either.... Thanks for your opinions and advice.


Should there be a "data hygiene" index for software - to indicate how clean the program is? not leaving temp files, etc

Should there be a "data hygiene" index for software - to indicate how clean the program is? not creating unused temp files, registry entries, environment variables, etc. For example, look in your users folder in Windows, you'll see all manner of work space files used by your applications. For example, this makes it hard to know what needs to be backed up and what can be discarded as being machine-generated.


When to start thinking about scalability?

I'm having a funny but also terrible problem. I'm about to launch a new (iPhone) app. It's a turn-based multiplayer game running on my own custom backend. But I'm afraid to launch. For some reason, I think it might become something big and that its popularity will kill my poor lonely single server + MySQL database. On one hand I'm thinking that if it's growing, I'd better be prepared and have a scalable infrastructure already in place. On the other hand I just feel like getting it out into the world and see what happens. I often read stuff like "premature optimization is the root of all evil" or people saying that you should just build your killer game now, with the tools at hand, and worry about other stuff like scalability later. I'd love to hear some opinions on this from experts or people with experience with this. Thanks!


SSO between multiple Flex applications

We have three applications developed in **Flex** and all these use BlazeDS. These applications have their own authentication implementations **(Database)**. Also they will be deployed in **tomcat**. Deploying all these applications in the same tomcat instance is acceptable for us. We want to bring the authentication credentials of all these applications into a single place and also provide **SSO feature between these applications**. We also want the authentication module to be **configurable**. Something like the system administrator can decide if the authentication should be done against **a database or LDAP**. Say, if the user successfully logs into app1, and when he access app2 in the same browser he should be automatically logged in. Same goes for logout as well. We have been exploring **OpenAM, jGuard and JOSSO**. I'm not sure if these require lot of customization to work with **Flex**. I would like to know how people are implementing SSO for Flex applications. **Is there a common and simple SSO solution available for Flex based applications ?**


reading parameters and files on browser, looking how to execute on server

I have a site done in Rails, which uses javascript to load files and generate forms for the user to input certain information. Those files and parameters are then to be used in a fortran code on the server. When the UI was on the server (using Qt), I would create a parameters file and execute the fortran code using threads so I wouldn't block the computer. Now that is web-based, I need to make the server and browser talk. What's the procedure for that? where should I start looking? I'm already using rails + javascript. I need that extra tool to do the talking, and no idea where to start.


Can an internally developed fast evolving, agile, short sprint web application lend itself to offshoring?

I have recently been set a target to achieve readiness to successfully manage and deliver results through the usage of offshore teams on our mainline development project within 12 months. Our mainline is a multi-thousand user highly available web application, and various related SAAS components delivered through the above mentioned web application. We work agile on the mainline with a rapid 1 week sprint using continuous integration. Our delivery platform is a bespoke php framework, although we have some .net services and components in the mix. My view is: an offshore team could work if we either ship out an entire isolated project for offshore development, or we specify a component for our system in huge detail up front. But we don't currently work like that, and it will conflict with the in-house method, and unless the off-shore is working within our team, with our development/deployment chain it could be an integration nightmare. So my question is, given we have a closed source bespoke framework (Private IP) which we train our developers to use, and we work agile minimising documentation, maximising communication and responding to rapidly changing requirements, and much of the quality control is via team skills building and peer review, how can I make off-shoring work on our main line development?


Employer purchased a Macbook for me, as a programmer what do I need to do to get my environment setup?

I come from growing up on dos/windows and the more I got into programming and development the more I invested time/effort into linux distributions. I had a choice between an IBM and a Macbook. I went with the Macbook to get some experience but I am not really sure where to start? I find myself wanting to install virtualbox and boot up linux. Any advice for a new Mac user who wants to get back up to speed with programming efficiently?


Any tools/suggestions on how to refute code coverage quality argument

Now I know people could consider this question duplicate or asked many times, in which case I would appreciate a link to relevant questions with answer to my question. I have been recently in disagreement with some folks about code coverage. I have a group of people who want our team to drop looking at code coverage altogether based on the argument that 100% coverage does not mean good quality tests and thus good quality code. I have been able to push back by selling the argument that Code Coverage tells me what has not been tested for sure and help us focus on those areas. (The above has been discussed in a similar fashion in other SO questions like this one - http://stackoverflow.com/questions/695811/pitfalls-of-code- coverage) The argument from these folks is - then team would react by quickly creating low quality tests and thus waste time while adding no significant quality. While I understand their point of view, I am searching for a way to make a more robust case for code coverage by introducing **more robust tools/frameworks that take care of more coverage criteria** `(Functional, Statement,Decision, Branch, Condition, State, LCSAJ, path, jump path, entry/exit, Loop, Parameter Value etc)`. What I am looking for is **suggestion for a combination of such code coverage tools and practices/processes to go with them** which can help me counter such arguments while feeling comfortable about my recommendation. I would also welcome any accompanying comments/suggestions based on your experience/knowledge on how to counter such an argument, because while subjective, code coverage has helped my team be more conscious of code quality and value of testing. * * * Edit: To reduce any confusion about my understanding of weakness of typical code coverage, I want to point out that **I am not referring to** `Statement Coverage`(or lines of code executed) tools(there are plenty). In fact here is a good article on everything that is wrong with it: http://www.bullseye.com/statementCoverage.html I was looking for more than just statement or line coverage, going more into multiple coverage criteria and levels. See: http://en.wikipedia.org/wiki/Code_coverage#Coverage_criteria The idea is that if a tool can tell us our coverage based on multiple criteria then that becomes a reasonable automated assessment of test quality. I by no means am trying to say that line coverage is a good assessment. In fact that's the premise of my question. * * * Edit:   Ok, maybe I projected it a bit too dramatically, but you get the point. The problem is about setting processes/policies in general across all teams in a homogeneous/consistent fashion. And the fear is general that how do you ensure quality of tests, how do you allocate guaranteed time without having any measure to it. Thus I like having a measurable feature that when backed up with appropriate processes and the right tools would allow us to improve code quality while knowing that time is not being force spent in wasteful processes. * * * **EDIT: So far what I have from the answers:**   * Code reviews should cover tests to ensure quality of tests   * Test First strategy helps avoid tests that are written after the fact to simply increase coverage %   * Exploring alternative tools that cover test criteria other than simply Statement/Line   * Analysis of covered code/number of bugs found would help appreciate the importance of coverage and make a better case   * Most importantly trust the Team's input to do the right thing and fight for their beliefs   * Blocks Covered/# of tests - Debatable but holds some value Thanks for the awesome answers so far. I really appreciate them. This thread is better than hours of brainstorm with the powers that be.


What is the role of traditional issue tracker when Scrum / Kanban board is used?

From a very high level view, to me it seems there are generally 2 types of Project Management tools:   1. **Traditional issue trackers** like Fogbugz, JIRA, BugZilla, Trac, Redmine etc.   2. **Virtual card boards** / agile project management tools like Pivotal Tracker, GreenHopper, AgileZen, Trello etc. Sure, they overlap in one way or another, e.g. Pivotal Tracker tasks can be imported to JIRA, GreenHopper itself is implemented on top of JIRA issue base etc. but I think one can still see the difference in orientation between those two types of tools. Traditional issue tracker seems to be used even in companies otherwise doing agile project management. My question is, why do they do that? I also feel that we should use an issue tracker in my company but when I'm thinking about it, I'm not actually sure why should we need it. For example, Trello development seems to be managed by using Trello itself (see this virtual wall) even though they have access to Fogbugz, one of the best issue trackers around. So maybe we don't need traditional issue tracker when we'll be doing 100% of our work in an agile manner using one of the agile PM tools?


Design for a plugin based application

I am working on application, details of which I cannot discuss here. We have core framework and the rest is designed as plug in. In the core framework we have a domain object. This domain object is updated by the plugins. I have defined an interface in which I have function as `DomainObject doProcessing(DomainObject object)` My intention here is I pass the domain object, the plug in will update it and return it. This updated object is then passed again to different plugin to be updated. I am not sure if this is a good approach. I don't like passing the DomainObject to plugin. Is there a better way I can achieve this? Should I just request data from plugin and update the domain object myself?


Should I write a wrapper within a manager object?

I have three classes that work together to do one function (from the perspective of the rest of my program). There is a little bit of set up between them, so, to make it easier for the rest of my program, I grouped them into:   * `ListManager`: object, which initializes them to the right values when it is constructed. The three objects it stores are:      * `Timer`:     * `TriggerManager`: basically a wrapper around an `ArrayList` that manages `Trigger` objects     * `CueList`: a linked list with the usual getters and setters that come with that.  Since the rest of my program is only interacting/referencing the `TriggerManager` class, should I write wrapper methods for the objects it manages?   1. So should I make `ListManager.add(Cue c)` as a wrapper for `CueList.add(Cue c)`.    2. OR should I just add getters for the three objects and let the rest of my program use that to manipulate them. I tend to think that the later option is far more maintainable, but at the same time, the code produced if I make the wrapper just seems... prettier... What's the best practice in situations like this?


Assuming:   * The employee and company are parting on good terms   * The new company is OK with a little contract work as long as it doesn't distract from the new job   * The former company wants the help and the employee is willing to work a few hours a week Is it a good idea to do contract work for a former full time employer? Has anyone ever done this? How did it work out for you? I can see some possible pitfalls, so I wonder how good an idea it really is. What difficulties do you encounter doing development work outside the office and on a different schedule from the rest of the programming staff and how can they be overcome? If I do go forward, what would be a fair amount to request as compared to current salary?


Are there any notable examples of business disasters directly attrutible to open-source software?

In "enterprise" environments, I've observed a strong prejudice towards proprietary software. Even in large business that use Java, it is unusual to find MySQL or PostgreSQL, and WebSphere and WebLogic are strongly preferred over JBoss or Tomcat. This is very understandable. While many developers prefer Tomcat or Postgres to WebSphere or Oracle DB, they are not the ones that make the final decisions in these matters. Whoever does make the decision regarding which DBs and application servers will be used in production will find that the licence fees seem quite small compared to being fired for choosing the free software that caused something really, really, bad to happen. I'm not asking the question of whether Postgres is as good as Oracle. That's not the point. Oracle doesn't get chosen over Postgres after a careful considerations of features and benchmarks. Postgres doesn't enter the conversation, because free software isn't trusted in certain places. I'm curious if this lack of trust came about in response to any specific events. So my question is this: **Are there any documented cases of business calamities (failures, significant loss of revenue, significant loss of corporate data, etc.) that were shown to be the result of deficiencies in open-source software?** _Clarification:_ If you have experience with enterprise level companies that fully embrace OSS, that have to prejudice in the matter but make choices based on the needs of the particular situation, then **Good for you!** Your experience doesn't change the fact that other enterprise companies have a very different attitude, and my question is valid even if these companies are in the minority.


Workflow: Using binary document formats in Git without locks (moving from subversion)

We're a software consultancy with a multitude of projects for different customers. We traditionally use Subversion, but are currently considering moving to Git. A significant portion of the documents we produce are shared with our customers (requirements, global designs, test specs, etc), and we use MS Office to produce these. In Subversion, we could use its "Lock" feature to ensure that no one was editing the same document at the same time. In Git, you can't do that since by its distributed nature, git doesn't have locks. Locks are really little more than a communication mechanism, but they're a very effective one. Currently, our code and customer-facing documents are typically in different subfolders of a different svn repository. When moving to git, what would you recommend we do? I see a set of options:   1. We move the svn repositories to git 1-on-1. Instead of using locks on the Office files, we do what the git people suggest and somehow try to change our workflow to fix it. This could be working in a branch on any document edit, and merging that over review. This approach breaks over e.g. Excel sheets that contain project management info; they're easily edited by team members (and we encourage that this is done), but not subject to any formal review process   2. We use git for code and svn for docs and project management. This has the disadvantage that certain more design-ish documents won't be "nearby" the code it specs, increasing the chance that people forget to update them. Additionally, everybody has to use and understand two sets of tools. That said, maybe this is a great opportunity to move to text-based doc tools (latex, markdown, HTML, whatever) for non-customer-facing design docs.   3. Like 1, but we hack up a `git lock` command that does what svn lock does for us (toggle the read-only flag appropriately and sync with a server through some means). I don't buy the argument that locks don't work in a DVCS because the system should even work when you're entirely offline. Svn locks can be overridden as well; they're a _communication_ mechanism. Without some sort of network connection, you won't get your computer to communicate a lot. We can't be the only shop who're very happy with how `svn lock` fits in our workflow, right? Any ideas or tips? I found http://stackoverflow.com/questions/119444/locking-binary-files-using- git-version-control-system but the discussion is rather technical; i'm looking for ways to solve or avoid the practical problem of two team members editing the same binary file at the same time.


Reveal detailed license-errors?

So after one has programmed and integrated a licensing solution into his or her application, how should one deal with licensing errors? My understanding is: Show whether a license is valid or invalid - and report if the license server is not reachable. Nothing more, nothing less. Licenses could be invalid due to a variety of reasons: Invalid Machine-Code, maximum number of activations reached, invalid licensed version... But should we report them to the user or just tell him "okay", "not okay" or "license server not reachable"? I don't know if this is the right place to ask, maybe security.stackexchange.com is more suitable, but that could be true for ux.stackexchange.com, too... So I'm asking it here.


Can I migrate a clone of Google Code repository into Github?

I want to create a clone of a Google Code repository, which I cannot download due to Country restrictions and I want to migrate that clone into Github, which I can use without any problem. The thing is I have a Github account and I can browse through GoogleCode but I cannot take my TortoiseHg and clone a repo just like that because I'm from Cuba and I get a lovely Google page saying that I cannot go into Google code. I'm guessing you know how I manage to browse :) I would like to import a mercurial repository into my Github repo, my questions:   * **Is it possible?**   * **How can I do it?**


Wrapping basic functions in high-level functional-programming languages

I'd like to know if there's a general guide or best practice for wrapping basic functions. Let's take J for example. It has several 1-or-2 character "functions" called primitives. Examples:   * `,` : Flatten a matrix or append to a vector   * `{` : Catalogue combinations or take nth item of a matrix   * `{.` : Take first or n elements of a matrix   * `}` : Amend items in a matrix Some J programmers think it best to use them as such, other will wrap them in functions like so:   * `Append =: ,`   * `TakeFirst =: {.` I found that's not always practical because I'm used to the actual "symbols", but that basically means I'm biased. So, any advice on the best practice to use? To wrap or not to wrap?


Which is better: to include HTML inside PHP code or outside it?

Look at this:               <?php     echo "Hello World";     ?>
     <?php     echo "Welcome";     ?>      And now look at this:               <?php     echo "Hello World";     echo "
";     echo "Welcome";     ?>      Which one of the above examples is considered to better (at least from performance point of view)?. I know the examples are trivial but I want to follow good practice habits from the beginning so when I have more and more lines they would not affect the performance or whatever in a negative way.


How to find a project that uses specific frameworks/technologies?

I would like to practice specific technologies/frameworks like Hibernate, Spring, GWT and so on. How can I find an open-source project that uses specific frameworks technologies so I can contribute to it?


Why was the percent sign (%) chosen as the format specifier for the printf family of functions?

Everyone knows that, at least in C, you use the `printf` family of functions to print a formatted string. And these functions use a percent sign (`%`) to indicate the beginning of a format specifier. For example, `%d` means to print an `int`, and `%u` means to print an `unsigned int`. If you're unfamiliar with how the `printf` function and format placeholders work, or simply need a refresher, the Wikipedia article is a good place to start. **My question is, is there a particularly compelling reason why this was originally or should be chosen in the future as the format specifier?** Obviously the decision was made a long time ago (very likely for a predecessor of even the C language), and it's been more or less "standard" ever since then (not only in C, but also in a vast array of other languages that have adopted its syntax to varying degrees), so it's far too late to ever change. But I'm still curious if anyone has any insight on why this choice might have been made in the first place, and whether it still makes sense as the choice if one is designing a new language with similar functionality. For example, with C# (and the other family of .NET languages), Microsoft made a slightly different decision regarding the operation of the string formatting functions. Although some degree of type safety can be enforced there (unlike with the implementation of `printf` in C), and therefore it is unnecessary to include an indication of the type of the corresponding parameter, they decided to use zero-indexed pairs of curly braces (`{}`) as format specifiers, like so:               string output = String.Format("In {0}, the temperature is {1} degrees Celsius.",                                   "Texas", 37);     Console.WriteLine(output);          // Output:     //     In Texas, the temperature is 37 degrees Celsius.      The documentation for the `String.Format` method contains more information, as does this article on composite formatting in general, but the exact details are rather unimportant. The point is simply that they abandoned the long- standing practice of using `%` to indicate the beginning of a format specifier. The C language could just have easily used `{d}` and `{u}`, but it didn't. Anyone have any thoughts on why, whether this decision makes sense in retrospect, and whether new implementations should follow it? Obviously there's no character that could be chosen that wouldn't have to be escapable so that it could be included in the string itself, but that problem is quite well solved already by just using _two_ of them. What other considerations are relevant?


Limitations of Polymorphism in statically typed languages

I program mostly in statically typed languages, like C++ and Java. A common strategy employed in languages like these to handle dealing with collections of objects which are _related_ , but which need to employ specific behaviors, is to use polymorphism and inheritance hierarchies. But Polymorphism only works when the Base class has a method (virtual function) which can then be overridden by every Derived class. But there are often cases where a Derived class needs to have a method, and it doesn't make sense to place a method of the same name in the Base class, because it is very specific to the Derived class. Let me give a concrete example that many of us can probably relate to: the HTML DOM. Javascript programmers are quite used to doing things like iterating over collections of DOM nodes. They take for granted the dynamically-typed nature of Javascript when they do something like:               node = document.getElementById("foo");     for (var i = 0; i < node.childNodes.length; ++i)          doSomething(node.childNodes[i]);      Something like this would be very messy to do in a statically typed language like Java, because inheritance-based polymorphism doesn't lend itself well to situations where Derived classes have methods which don't exist in the Base class. For example, when iterating over the above HTML Nodes, we might find a DIV node, which has certain methods, and a Text node, which has certain different methods, and a TABLE node, which has its own unique methods - and it wouldn't make much sense for ALL of these various methods to exist in a common Base class "Node", because they are highly specific to each Derived type. (e.g. a DIV node has no need of a "cells" method, but a TABLE node does.) So, in a statically typed language, you'd be forced to fall back on something like Type Enums and a lot of messy down-casting to check what type of Node you have. So basically you end up with messy code like:               Node node = document.getElementById("foo");     for (int i = 0; i < node.childNodes().length(); ++i)      {        Node n = node.childNodes().elementAt(i);        if (n.type() == Node.DIV_NODE) doSomethingWithDiv(((DivNode)(n)));        else if (n.type() == Node.TABLE_NODE) doSomethingWithTable(((TableNode)(n)));        /* etc... */     }      This is similar to what C programmers do, and it's seemingly the sort of thing virtual functions were designed to _avoid_. And yet, when you're faced with a situation where there are various different methods in a Derived class for which it doesn't make any sense to place in a common base class, you have no recourse but to resort to something like Type Enums. So, how is this problem usually addressed in statically-typed languages? Is there a better design pattern than Type Enums?


Javascript, JQuery and now AngularJS What is happening?

I have been away from computers for about 3 years and starting to get back into programming. Lots has changed in resources and help sites available on the web especially the evolving StackExchange community. I come from the IRC #javascript, #html, #php days with php.net and a bit of google search finds here and there. With that said, before I took my break from programming JQuery was around but not nearly as common as today. I personally stay away from it finding it easier to just write what I need done in traditional javascript. Now I have just stumbled across AngularJS. I do not know much about it, just looked at the home page and saw a few script samples. My question is: Am I hindering my clients by using javascript while being ignorant to JQuery and/or AngularJS?


Graph/diagram editor that works with pseudographics

Is there a graph/diagram editing tool that can output (or even better also parse) pseudographics, that can be easily inserted into source code comments? Like this:               +---------------+                 |  Some Class   |            +---------------+     |  ----------   |----------->| Another Class |     | @its_attribute|            +---------------+     | @another_attr |           /      +---------------+  --------/             |         /             |        /     +---------------+     |Something Else |     +---------------+


Ship Early, Ship Never

This started as a "Note to Self," so please excuse me if the frustration is all too evident and the writing is less than stellar... Three major subjects I've had at the forefront of my mind lately:   1. Motivation   2. Learning (Curiosity)   3. Doing (Making) I've been studying motivation and incentives for months now. It seems there are an infinite number of different motivations that people might have for doing things (I realize that sounds trite but bear with me). I've been really drawn to it because I'm desperate to find out **why I do the things I do and why I don't do the things that I want to do but don't do**. I'm in the midst of reading Paul Graham's excellent Hackers and Painters book. In it, he makes the case that hackers and painters are very similar because they are both "makers." Painters _make_ paintings. Hackers _make_ software. Painters don't necessarily need to understand the chemical composition of paint to make beautiful paintings. And hackers don't necessarily need to know 1's and 0's to make beautiful software. Graham then draws the distinction between disparate computer science fields:   1. some people seem to be studying mathematics   2. some people seem to be studying the computers themselves   3. the hackers are _making_ software. The difference is incredibly important. It seems the motivation for some is to _make_ beautiful things. And the motivation for the others is to learn out of curiosity. Certain motivations seem obvious to me, but curiosity seems a bit less obvious. I would certainly consider myself as a curious person with a seemingly unquenchable thirst to learn just about everything I can. But this is exactly where the problem comes up. The thing that scares me so much is that I desperately want to _make_ things. I desperately want to _do_ things. I want to write a book. I want to paint a painting. I want to compose a song. I want to _do_ things like travel. But the strangeness is that I also want to _learn_ things. I want to learn to play guitar. I want to _learn_ about art history. I want to _learn_ more about philosophy and literature. The key seems to be the balance between learning and doing... between studying and making. While I'm not sure how much one should learn about a given thing before doing it, I know for certain that I find myself constantly on one side rather than the other. As it stands now (and as far as I can tell I've always been this way), I am a learner and not a doer. I've read great books. I've practiced guitar for years. I've spent countless hours studying programming. But I've written 0 books. I've composed 0 songs. I've coded 0 beautiful programs. I've painted 0 beautiful paintings. I've started 0 viable businesses. The scary part of all this is that there are probably countless unfinished works of art in the world. Is this my misanthropic revenge against society and culture to never _produce_ or _finish_ any of the works of art that I start? Perhaps the worst part (aside from this being my natural inclination), is the fact that I f***ing know better. I just finished books like "Getting Things Done" and "Making Ideas Happen." I've aggregated and synthesized countless words of wisdom on how to _do_ things and how to _make_ things. Imagine the horror of going through life without being able to do the things you want to do. If this is something you've struggled with (and hopefully overcome), please share. If not... perhaps some delicious pity would make me feel better. [UPDATE: Just wanted to send a quick thanks to everyone that shared their thoughts. I deliberately left the question somewhat open-ended in hopes of encouraging discussion and having others refashion the central problem around their similar experience, and I think it worked out great... there's a lot of amazing insight here to work with and it was really helpful. Thanks again.]


Do startups need a dba?

I am a Database/ BI person with 5+ years of experience (SQL Server and Oracle). I would really love to work for a startup, but from the feeling I get from seeing the job postings, most startups are not looking for people other than developers for their IT team. Do startups even look for other IT people other than developers? And if so, how can I connect with ones that are looking for DB persons?


Which is more expensive multiple conditional branches or multiple relational expression in a single condition?

Which is more expensive in terms of processing costs               if ( x < 20 && z == "M") {         // statements 3     }          if ( x >= 20 && w && x <= 65) {         // statements 1     }           if( x >= 20 && z == "F"){         // statements 2     }      or this               if ( x < 20 ) {         if( z == 'M') // statements 3;     } else         if ( x <= 65 && w == true ) // statements 1;         if ( z == 'F' ) // statements 2;     }


How important is it to reduce the number of lines in code?

I am a Software developer who works on J2SE (core java).   Often during our code reviews we are asked to reduce the number of lines in our code. It's not about removing redundant code, it's about following a style that focuses on doing the same things with fewer lines in the code, while I believe in having clarity in code even if it means increasing the number of lines. What do you think is the right way of doing things?   If LOC (lines of code) is a small number, how does it affect the code? If LOC is a larger number, how does it affect the code? example from the website : "javaranch" -               public static void happyBirthday(int age)     {               if ((age == 16) || (age == 21) || ((age > 21) && (((age % 10) == 0) || ((age % 25) == 0))))                 {                  System.out.println("Super special party, this year!");         }         else         {             System.out.println("One year older. Again.");         }     }      VS               public static void happyBirthday(int age)     {              boolean sweet_sixteen = (age == 16);         boolean majority = (age == 21);         boolean adult = (age > 21);         boolean decade = (age % 10) == 0;         boolean quarter = (age % 25) == 0;              if (sweet_sixteen || majority || (adult && (decade || quarter)))         {             System.out.println("Super special party, this year!");         }         else         {             System.out.println("One year older. Again.");         }     }


Entity Framework 6 Conventions

I use the Entity Framework often, but I have one area of confusion I would like to understand better. If I wanted to have a navigation property in an Entity such as               public virtual ExampleObject Example {get;set;}      it is also the done thing to have an Id property               public int ExampleId {get;set;}      My undertsanding is this creates a FK, but if I omit it, the functionality is the same and the FK seems to be created anyway. So, is there a reason for the additional field?


Why doesn't the .NET world have anything like rails/grails/django/roo?

It seems to me that rapid-development web platforms are going to radically change the world of web applications. It has been five years since Rails 1.0 was released for Ruby, and since that time we have seen Grails for Groovy, Django for Python, and Roo for Java. But to my knowledge (which is probably limited, being a Java/Groovy progammer) there is no similar framework for C#. Does such a thing exist? If not, why not? **Edit:** It's quite possible I'm not using the right words when I say "rapid- development," but I'm talking about frameworks that can conceivably allow you to build a working blog engine in 30 minutes. You couldn't reasonably do this with, say, Java, Spring, and Hibernate, given the various configuration needed to allow your controllers to be found, and both configuration and code necessary for your entities to persist and be retrieved. So I'm talking about frameworks that handle all of the CRUD with a convention- over-configuration mentality. If someone has the right words for what I'm talking about, let me know.


How can I get an anonymous user to submit bugs on a private GitHub project?

Our company has a private GitHub repository for the project I'm working on. After a full summer of work, it looks like we'll be launching this week (wheee!). However, I want to include a "submit a bug" link in the program that leads to a form somewhere where the user can fill out a form that becomes an issue for us on GitHub. Googling around hasn't found any solution (or someone who has the same problem). Is this possible (through some API, perhaps?) or will I have to manually enter the bugs my users report?


"A proof is a program; the formula it proves is a type for the program"

This might be a philosophical kind of question, but I believe that there is an objective answer to it. If you read the wikipedia article about Haskell, you can find the following: > The language is rooted in the observations of Haskell Curry and his > intellectual descendants, that "a proof is a program; the formula it proves > is a type for the program" Now, what I'm asking is: doesn't this really apply to pretty much all the programming languages? What feature (or set of features) of Haskell makes it compliant with this statement? In other words, what are the noticeable ways in which this statement affected the design of the language?


Can one edit a built-in Python module?

I'm currently learning Python and I'm at the point in the book about using the Math library. I looked on the Python website and noticed the library was a bit scarce and am writing some more useful functions. For example, I went ahead and wrote a function to take coefficients and return the roots of the equation. Essentially a quadratic formula function. I'm wondering if it's possible to add this to the python Math library. If it isn't, how do I save it such that I can use that function in other Python programs I write just by calling it?


Object Design & Cohesion - Issue & potential refactoring

**Abstract** I have been trying to get my head around the cohesiveness of some functionality in our code base. I’ve approached this design in different ways, and lately I’m convinced that I took the wrong approach, as in I incorrectly applied the Single Responsibility Principle. **Issue** The problem domain is a Well, otherwise known as a round hole in the ground. The current code looks something like this... I have a set of data in a data only object... Note: This is not the full code, just method names to keep things short...               public class WellData     {         public string Name { get; set; }         public ICollection<SurveyPoint> SurveyPoints { get; set; }         public ICollection<GeometryItem> GeometryItems { get; set; }         public ICollection<TemperaturePoint> WellTemperature { get; set; }         public ICollection<FluidPoint> WellFluids { get; set; }     }      I broke functionality that operates on this data into several small classes. As per below…               public class ReferenceWellSurvey     {        ICollection<SurveyPointCalculate> _calculatedSurveyPoints;        double GetTvdAtDepth(double depth) {}        double GetAzimuthAtDepthRad(double depth) {}        double GetInclinationAtDepthRad(double depth){}        double GetTortuosityPeriodAtDepth(double  depth ) {}        double GetTortuosityAmplitudeAtDepth(double depth ) {}     }          public class ReferenceWellGeometry     {        ICollection<GeometryItem> _geometryItems;        double GetFrictionAtDepth(double depth) {}        double GetHoleIdAtDepth(double depth) {}     }          public class ReferenceWellTemperature     {        ICollection<TemperaturePoint> _wellTemperatures;        double GetTemperatureAtDepth(double depth) {}        double GetSurfaceTemperature(double depth) {}     }     Etc.      I’ve realized lately when looking at our code that I have to glue all this back together to make it usable where I need it in the application logic. Something like….               public class ReferenceWellData     {     private IReferenceWellGeometry _refWellGeometry;     private IReferenceWellTemperature _refWellGeometry;               private IReferenceWell _refWellGeometry;               private IReferenceFluid _refWellFluid;            //Proxy functions from each class to glue it all back together…     }      A few things that led me to the current mess. The well data class contains several collections of information and if everything is in one class most functions will only operate on a small subset of the data. At the time I felt that would create low cohesion, now a few months later, I feel these things do actually all belong together. Additionally, there are several classes in my code that need to call just one method of the ReferenceWellSurvey class, GetTvdAtDepth(). Really what I did didn’t solve this issue. After thinking more about this, and after reading this Wikipedia article http://en.wikipedia.org/wiki/Cohesion_(computer_science), I’m starting to see that I have committed a few programming sins. • Anemic domain model • Low cohesion • Constructor over injection in code where I try to glue things together • Giving a class that depends on GetTvdAtDepth access to other methods that it does not need, violated Interface Segregation Principle. **Solution** I’m looking for that Goldilox design that doesn’t give too much responsibility to any one class (No God Objects), while yet maintaining a good degree of cohesion.   My current thoughts on fixing this are as follows. Move the functionality that operates on the well data into the same class. This should help get this functionality closer to Communicational/informational cohesion.               public class WellData : IWellData      {         public string Name { get; set; }         public ICollection<SurveyPoint> SurveyPoints { get; set; }         public ICollection<GeometryItem> GeometryItems { get; set; }         public ICollection<TemperaturePoint> WellTemperature { get; set; }         public ICollection<FluidPoint> WellFluids { get; set; }             // Operates on SurveyPoint collection         double GetTvdAtDepth(double depth) {}        double GetAzimuthAtDepthRad(double depth) {}        double GetInclinationAtDepthRad(double depth){}        double GetTortuosityPeriodAtDepth(double  depth ) {}        double GetTortuosityAmplitudeAtDepth(double depth ) {}        //Operates on WellGeometry collection         double GetFrictionAtDepth(double depth) {}        double GetHoleIdAtDepth(double depth) {}        //Operates on WellTemperature collection        double GetTemperatureAtDepth(double depth) {}        double GetSurfaceTemperature(double depth) {}     }      Next to address the issue of several classes needing just one function, I could make this one function into a separate interface IGetTvdAtDepth. In this way, my classes that need that functionality can depend just on this interface, which I can inherit into my WellData interface, and implement it there, but not tie my other classes to all the functionality that is in my WellData class. Thoughts on this approach vs. the original approach? One thing that bothers me about doing things way is that in my API I'm using bastard injection to fulfill the required dependencies of this class... Right now I have three required dependencies, a Survey calculator, and a special class that references data at different measured depths. I'd like to move away from this, but that seems to point back toward having services do more of the lifting...


How can I motivate my teammates to work?

I've been recruited in a small team of seven developers about 4 months ago on a small scale Java project involving a basic game development, where each programmer has to do a certain part. For example programmers 1,2 and 3 have high experience in Java and they get harder tasks, while programmers 4 and 5 handle the small details of the project. (They also program, but they get the boring stuff) We are relatively well organised, we all live in different countries and communicate by skype and share the source by Dropbox, where we keep a log of updates, a task list and whatnot, but in general a problem always occurs in the project development. Basically everyone gets motivated for a day or two and works on some fast code that does it's job (Although not always 100% efficient, but clean and maintainable) then stops working and becomes un-motivated because he thinks he's the only one doing his job. Very little work gets done and their programming knowledge could lead the project sky-high if they used it properly. There's always a de-motivating factor in project development, such as "I don't like this feature, I think we should go back" or "Nobody works so I won't either" and in the end, it all turns out messy. My question is - what could be done to motivate them? How could I manage them in a way to constantly have them working on the project? **EDIT:** I forgot to add that all the programmers on the project are doing this mostly for experience, **_they work for free_** and they do not get paid. I personally work because I wish to gain experience in working with a team.


How can a true Vector be implemented in Haskell?

How could a true Vector type be implemented in Haskell? In order for something to be a Vector, it has to be stored sequentially in memory, with `O(1)` random access. But Haskell hides its memory management, and its datatypes describe trees! So how could you express that kind of requirement?


Classic inheritance problem?

I keep seeing the following pattern when people learn about OOP: Problem: How do I put objects of different but related types into a container? Solution: Inherit from a common base class. New problem: I have a bunch of base class objects, how do I get the real type? Solution: ??? The classic inheritance example is to make a graphics program that deals with geometric objects. We have `Circle`s, `Ellipse`s and `Triangle`s. All these objects have a common base `Drawable`. ![Drawable](http://i.stack.imgur.com/LuLXm.png) In C++ this might look something like this:               struct Drawable{         virtual ~Drawable(){}         virtual void draw() const = 0;     };          struct Triangle : Drawable{         Point p1, p2, p3;         void draw() const override;         void stretch(double xfactor, double yfactor);         std::touple<double, double, double> getAngles() const;         //...     };          struct Circle : Drawable{         double radius;         void draw() const override;         //...     };          struct Ellipse : Drawable{         double radius;         void draw() const override;         //...     };          std::vector<Drawable *> drawables = {new Circle, new Triangle, new Ellipse};     for (const auto &d : drawables)         d->draw();      So far so good. Now I want to increase the radius of my `Circle`s and `Ellipse`s. As far as I know there are 4 ways to do that: 1: Put everything into the base class. The base class gets the virtual functions `getAngles`, `getRadius`, `stretch` and `getEccentricity`. There is a default implementation for each so that for example `getRadius` returns some dummy value when you are dealing with a `Triangle`. After this is done you can easily iterate over the `Drawable`s and increase their radius. This makes the base class ridiculously huge and working on a `vector<Drawable *>` becomes inefficient because the functions do nothing for most elements. 2: Use `dynamic_cast` hacks.               for (const auto &d : drawables){         if (dynamic_cast<Circle *>(d))             ((Circle *)d)->radius++;         else if (dynamic_cast<Ellipse *>(d))             ((Ellipse *)d)->radius++;     }      Unfortunately you need to repeat this ugly syntax every time you need to do something like this. You cannot put it in a function or macro. Every time a new `Drawable` is added you have to go through the whole code base and add it where appropriate. Also the `if`/`else`-chain is fairly inefficient. 3: Add a Tag as the first member variable and cast accordingly.               for (const auto &d : drawables){         switch(d->tag){             case Tag::Circle:                 ((Circle *)d)->radius++;                 break;             case Tag::Ellipse:                 ((Ellipse *)d)->radius++;                 break;         }     }      Slightly more efficient due to a switch instead of an `if`/`else`-chain, but there is already a kind of tag that shows the dynamic type, so the tag is redundant. Also it has the same problem as 2: since you need to change the whole code base whenever a new `Drawable` comes along. 4: Just keep the objects in separate containers.               vector<Circle> circles;     vector<Triangle> triangles;     vector<Ellipse> ellipses;     for (auto &c : circles)         c.radius++;     for (auto &e : ellipses)         e.radius++;      This is very efficient memory layout wise and you only iterate over objects that matter. It is my favorite, but unfortunately it breaks the first solution in that you do not keep differently typed objects in a single container. I tried to solve the problem by creating a variadic template that internally has a `vector` per type and forwards insertions to the right container. Ideally it would completely hide the fact that there are different containers under the hood. Usage would look something like this:               MultiVector<Triangle, Circle, Ellipse> mv;     mv.push_back(Triangle());     mv.push_back(Circle());     mv.push_back(Ellipse());     for (auto &d : mv.get<Circle, Ellipse>())         d.radius++;      The solution is not perfect, for example different types do not keep their order and implementing the iteration is tricky. I presented this problem and solution attempt to my (university) research group and got the reactions " _If you design your classes right this is not a problem_ " and " _The proposed solution is a very specific tool to solve a very specific problem and it is questionable at best to add even more complexity to c++ for such a minor detail_ ". In my opinion this is a very basic problem that needs fixing and the usual solution of better class design only tries to find the least evil of the 4 workarounds in the specific case without actually solving the problem. The problem comes up almost every time inheritance is used. So finally here is the question: Did you run into this problem too / is this a real problem? Do you know of another workaround/solution? Do other languages deal better with the problem? I want to simulate a poll using 2 comments below so feel free to upvote either " _I never had this problem / The problem is easily solved._ " or " _I also had this problem and never solved it to my satisfaction._ " Edit: To prevent a close due to primarily opinion based / discussion: I want a clear answer that solves the problem or some resource that says that there is none. Edit: Related: Do I really have a car in my garage?


Using lambdas to improve encapsulation

Just as many people believe tenaciously in small functions, some people believe lambdas should only contain small code fragments. An often overlooked advantage of lambdas however, is using them you can **encapsulate behavior which you would otherwise have to make available to the entire class**. Isn't it is a true advantage to maintain proper encapsulation, regardless of line count? Which possible disadvantages of using anonymous functions with a lot of lines of code am I overlooking? * * * The following is an actual example. `argumentsMatch` does very specific argument matching, highly dependent on the behavior of the function in which it is defined. The following code IMHO follows the Single Responsibility Principle. Moving `argumentsMatch` to a private method would result in it only being called from within this method.               /// <summary>     ///   Get the first found matching generic type.     ///   The type parameters of the generic type are optional.     ///   E.g. Dictionary<,>     ///   When full (generic) type is known (e.g. Dictionary<string,string>),     ///   the "is" operator is most likely more performant,     ///   but this function will still work correctly.     /// </summary>     /// <param name = "source">The source for this extension method.</param>     /// <param name = "type">The type to check for.</param>     /// <returns>     ///   The first found matching complete generic type,     ///   or null when no matching type found.     /// </returns>     public static Type GetMatchingGenericType( this Type source, Type type )     {         Type[] genericArguments = type.GetGenericArguments();         Type rawType = type.IsGenericType ? type.GetGenericTypeDefinition() : type;              // Used to compare type arguments and see whether they match.         Func<Type[], bool> argumentsMatch             = arguments => genericArguments                 .Zip( arguments, Tuple.Create )                 .All( t => t.Item1.IsGenericParameter || // No type specified.                            t.Item1 == t.Item2 );              Type matchingType = null;         if ( type.IsInterface )         {             // Traverse across all interfaces to find a matching interface.             matchingType =                  (from t in source.GetInterfaces()                  let rawInterface = t.IsGenericType ? t.GetGenericTypeDefinition() : t                  where rawInterface == rawType &&                        argumentsMatch( t.GetGenericArguments() )                  select t).FirstOrDefault();         }         else         {             // Traverse across the type, and all it's base types.             Type baseType = source;             while ( baseType != null && baseType != typeof( object ) )             {                 Type rawCurrent = baseType.IsGenericType                     ? baseType.GetGenericTypeDefinition()                     : baseType;                 if ( rawType == rawCurrent )                 {                     // Same raw generic type, compare type arguments.                     if ( argumentsMatch( baseType.GetGenericArguments() ) )                     {                         matchingType = baseType;                         break;                     }                 }                 baseType = baseType.BaseType;             }         }              return matchingType;     }


sizeof style: sizeof(type) or sizeof variable?

I've seen two styles of using `sizeof` for memory-related operations (such as in `memset` or `malloc`):   * `sizeof(type)`, and   * `sizeof variable` or `sizeof(variable)` Which one would you prefer, or would you use a mix of the two styles, and when would you use each style? What are the pros and cons of each style and when you use them? As an example, I can see the following pair of situations where one style helps and the other doesn't: When you get the pointer indirection wrong:               type *var;     ...     memset(var, 0, sizeof var);    /* oops */      When the type changes:               new_type var;    /* changed from old_type to new_type */     ...     memset(&var, 0, sizeof(old_type));    /* oops */


Keeping track of all objects of a class

I'm new to object-oriented programming, and I keep running into this issue. (I'm programming in Java) I've been a bit reluctant to ask about this, since it seems like such a basic issue, but I can't find any information on it, or questions about it here, and none of the textbooks I have read (on a quite basic level of course) have touched on this issue: Often I need to keep track of all objects of a class that have been created, to iterate through them for various purposes. They way I currently write programs, many objects are only referenced from other objects, meaning I have no array or collection with which to reference them all. I imagine that, as this seems like such a very basic necessity in OOP, there should be a quite institutionalized, and simple, way to go about this? Is it usual practice to keep a separate list of all the objects of a class? I thought about a static array or collection, to which through its constructor, every new object created would be added. This however would not work with subclasses, since constructors are not inherited? I realize this question might not have one easy answer; I just hope someone can enlighten me a bit on this subject. I feel like if I'm lacking a central piece of knowledge here.


IXRepository and test problems

Recently had a doubt about how and where to test repository methods.   Let the following situation: I have an interface `IRepository` like this:               public interface IRepository<T>         where T: class, IEntity     {         IQueryable<T> Query(Expression<Func<T, bool>> expression);         // ... Omitted     }      And a generic implementation of `IRepository`               public class Repository<T> : IRepository<T>         where T : class, IEntity     {         public IQueryable<T> Query(Expression<Func<T, bool>> expression)         {             return All().Where(expression).AsQueryable();         }     }      This is an implementation base that can be used by any repository. It contains the basic implementation of **my ORM**. Some repositories have specific filters, in which case we will `IEmployeeRepository` with a specific filter:               public interface IEmployeeRepository : IRepository<Employee>     {         IQueryable<Employee> GetInactiveEmployees();     }      And the implementation of `IEmployeeRepository`:               public class EmployeeRepository : Repository<Employee>, IEmployeeRepository // TODO: I have a dependency with ORM  at this point in Repository<Employee>. How to solve? How to test the GetInactiveEmployees method     {         public IQueryable<Employee> GetInactiveEmployees()         {             return Query(p => p.Status != StatusEmployeeEnum.Active || p.StartDate < DateTime.Now);         }     }      ## Questions   1. Is right to inherit `Repository<Employee>`?   The goal is to reuse code once all implementing `IRepository` already been made. If `EmployeeRepository` inherit only `IEmployeeRepository`, I have to literally copy and paste the code of `Repository<T>`.   2. In our example, in `EmployeeRepository : Repository<Employee>` our `Repository` lies in our ORM layer. We have a dependency here with our ORM impossible to perform some **unit test**.   3. How to create a **unit test** to ensure that the filter `GetInactiveEmployees` return all Employees in which the Status != Active and StartDate < DateTime.Now. I can not create a Fake/Mock of `IEmployeeRepository` because I would be testing? Need to test the actual implementation of `GetInactiveEmployees`. The complete code can be found on Github


The Request/Response Cycle

When User A decides he want to pay a visit to http://example.com/ it all begins with a Request. A short moment later he is given a Response. In this cycle Request-Response a lot is going on, in different frameworks it's decoupled in different components among them Routing, Dispatching, etc. I'm looking to make a simple experimental MVP Framework for my learning, trying to use as many best practices, heck who knows it might even be worth using when I'm done. I'm not sure how I should decouple this cycle in to these different components and I'm not even sure of what each component is responsible for (Thinking SOLID, DRY, SRP, etc). That is what I am asking, looking at different frameworks these components seem to have different use-areas from time to time. What is each of these components responsible for and in what order are the used? Request, Response, Dispatcher, Router, Front Controller, Bootstrap, Events.


Difficulties With TDD & Refactoring (Or - Why Is This More Painful Than It Should Be?)

I wanted to teach myself to use the TDD approach and I had a project I had been wanting to work on for a while. It wasn't a large project so I thought it would be a good candidate for TDD. However, I feel like something has gone awry. Let me give an example: At a high level my project is an add-in for Microsoft OneNote that will allow me to track and manage Projects more easily. Now, I also wanted to keep the business logic for this as decoupled from OneNote as possible in-case I decided to build my own custom storage and back end some day. First I started with a basic plain words acceptance test to outline what I wanted my first feature to do. It looks something like this (dumbing it down for brevity):   1. User clicks create project   2. User types in title of project   3. Verify that the project is created correctly Skipping over the UI stuff and some intermediary planning I come to my first unit test:               [TestMethod]     public void CreateProject_BasicParameters_ProjectIsValid()     {         var testController = new Controller();         Project newProject = testController(A.Dummy<String>());         Assert.IsNotNull(newProject);     }      So far so good. Red, green, refactor, etc. Alright now it needs actually save stuff. Cutting out some steps here I wind up with this.               [TestMethod]     public void CreateProject_BasicParameters_ProjectMatchesExpected()     {         var fakeDataStore = A.Fake<IDataStore>();         var testController = new Controller(fakeDataStore);         String expectedTitle = fixture.Create<String>("Title");         Project newProject = testController(expectedTitle);              Assert.AreEqual(expectedTitle, newProject.Title);     }      I'm still feeling good at this point. I don't have a concrete data store yet, but I created the interface how I anticipated it would look. I'm going to skip a few steps here because this post is getting long enough, but I followed similar processes and eventually I get to this test for my data store:               [TestMethod]     public void SaveNewProject_BasicParameters_RequestsNewPage()     {         /* snip init code */         testDataStore.SaveNewProject(A.Dummy<IProject>());         A.CallTo(() => oneNoteInterop.SavePage()).MustHaveHappened();     }      This was good until I tried to implement it:               public String SaveNewProject(IProject project)     {         Page projectPage = oneNoteInterop.CreatePage(...);     }      And THERE is the problem right where the "..." is. I realize now at THIS point that CreatePage requires a section ID. I didn't realize this back when I was thinking at the controller level because I was only concerned with testing the bits relevant to the controller. However, all the way down here I now realize I have to ask the user for a location to store the project. Now I have to add a location ID to the datastore, then add one to the project, then add one to the controller, and add it to ALL of the tests that are already written for all of those things. It has become tedious very quickly and I can't help but feel like I would have caught this quicker if I sketched out the design ahead of time rather than letting it be designed during the TDD process. Can someone please explain to me if I've done something wrong in this process? Is there anyway this kind of refactoring can be avoided? Or is this common? If it is common are there any ways of making it more painless? Thanks all!


Multiple arguments in function call vs single array

I have a function that takes in a set of parameters, then applies to them as conditions to an SQL query. However, while I favored a single argument array containing the conditions themselves:               function searchQuery($params = array()) {         foreach($params as $param => $value) {             switch ($param) {                 case 'name':                     $query->where('name', $value);                     break;                 case 'phone':                     $query->join('phone');                     $query->where('phone', $value);                     break;             }         }     }      My colleague preferred listing all the arguments explicitly instead:               function searchQuery($name = '', $phone = '') {         if ($name) {             $query->where('name', $value);         }              if ($phone) {             $query->join('phone');             $query->where('phone', $value);         }     }      His argument was that by listing the arguments explicitly, the behavior of the function becomes more apparent - as opposed to having to delve into the code to find out what the mysterious argument `$param` was. My problem was that this gets very verbose when dealing with a lot of arguments, like 10+. Is there any preferred practice? My worst-case scenario would be seeing something like the following: `searchQuery('', '', '', '', '', '', '', '', '', '', '', '', 'search_query')`


Is it worth to move from ASP webforms to ASP MVC?

I have one year experience on ASP.net webforms and now I decided to move to another company where ASP MVC is the architecture. I decided because I always felt its not the real way to develop apps on web.(single form architecture and viewstate). But I know that I can accomplish everything on MVC on webforms with a controlled architecture? Will it give a value in job market if I moved to ASP MVC?


How viable is it to switch stacks for setting up a startup

I am currently employed with a company for 2.5 years and I have been working with the .net stack for the entire duration mainly on the MVC framework. I _believe_ I have some cool ideas for a startup but I am not sure if I should continue in this stack or switch to some other stack like Ruby on Rails. The reason why I am consider this switch is due to the Infrastructure required to host a dot net application and scaling it successfully as compared to setting up a live running site on some other stack. I have a really good domain expertise in dot net at this moment but I believe it should be not so hard to move onto a new stack and adopt the best practices that I have picked up in the past two years. Let me know if I am missing something in the puzzle and if I am taking the right decision? Are there any complications of learning a new stack and building on it? Please guide me in the right direction.


Using a try-finally (without catch) vs enum-state validation

I have been reading the advice on this question about how an exception should be dealt with as close to where it is raised as possible. My dilemma on the best practice is whether one should use a try/catch/finally to return an enum _(or an int that represents a value, 0 for error, 1 for ok, 2 for warning etc, depending on the case)_ so that an answer is always in order, or should one let the exception go through so that the calling part would deal with it? From what I can gather, this might be different depending on the case, so the original advice seems odd. For example, on a web service, you would always want to return a state of course, so any exception has to be dealt with on the spot, but lets say inside a function that posts/gets some data via http, you would want the exception (for example in case of 404) to just pass through to the one that fired it. If you don't, you would have to create some way to inform the calling part of the quality of the outcome (error:404), as well as the outcome itself. Though it IS possible to try-catch the 404 exception inside the helper function that gets/posts the data, should you? Is it only I that use a smallint to denote states in the program (and document them appropriately of course), and then use this info for sanity validation purposes (everything ok/error handling) outside? **Update:** I was expecting a fatal/non-fatal exception for the main classification, but I didn't want to include this so as not to prejudice the answers. Let me clarify what the question is about: Handling the exceptions thrown, not throwing exceptions. What the desired effect is: Detect an error, and try to recover from it. If recovery isn't possible, provide the most meaningful feedback. Again, with the http get/post example, the question is, should you provide a new object that describes what happened to the original caller? If this helper was in a library you are using would you expect it to provide you with a status code for the operation, or would you include it in a try-catch block? If you are _designing_ it, would you provide a status code or throw an exception and let the upper level translate it to a status code/message instead? Synopsis: **How do you chose if a piece of code instead of producing an exception, returns a status code along with any results it may yield?**


Syncing chat on android device with web application

I am trying to make a chat application in android. Just a one on one chat. However I also want the chat to be synced with the web app that runs on the browser. I am confused about how to go about it. So I want my web app as well as the android app to be in sync. I have 2 things in mind. One,use metoerjs for frontend and php for backend connected with a mongodb. I am inclined towards metoerjs for front end because it seamlessly syncs with the mongodb object and is a good real time js library. This would require me hosting my php script on an apache server and the front end running on node. Is it possible to make http post requests to the meteor js server(and add stuff to my database) through my android device? If it is then I can do away with using php, and develop both the client and server side in javascript. Second, use some xmpp client to set up the chat on android.But I have no idea how am I supposed to connect it to my webserver. I am a complete beginner with server side scripting in javascript, noSQL databases and the xmpp protocol. So I would really appreciate if someone could point me in the right direction.


Optimizing sorting large amounts of text stored in a database

How would you store text information - in a relational database or maybe using NoSQL? The problem is that the text should be divided into various parts, each of which satisfies to some requirement, e.g. the same text should be contained in several "places". Is there another way to organize this? I have several books (each of them about 600 pages), which should be stored in a database, but there will be a mechanism which should sort the content of the books by some criteria. The criteria are complex, so I wonder if it is becoming a big problem. Would it help to store the same text in various "tables", each of which would satisfy a concrete "condition" Do I need to save the same text in various "tables", each of which satisfies a specific set of criteria?


How do software development methodologies fit in the field of consulting?

I work for a fairly small consulting company, roughly 100 employees, and I've been with them for about a year currently. This is my first job out of college. As a company we do not specialize in any specific technology, but my day-to-day usually consists of some sort of .NET programming, whether it be ASP.NET, custom SharePoint development, etc. Our projects generally consist of adding features to, or expanding, a client's existing code-base. Rarely we will build web applications from the ground up. Something that has been bothering me is the distinct lack of any sort of methodology or framework that helps us deliver quality solutions to clients. We do not conduct code reviews, the testing we do seems weak, technical direction seems lackluster. It seems that little effort is made to ensure the code the team commits to a project meets any sort of standard of extensibility and maintainability or adheres to any best practices for the given environment. From my experience thus far, leaving that responsibility solely up to the individual programmer yields some lackluster results especially when inexperienced members of the team are involved. I would like to know if this is business as usual in the consulting world. If you work at a consulting firm, I would like to hear about any techniques, processes, or approaches that are used to make sure the solution your team is developing avoids becoming a mess, all the while under the restriction that you are working on a client's existing code-base that you may not have complete control of. What can I do as a junior member of the team to promote a culture of producing better software?


Philosophy behind the memento pattern

I have been reading up on memento pattern from various sources of the internet. Differing information from different sources has left me in confusion regarding why this pattern is actually needed. The dofactory implementation says that the primary intention of this pattern is to restore the state of the system. Wiki says that the primary intention is to be **able** to restore the changes on the system. This gives a different impact - saying that it is possible for a system to have memento implementation with no need to restore. And that ability of restore is a feature of this. OODesign says that > It is sometimes necessary to capture the internal state of an object at some > point and have the ability to restore the object to that state later in > time. Such a case is useful in case of error or failure. So, my question is why exactly do we use this one? Is it to save previous states - or to promote encapsulation between the Caretaker and the Memento? Why is this type of encapsulation so important? Edit: For those visiting, check out this Implementation! **Edit** : I am working in implementing a memento solution to my problem. I will post another question regarding that and link that question to this one. Thanks all for responding with valuable suggestions! **Edit 3** : Here is the link to my sample implementation


Non-transactional Database and Integration Testing

One issue I think I am going to run into with my integration testing is having multiple tests accessing the same database. While this is not a problem now, I know we have multiple applications here that access the same database and I am just trying to think of a way to prevent this issue before it happens. An idea I have seen a lot is using transactions. In the start up you start a transaction and then in the teardown you rollback the transaction. This means that multiple tests accessing the same database tables and will not effect each other which is great. The issue I have is that in my case, 85-95% of the tables I am working with in MySQL are MyISAM which don't support transactions. Are there any ways to get around storage engines that don't support transaction but still allowing multiple test to access the same tables without them effecting each other? From what I hear, the ruby on rails testing framework uses transactions in this way, how do they get around this issue (or do they)?


How does Ruby, Python, PHP manage without Spring?

I write enterprise Java applications and web services at work (Spring, Hibernate, Maven, RESTEasy) and PHP (CakePHP) and Python (Django) for my side projects. While I do see the value that Inversion of Control, Aspect Oriented Programming etc. that Spring brings in, I am not sure how massive web applications that are not on the Java stack manage without a framework like Spring. So, do the developers just have to "put up with" tightly coupled components and other grievances that Spring eliminates or am I missing something? For those unfamiliar with Spring, the features we use the most are:   * Inversion of Control container: configuration of application components and lifecycle management of Java objects,   * Aspect-oriented programming: enables implementation of cross-cutting routines,   * Transaction management: unifies several transaction management APIs and coordinates transactions for Java objects.


Why we should (not) develop on a server via RDP

I have a client who is requesting that we develop their fairly small web application directly in their environment by RDP to the server that will host the app. They have had a contractor do this for a while and it has worked "fine" for them, so they are comfortable with that approach. The client's biggest concern at this point is cutting costs - they have a very tight budget. My manager does not seem to care or think that it makes a difference. However, I strongly do not agree with that practice. How best can I convince the client that it is bad practice to do things that way? I need to use "management" language, not developer language. I can think of a few advantages of developing locally (as a developer):   1. We can not guarantee code quality in the remote environment (why not?)   2. Internal team collaboration increases efficiency (how?)   3. Internally, we can take better advantage of source control (although that can also be installed on the server)   4. Internally, we can follow better quality control processes   5. With RDP, only one developer can work on project at a time   6. Developing locally increases a developer's efficiency (how? maybe because it is their comfort zone? maybe with multiple monitors? how does that benefit the client?) Unfortunately, these do not necessarily translate to something management appreciates (e.g. dollars and cents) Please help.


Why isn't there an html tag "field"?

There is a `<fieldset>` tag for a set of fields. Why isn't there a hierarchical child for fieldsets?               <form>         <fieldset>             <legend>Thin Sandwich Options</legend>             <field>                 Meat
                                              <input type="radio" name="meat" value="turkey" />Turkey                                              <input type="radio" name="meat" value="monkey" />Monkey

Pick one meat for the thin sandwich.
             </field>             <field>                 Cheese
                                              <input type="checkbox" name="cheese" value="chedder" />Cheddar                                              <input type="checkbox" name="cheese" value="swiss" />Swiss

Pick one meat for the thin sandwich.
             </field>         </fieldset>         <fieldset>             <legend>Beverage Options</legend>             <field>                 Carbonated
                                              <input type="radio" name="carbonated" value="coke" />Coke                                              <input type="radio" name="carbonated" value="mtn-dew" />Dew

Pick one beverage per combo.
             </field>             <field>                 Non Carbonated
                                              <input type="radio" name="non-carbonated" value="tea-sweet" />Tea (non sweetend)                                              <input type="radio" name="non-carbonated" value="tea" />Tea
             </field>         </fieldset>     </form>      http://jsfiddle.net/5dC8c/ I keep coming back to this question whenever I am working on my HTML form layouts. As MDN defines it: > The HTML `<fieldset>` element is used to group several controls as well as > labels () within a web form. I see a `<field>` element as grouping a single control (or set of radio buttons) with a single label and a description. The field tag would have some of the same attributes that the input tag has, readonly, required, etc. Why does bootstrap use the class 'form-group'? Why does Wufoo use li tags for each field? Enclosing related form elements into fields would add clarity. Every major front-end framework has some class or tag to differentiate each field. Why the heck don't we have a single HTML tag to bring some normality to form design? **Update:** added a better HTML example of the usage of a `<field>` tag.


How to indicate reliability when reporting availability of competencies

We have employees with competencies:               Pete      Welder               Carpenter     Melissa   Carpenter            Assume they both work 40 hours/week, and have not yet been assigned work.   We need to report the availability of these competencies, expressed in hours.   As far as I can see now, we can report this in two ways: Method A. When someone has multiple competencies, count them both.               Welder    40 hours     Carpenter 80 hours      Method B. When someone has multiple competencies, count an equal division of hours for each               Welder    20 hours     Carpenter 60 hours      Method A has our preference:   \- A good planner will know to plan the least available competency first. If 30 hours of welding is planned, we will be left with 10 _welder_ , 50 _carpenter_.   \- Method B has the disadvantage that the planner thinks he cannot plan the job when 30 hours of welding is required. However, if we report this **we would like to give an estimate of the reliability of the numbers for each competency** , i.e. how much are these over-reported? In my example A, would I say that _carpenter_ is 100% over-reported, or 50%, or maybe another number?   How would I calculate this for large numbers of competencies?   I'm sure we are not the first ones dealing with this, is there a 'usual' way of doing this in planning? Additionally:   \- Would there be an even better method than A or B?   \- Optionally, we also have an _preference order_ of competencies (like: use him/her in this order), Pete could be 1. _welder_ 2\. _carpenter_. Does this introduce new options?


Are the "practical" chapters at the end of the Siebel's PCL book supposed to be skipped during the first pass?

Just completed the first pass through Peter Siebel's Practical Common Lisp. I'm fairly comfortable with C#, Ruby, Java; The chapters that teach Lisp and the early 'practical' chapters were easy on my brain. However towards the end of the book, the practical chapters (on binary serialization, id3 parsing, web programming and the HTML generating DSL) seemed to be just out of reach - I recognized the primitives and methods being used ; but the means of combination left me flabbergasted. e.g. Given the specs, I couldn't sit down and write that code on my own.. I skipped some of them and strafed through the rest. Are there other who felt that there was a missing level between the first 22 chapters and the practicals ? Or is it just me ? Should I read the basics again? Or is there another book that will help me cross the chasm ?


Choosing a programming language allowing that affinities of the customer?

I would like to have some professional opinion about the programming language used for a project in a company. Let's explain me... In my company, the first argument to choose Java as the main language is its name and its popularity from the perspective of the customer. It appears that if you propose to develop the client's software in Python/Ruby/..., he is less convinced. I would like to know if you are experiencing this kind of situation and what you think about that ?


What makes one language any better than another when both are designed for the same goals?

I'm in the process of creating a grammar for a scripting language but as I'm working on it I started to wonder what makes a language good in the first place. I know the goals for my script but there are always 1000 different ways to go about doing things. Goals:   * Easy to use and understand (not my grandma could do it easy, but the secretary at the front desk could do it or the VP of marketing could do it type of easy)   * No user defined functions or subroutines.   * Its use would be in events of objects in a system similar to HyperCard. Conceptually I was thinking of a language like this:               set myVariable to 'Hello World'     set counter to 0     repeat 5 times with x     begin         set counter to counter add x     end     set myVariable to myVariable plus ' ' plus counter     popup myVariable          set text of label named 'label' to 'new text'     set color of label named 'label' to blue      The end result would popup a dialog with the contents `Hello World 15` it would also change the text of a label and make it blue. But I could do the same thing 1000 different ways. So what makes one language any better than another when both are designed for the same goals?


Whole Solution Complexity ... vs Development Complexity

I am generally a PHP Developer that deals in a few different MVC frameworks. I am being tempted (like most) to break out of my comfortable LAMP environment in pursuit of a "prettier" and "more simple" language, attached to frameworks that are becoming more and more popular. I agree with most arguments to switching to a (the) ruby framework or a python framework, and would trade out PHP for Python in the LAMP acronym any day of the week. But as I've found in trying to get started with these, it's not quite that simple... In my attempts to figure out the spaghetti of dependencies, versions, and install procedures, I've found that while final development time/simplicity is a benefit, in my mind it is almost overshadowed by the complexity of deployment... Especially being use to the copy/paste deployment to the ever numerous lamp hosting services. I am specifically speaking of   * Ruby on Rails   * Django (python) To those that work in these platforms, was your initial experience similar? if so how did you overcome it?


how to tell users to wait, becase page is loading

On my webpage, i have to generate some excel and pdf files but the user has to wait until the file is generated. the scenario is this: user press a link and waits until the files are generated and displayed as a links on the raports page. how can i 'tell' to the user to wait?


How to document/verify consistent layering?

I have recently moved to the dark side: I am now a CUSTOMER of software development -- mainly websites. With this new role comes new concerns. As a programmer i know how solid an application becomes when it is properly layered, and I want to use this knowledge in my new job. I don't want business logic in my presentation layer, and certainly not presentation stuff in my data layer. Thus, I want to be able to demand from my supllier that they document the level of layering, and how neat and consistent the layering is. The big question is: How is the level of layering documented to me as a customer, and is that a reasonable demmand for me to have, so I don't have to look in the code (I'm not supposed to do that anymore)?


A RESTful way to verify server state

I'm interested in building verifications into a REST service to help with service monitoring. For example, one could run assertions like `http://example.com/posts/verify?min-posts=5&since=1-hour-ago` which would respond with an error unless 5 new posts had been created in the past hour. Are there any existing services like this, or best practices? I'm particularly interested in a recommended error code for failed verifications, as I can't really see anything appropriate in the 4xx series. Errors like "Precondition Required" and "Internal Server Error" are more about the actual request or processing of it, than the meaning of it.


Should POCO domain classes contain collections?

The question title is not good, but I couldn't think of a way to word it better. I am used to develop using POCO classes in my projects, that is, domain objects contain absolutely no logic, only data. I am wondering which is the best approach when dealing with class relationships - to put a collection inside the class or to request it later. For example, consider we have an e-commerce application, that has Orders, and Items inside those Orders. So we could have (pseudo-code)               class Order     {          int id;          List<OrderItem> Items;     }          class OrderItem     {          Product product;          int quantity;     }      And then use it (1)               var o = LoadOrder(id);     foreach (var i in o.Items) {      ...or we could do:               class Order     {         int id;     }      And use it this way: (2)               var odr = LoadOrder(id);     var itms = LoadItemsOfOrder(odr);     foreach (var i in itms) {          .....      The first way is more compact and more "OOP-ish", but the second way gives more control on how and when items are requested, e.g. what if now I need to request only the items that have quantity > 3 ? And what if I don't use the Items collection at all (e.g. to display only a list of orders) - I will be doing unnecessary queries to the database. In my older, big projects I've gone with a hybrid approach - the domain classes are of the first flavor but there are various "load" methods, like "LoadOrder" and "LoadOrderWithItems" or "FillOrderObject". Now I am working on a small, toy project, no customers and crazy deadlines and got time to think on these issues. I tried searching the web but it is very hard to find a POCO answer not related to Entity Framework. (I am not working in .net this time, but would like to apply these concepts.) **Question** : is there a method which is clearly _better_ than the other, or both are valid and "it depends" on my project, if I am aiming for performance or for code clarity and maintainability?.