State pattern vs Inheritance

In the following image for the **State Pattern** from Applying Domain-Driven Design and Patterns: With Examples in C# and .NET ![enter image description here](http://i.stack.imgur.com/UCMr1.png) I'm trying to persist the `SalesOrder` entity into the database. Normally I would have a `salesOrder` table in my database with a field `currentState` pointing to the current state of the entity. This implementation is fine as there is a **single** entity and its states only contain different behavior. **However** , what if I had to track other properties for the different states? Examples:   * When a SalesOrder is cancelled I need to track the cancelled `quantity`,`cancellationReason`, `cancelledBy`, `cancellationDate`.   * When a SalesOrder is Refunded I need to track `refundQuantity`, `refundPrice`, `refundFee`. So basically it is like I have a `CancelledSalesOrder` and `RefundedSalesOrder` entities with additional attributes. Same can be said for the other states as well. So my problem now is that I will have to change the design from using the state pattern into using inheritance. However, inheritance doesn't allow my to dynamically change my state at run time (the problem which the state diagram solves initially). so my questions:   1. Does the state pattern fail when an entity in each state has additional attributes? what's the alternative?   2. How should I persist my entities in this case? Single table inheritance? table per class? table per concrete class?   3. If I have to maintain some attributes from a former state (Refund a Shipped order, but don't delete the Shipping address from Shipped state ), how would one approach this problem?   4. How do you keep track of the order of which the states occurred?


Template for writing requirements/specs for a WCF service interface

I need to write requirements/specs for a WCF service interface between our system and a third-party BizTalk server. I'm not quite sure how to do this, so I'm looking for a template. I guess I should at the very least define the interface itself, authentication policy and error handling. Any resources regarding documenting WCF/SOA requirements would be appreciated.


Rails data model - best practices question

I'm writing a Rails cookbook app as a learning exercise. I've created a table for Recipes which holds info for the recipe (name, author, etc...). I also have a table for Ingredients which will be a master ingredients list, and then a table in-between which holds info specific to that recipe/ingredient combo (for example, the ingredient table would have a listing for Onion, the in- between table would have the amount, technique (slice, chop, etc...) and whatever else for a particular recipe). Anyway - this is all working fine, but as I add ingredients to the table, I realize there are quite a few categories of ingredients (Spices, Vegetables, Meats, Fruits, etc...) and they have different bits of info I want to record about them. For example, meats and veggies might have the technique field (chop, dice, mince, etc) but spices might have a "spice_type" field to record if it is dry or fresh. Meats might require a "doneness" field (well-done, rare, etc..) while fruits do not... So, the crux of my question - is it better to have one large ingredients table with fields for every category, only using the ones I need for a particular row, or is it better to create five tables, one for each type of ingredient? I started coding it as separate tables, as it seemed proper since I am holding different fields for each type, but then I realized how much work it will be to code 5 x models, 5 x controllers, 5 x views, etc... SO, better to stuff it all in one table (after all, they are all ingredients!), have each record just leave the non-applicable fields nil, and make my views/etc.. dynamic to adapt to whatever type of ingredient is being worked with (essentially hiding or displaying the appropriate fields)? I hope this makes sense, whenever I get on this site I turn into a rambling fool ;) Thanks for the help **Update:** I was making some beer yesterday and thinking about my beer recipes along the lines of my cookbook app, and realized the beer recipes are a much better example of what I am trying to figure out, so below is the same question posed in a different paradigm: In my beer recipes, I have three types of Ingredients. There is malt, hops, and yeast. They are common in the sense that they are all ingredients, and will all have a few common attributes such as Name, Brand, and Price. However, there are specific attributes to each that the others don't share - for example, Malt has an SRM attribute (essentially color), while Hops has an AA (alpha acids) attribute, and yeast has a Flocculation attribute. So do I go STI and lay out a table like this? id, type, name, brand, price, srm, aa, flocculation Additionally, the "in-between" table will contain different info on each. All ingredients will have an Amount attribute, but hops will have a BoilTime and malts will have a MashTemp, etc... So do I use one table with STI and one "in-between" table to join? Do I make the "in-between" table STI as well? I have a lot of reading to do! :)


Why is sem_post pthread_mutex_lock protected while sem_wait is not?

All the pthread semaphore examples I have seen protect the sem_post call with a pthread_mutex_lock, but the sem_wait is left unprotected! It seems to me that sem_wait also should be protected in some fashion, though being a blocking call, it would lock the mutex permanently! What am I missing?


How does SCRUM manage different projects about the same product with different teams?

It happens in my workplace that when a product is finished, and just some weeks before it is released and the project is closed, some business considerations remain about features that are wanted for future versions. A revision is made about the features when the project is closed, and the clients and stakeholders, along with the team decided, for example, that they want to open a new project that has as objective to create a new version of the project that includes some new requirements. Now this is a typical case, but it happened before that the team that made the product, now works for another company and a new fresh team is formed to do this project. I know Agile aims to give value to interactions rather than documentation, but how does Agile manages this? How do you continue a new project to extend an already existing product without documentation?


Placing of copyright notice in source code

I'm about to release a project of mine that I'm really proud of under the GNU GPL and I have some questions:   1. Should one attach a copyright notice on each and every source code file from their project? I think it's a bit ridiculous to claim copyright on a 3 line abstract class. Should I attach a copyright notice only to really important source code files?   2. Can I not attach the whole standard thingy? Because it's big and bulky and gets in the way... If so, is the variant below ok/enough?  _Copyright year firstname lastname. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation._


When is it a good time to reason about performance in Haskell?

Simon Peyton Jones himself recognizes that reasoning about performance in Haskell is hard due to the non strict semantics. I have yet to write a significant project in haskell so I wonder: can I reason about performance only at the beginning of a project (when choosing basic data structures & IO library) and whenever a problem arise, deal with it with the profiler? To put it differently, is it possible (ie not too painful) to postpone dealing with performance when you have performance issues, or do you have to learn to predict how GHC will run your code (for exemple: infer what the strictness analyser will decide)?


What are examples of small/medium and large applications?

My question is associated with the accepted answer to this question. It says that the language should be based on the fact whther the application is small,medium or large. What popular applications would you put in each category? And why? (is it the size of the codebase/number of simultaneous users etc..) * * * Thanks for all your answers. But in your examples I didn't see any web applications.Can you include some?


Naming convention for iOS

I am learning Objective-C and iOS development and not sure what proper naming convention should be used. I understand how to use the label aspect of Obj-C methods but not the proper way to name each label. What is the best practice for naming methods, properties, objects, outlets, and actions? Also,   Should different naming conventions be used between Obj-C code and C code? And if so what differences is there?


Reading graph inputs for a programming puzzle and then solving it

I just took a programming competition question and I absolutely bombed it. I had trouble right at the beginning itself from reading the input set. The question was basically a variant of this puzzle http://codercharts.com/puzzle/evacuation-plan but also had an hour component in the first line(say 3 hours after start of evacuation). It reads like this This puzzle is a tribute to all the people who suffered from the earthquake in Japan. The goal of this puzzle is, given a network of road and locations, to determine the maximum number of people that can be evacuated. The people must be evacuated from evacuation points to rescue points. The list of road and the number of people they can carry per hour is provided. Input Specifications Your program must accept one and only one command line argument: the input file. The input file is formatted as follows: the first line contains 4 integers n r s t n is the number of locations (each location is given by a number from 0 to n-1) r is the number of roads s is the number of locations to be evacuated from (evacuation points) t is the number of locations where people must be evacuated to (rescue points) the second line contains s integers giving the locations of the evacuation points the third line contains t integers giving the locations of the rescue points the r following lines contain to the road definitions. Each road is defined by 3 integers l1 l2 width where l1 and l2 are the locations connected by the road (roads are one-way) and width is the number of people per hour that can fit on the road Now look at the sample input set               5 5 1 2 3          0          3 4          0 1 10          0 2 5          1 2 4          1 3 5          2 4 10      The 3 in the first line is the additional component and is defined as the number of hours since the resuce has started which is 3 in this case. Now my solution was to use Dijisktras algorithm to find the shortest path between each of the rescue and evac nodes. Now my problem started with how to read the input set. I read the first line in python and stored the values in variables. But then I did not know how to store the values of the distance between the nodes and what DS to use and how to input it to say a standard implementation of dijikstras algorithm. So my question is two fold 1.) How do I take the input of such problems? - I have faced this problem in quite a few competitions recently and I hope I can get a simple code snippet or an explanation in java or python to read the data input set in such a way that I can input it as a graph to graph algorithms like dijikstra and floyd/warshall. Also a solution to the above problem would also help. 2.) How to solve this puzzle? My algorithm was: Find shortest path between evac points (in the above example it is 14 from 0 to 3) Multiply it by number of hours to get maximal number of saves Also the answer given for the variant for the input set was 24 which I dont understand. Can someone explain that also. UPDATE: I get how the answer is 14 in the given problem link - it seems to be just the shortest path between node 0 and 3. But with the 3 hour component how is the answer 24 UPDATE I get how it is 24 - its a complete graph traversal at every hour and this is how I solve it               Hour 1     Node 0 to Node 1 - 10 people     Node 0 to Node 2- 5 people     TotalRescueCount=0     Node 1=10     Node 2= 5          Hour 2     Node 1 to Node 3 = 5(Rescued)     Node 2 to Node 4 = 5(Rescued)     Node 0 to Node 1 = 10     Node 0 to Node 2 = 5      Node 1 to Node 2 = 4     TotalRescueCount = 10     Node 1 = 10     Node 2= 5+4 = 9          Hour 3     Node 1 to Node 3 = 5(Rescued)     Node 2 to Node 4 = 5+4 = 9(Rescued)     TotalRescueCount = 9+5+10 = 24      It hard enough for this case , for multiple evac and rescue points how in the world would I write a pgm for this ?


Importance of uniformity of development architecture across the team

If some developers still use a 32 bit 'Windows XP' and others use a '64 bit Windows 7', would it be advisable for the entire team to work with 32 bit development tools even if their OS is 64 bit? Are there any problems that could happen if uniformity is not followed?


I would like to learn PHP for web development but have been drawn back because of comments like the following*:   * PHP is good but generates spaghetti code   * PHP is nice but Python is marriage material   * PHP lacks stuff that you get in other languages like C# or Java But for PHP5 I have seen some promising comments. So, my question is: How does PHP5 fare with earlier versions of the language and is it good enough now to learn for web development. * Comments are just for reference not to incite a flame war. No comparison of PHP with other languages is asked for here. Please comment just on PHP5 and how it compares with earlier versions.


API Client Design

I'm designing a client to the Tomtom WEBFLEET.connect API in PHP. (You can read more about the API through the full documentation here: https://uk.support.business.tomtom.com/ci/fattach/get/488198/1396263217/redirect/1/filename/WEBFLEET.connect- en-1.19.1.pdf) The API provides a CSV over HTTP(S) interface (JSON and SOAP are also available but their JSON interface has a couple of issues I've noticed at present). I am using the CSV method of interacting, which is a little unorthodox but does work. I am designing my PHP classes to particularly be compliant with the Single Responsibility Principle, Open-Closed Principle and the Dependency Inversion Principle. Writing this API client library is as much as personal programming exercise as I'm trying to better my OOP and class design principles. I've included a brief class diagram below. Please excuse the verbose names, this is of course expressing the PHP namespaces. I would be most appreciative of some comments regarding:   * General class design thoughts and critique (e.g. compliance with SRP, etc.)   * Whether distinct objects for each type of Request and Response are recommended, as I have proposed below (this mirrors each API method).   * How the public API to external calling code should appear. For example, should I have a 'factory' class return an instance of the chosen Transport to the calling code? Or should a central class (similar to the command pattern) hold an instance of the transport class and offload requests to it? ![UML Class Diagram](http://i.stack.imgur.com/HzFIC.jpg) Larger image URL: http://i.imgur.com/kneY9GE.jpg


Dealing with a large pull request

I'm currently working on a project with a team that's using a git workflow. It's fairly simple, master should be in a deployable state and branches are used to create features and hotfixes. Whenever we have a feature or bugfix completed and tested then we move that over to master as soon as we can. The idea is that branches should be as small as possible to make it easier to merge them back into master. We have a policy that any code pushed to master branch should be in a deployable state and pass the tests. We have got a situation where one of the developers has done a lot of work (a few months worth) on a single branch and this branch hasn't been merged back into the master yet. There's now a few separate features and a bunch of commits on this branch, essentially this branch really should have been merged back in a few times already but so far hasn't been. Most of the code is in a good state with unit tests that could be merged back into master but the most recent changes should certainly not be as they are not completed and aren't tested. What is the best way to deal with such a situation where one branch is really far away from the others? What ways can we avoid branches getting a very large number of commits away from master in the future?


What are the perks and drawbacks of using html templates versus building the html in-code

As far as I can see there are two ways of building a html page: "inside" the language (I'll call it _building_ for lack of a better name) or outside the language (using templates). Let me explain a bit what I mean by this before I jump to the questions. ### Building One way is to build the html page "inside" the language you are using, using preferably in-language constructs (not just by concatenating strings), and converting these constructs to html in one last step. A really good example of this is Clojure's hiccup library, which uses the Clojure maps and vectors to represent the html. This allows one to use the full power of the language one's working in to manipulate these structures. ### Templating The second way is to write the html separately from the main program and use some kind of template DSL to insert logic into the templates. The hamlet package for Haskell is an example of this. **Now my question is** : what are other advantages and disadvantages of both approaches? * * * I'd love to get more acquainted with these concepts so pointers to articles etc. are more than welcome. Also please inform me if there is another approach I didn't think of. * * * ## Summary of answers so far ### Pro templating   * It's easier to separate the view from the rest of the code. The code will be easier to maintain and you avoid mixing business logic with the rest of your code.   * This approach generally is much more accessible to people with less technical skills. ### Con templating _(none so far)_ ### Pro building   * Functional languages, make it easy to write declarative code natively so a template language is not required.   * You can get all the power and flexibility of your programming language, and still get the benefits of a declarative syntax. ### Con building   * Designers/clients are bad at your preferred logic language.   * It still boils down to hard-coding the page into codem just that it is not separate template code.   * Has more power, that could be used inappropriately. You have to take extra care   to separate view code and business logic.   * In ideal cases it is faster though.


What are the typical applications of Lisp macros?

I am trying to learn some LISP and I have read a lot about the importance of LISP macros so I would like to get some working experience with them. Can you suggest a practical application area that would allow me to use macros to solve a real-world problem, and to understand the usefulness of this programming construct? **NOTE** This is not a generic **what project should I do next** question. I am interested to understand which kinds of problems are typically solved by means of LISP macros. E.g., are they good for implementing abstract data types? Why was this construct added to the language? What kinds of problems does it solve that cannot be solved by means of simple functions?


Resharper - Benefits

Having seen a few mentions about Resharper on this site and on SO, I thought I would take a look. There seems to be a hell of a lot of documentation on their website, so I was just wondering, in a snapshot, what benefits it brings and what are the main reasons people use it?


Babysitting your Continuous Integration System

One of my roles in my team is _the build person_. I am responsible for maintaining/updating our build scripts and making sure we are building 'smoothly' on the continuous integration server. I usually do not mind this job, though often it feels like I am constantly babysitting the CI server. This job can be annoying at times because if the build breaks I have to drop the story I am working on and investigate the build failure. Build failures happen daily on our team. Sometimes developers simply do not build locally before committing so tests fail on the CI server. In this situation I like to quickly get to the person who had the 'bad commit' so the build does not stay broken too long. Sometimes (a lot less frequently) a strange condition exists on the CI server that needs to be debugged. I know that many mature teams use Continuous Integration but there is not a lot of material out there about good practices. Do my problems point out that our continuous integration is not very mature or is this simply part of the job? What are some good practices to follow? What are the characteristics of _mature continuous integration_? **Update** Instead of answering some comments I am going to make an update instead. We have a single, simple command that does exactly what the build server will do when building the app. It will compile, run all unit/integration and some quick UI based tests. Reading everyone's answers, it feels we might have two major problems.   1. CI Server not complaining loud enough when a build fails.    2. Developers do not feel like its everyone's responsibility to make sure their commit goes through successfully. What makes things harder in my team is that we have a large team (10+ developers) AND we have a couple of off-shore team members committing when we are not even at work. Because the team is large and we established that frequent, small commits are preferred, we sometimes have really a lot of activity in a day.


In GSL, why do some functions take a "workspace" argument?

In certain functions in GSL (GNU Scientific Library), some functions take a "workspace" environment as an argument. For example, `gsl_poly_dd_taylor` from this page. Why? Wouldn't it be easier for the function to allocate its own memory, or at least the same difficulty? I suppose that this allows the caller to specify _where_ the function works, but I don't see how it helps.


Most human-friendly way to order class method definitions?

In any given class definition, I've seen the method definitions ordered in various ways: alphabetical, chronological based on most common usage, alphabetical grouped by visibility, alphabetical with getters and setters grouped together, etc. When I start writing a new class, I tend to just type everything in, then reorder when I'm done writing the entire class. On that note, I've got three questions:   1. Does order matter?   2. Is there a "best" order?   3. I'm guessing there's not, so what are the pros and cons of the different ordering strategies?


Applying DDD principles in a RESTish web service

I am developing an RESTish web service. I think I got the idea of the difference between aggregation and composition. Aggregation does not enforce lifecycle/scope on the objects it _references_. Composition does enforce lifecycle/scope on the objects it _contain/own_. If I delete a composite object then all the objects it contain/own are deleted as well, while the deleting an aggregate root does not delete referenced objects. **1)** If it is true that deleting aggregate roots does not necessary delete referenced objects, what sense does it make to not have a repository for the references objects? Or are aggregate roots as a term referring to what is known as composite object? **2)** When you create an web service you will have multiple endpoints, in my case I have one entity `Book` and another named `Comment`. It does not make sense to leave the comments in my application if the book is deleted. Therefore, book is a composite object. I guess I should **not** have a repository for comments since that would break the enforcement of lifecycle and rules that the book class may have. However I have URL such as (examples only):               GET /books/1/comments     POST /books/1/comments      Now, if I do not have a repository for comments, does that mean I have to load the book object and then return the referenced comments? Am I allowed to return a list of Comment entities from the BookRepository, does that make sense? The repository for Book may eventually become rather big with all sorts of methods. Am I allowed to write JPQL (JPA queries) that targets comments and not books inside the repository? What about pagination and filtering of comments. When adding a new comment triggered by the POST endpoint, do you need to load the book, add the comment to the book, and then update the whole book object? What I am currently doing is having a own CommentRepository, even though the comments are deleted with the book. I could need some direction on how to do it correct. Since you are exposing not only root objects in RESTish services I wonder how to handle this at the backend. I am using Hibernate and Spring.


Icons for my program

I'm developing a simple text editor, just to practice a little bit. I'm developing it under Linux but since I am using Qt as GUI Framework I can easily compile this on a Windows or Mac with the same code (in other words, it's cross-platform). Qt offers a function `QIcon::fromTheme()`. This function allows me to get the standard Icon for e.g. the _New Document_ Icon and use it for whatever I want. These Icons are sadly only available on Linux. However, I wrote a simple function to save these icons as PNG files in different formats (16x16 up to 1024x1024) so that I can use these on a Windows as well. Now my question, is it even legal to use these images on windows as well? And would you find it strange if such icons appear in a windows program? Because Linux has a whole different style than windows... Same thing with OS X'. The _New Document_ Icon for example would look similar to this:   http://findicons.com/files/icons/2455/web_icons/48/empty_document_new.png


We need a custom strategy for collecting unhandled application exceptions. What are our options?

## "Unhandled exception" term In .NET Framework, unhandled exceptions are the exceptions which were not handled by the application itself, and result in a crash. In a case of a desktop application, it means that a window similar to this one is displayed: ![enter image description here](http://i.stack.imgur.com/96et2.png) For a web application, it mostly means an HTTP 500. Under unhandled exceptions, I also include ones which are "handled globally", i.e., in a case of a desktop applications, the global handling which consists of displaying a custom window instead of the Windows default one. ## Context When I work as a freelancer, I use my own in-house solution to gather unhandled exceptions from different sources (web apps and desktop apps). The gathered results are then displayed on a monitoring panel in real time as well as collected for future analysis (to be linked with a bug tracking software, etc.) Currently, I work in a company where I wouldn't be able to use my in-house solution to collect the exceptions (one of the reasons being that they won't accept to send all the exception messages to my servers). This company doesn't have any precise strategy for collecting unhandled exceptions. The only solution which was used before is both rudimentary and out of question: it consists of sending every exception by e-mail. This means that for the new product I'm working on, we should develop a custom strategy for collecting unhandled exceptions. ## Question I can always do by hand the part which will save the exceptions to the database or a log and the part which will load them from the database, a log or Windows Events. I would like to avoid reinventing the wheel and use something which is already commonly used. What are my choices? How are unhandled exceptions usually collected and processed later? By the way:   * Are there any libraries which help collecting those exceptions?   * Are there any software products which help analyzing those exceptions?


Which concepts are pertinent to plan a “end-user documentation” strategy?

I am writing a lot of software and I feel that writing good documentation is very difficult. Since I am not aware of any structured theory about software documentation I started to organise my knowledge in this field and hope that doing this will help me to break down information in sensible units and organise documentation efficiently. First, I would like to make a complete list of relevant concepts, that I will investigate in other questions. Which concepts are useful or relevant when describing user documentation? How does these concepts interact with each other? Is there any methodology I can use to analyse my software and devise a pertinent documentation strategy? I identified the following concepts:   * _Information categories_ like recipes (“how do I…?”), _references_ (like UNIX man pages) or _expert knowledge_.   * _User role_ like normal user, power user, system administrator and any other roles that the system defines like security officer, data officer, etc.   * _Medium_ like a hardcopy manual, contextual help, editable wiki. These concepts interact one with the other and lead to a variety of questions: When is it useful to write a handbook for each role? What should go in hard copies and what in the on-line reference? When is it useful to run a wiki gathering “recipes”? With these examples, I hope I could provide a useful explanations of what I understand under “concept” and “interaction” in my questions.


Presenting agile estimates for Pivotal Tracker project

I've been developing for 6-7 years but never in a particularly agile way. With the latest project I'm trying to make our development process more professional, and more agile. We're using Pivotal Tracker to track the project and have gathered some pretty well thought out stories. We're also trying to keep some of our (Prince2/Waterfall mindset) project managers happy. So far I've got them to accept that   * requirements always change   * priorities always change   * some of the requirements won't be delivered if you fix the time scale    * you should fix the time scale   * short sprints and regular review is good However they still feel like they need to get a better grip of roughly how much will be delivered within a certain time. I've come up with a spreadsheet to demonstrate what we might expect to get done in a range of 4 different timescales. ![Estimates Example](http://i.stack.imgur.com/VbHr9.jpg) Questions   * Are we setting ourselves up to fail   * Are there better ways to do this


Listening For and Raising Events in the BLL

I'm working on a WinForms .Net Recording App and I have a RecordingMgr in my BLL to listen for new events captured by another class. I want to display the events in my UI and I'm stuck as to what's the **best** way to do this. I can think of a few scenarios to handle this but all of them seem sub-optimal:   1. Listen for and handle Recorded Events in both the UI and in the RecordingMgr   2. After receiving the event in the RecordingMgr, raise it again so that the UI can pick it up   3. Create a variable in RecordingMgr (e.g., a BindingList) that the UI can bind to and update it when an Event is received   4. Ditch the RecordingMgr and just put the event recording logic in the UI What's the best approach? Something above or something else?


Boolean-Integer Typecasting to Replace Conditional

When choosing a value based off of 2 boolean values in this format               var foo:int;          if (X){         foo = 50;     } else if (Y){         foo = -50;     } else {         foo = 0;     }      I discovered that I can condense this down by typecasting the boolean operations to integers, and mathing it up a bit like so:               var foo:int;          foo = ( int (X) - int(!X && Y) ) * 50;     // int() typecasts a boolean argument to an int of 1 if true, 0 if false.      Here are my questions:   1. Is this approach less resource intensive?   2. Is this approach readable to you?   3. Is assigning values in this way common?   4. If 1 is true then in your opinion, does the performance increase justify the less readable nature of this approach? This situation arose in ActionScript 3.0, but I am interested in answers from all languages, and from a best practice perspective.


UML activity diagram: How to end activity after Event Signal Action?

To my knowledge, event signal actions are not allowed to have output control flow, so how can I model the end of an activity after a event signal action? The same issue arises for accept event actions and activity start nodes.


Does this Decorator implementation violate the Liskov Substitution Principle?

Please consider the following implementation of the Decorator design pattern: `WordBank` objects store strings and return them to the client through the method `getWords()`. The decorator class, `WordSorter`, is a subclass of `WordBank` (as in the Decorator pattern). However it's implementation of `getWords()` sorts some of the strings and removes them, before returning the array to the client. For example a `WordSorter` might delete all of the strings in the bank that start with letter 'a', and only after that return the array to the client. Does this violate the Liskov Substitution Principle? Since some implementations of `WordBank` return strings while others first sort through the strings and only return some of them, I'm not sure if it's safe to say that a `WordSorter` can be used anywhere any other `WordBank` is used. Or am I understanding this principle wrong? ![enter image description here](http://i.stack.imgur.com/Zafoi.png)


How does one generate challenging different puzzles like the one in AirLock android game

here's the link of the app: https://play.google.com/store/apps/details?id=com.iatll.airlock I had studied AI in the final year of b.tech cs programme, and i do remember some algorithm of generating and solving the 8 puzzle game; we had to implement it in Prolog (tough times) But I'm not sure if the above mentioned app uses that same algorithm. Where do I need to look to create a puzzle game like that? They seriously couldn't have designed each level by hand right? Had to be computer generated. How can I so that? pardon me for not formatting, I'm on a mobile device.


ActionScript and Python

I am currently using VB.net 2010 and WPF 4 to create an application, but the further I learn it, the more I realize that the two programming languages may not meet my needs, especially where I have to migrate a version to a web-based Silverlight platform. With this in mind, I'm thinking of dumping the Microsoft programming languages all together before I get further into this project, and build this entire thing over again in a cross-platform language. This brings me to my question: I need the graphic capabilities of WPF, which I know is in the Flash platform, but I also need a language I can migrate my VERY complex VB.net core code into; thus, I'm thinking using Python. Are these two languages capable of working side by side? Alternatively, can I convert all my Vb.net code into ActionScript, instead of using two languages?   Is there another alternative to consider? Open source is the best, though I know ActionScript isn't, by any means open source. This is a strictly commercial project. Thank you!


How quickly, and how severely, should one sound the alarm when things look suspicious?

I presently have the task of baby-sitting a business critical batch ETL system, querying the database of this system every morning for inconsistencies, and rerunning jobs that have failed. I am not the original designer of the system or of the database, but have made several changes to both, and am reasonably comfortable with the codebase and the data model. The system has a reputation for being unreliable. Improvements have been made, but we are still a long way from hitting the targets we need to hit. This has led to trust issues for both the system and the team involved. Hence, the system now has a baby-sitter who makes sure it behaved well every morning while we work on hardening it up. With this in mind, I have come up against a dilemma that my team is split on. Whenever the system shows inconsistencies or failed runs, how rapidly and how severely should we sound the alarm? Here are the factors that have gone into the discussion thus far:   * If we do not know what is causing a symptom, but the symptom looks severe, do we hold off on sounding the alarm, or sound the alarm with a lesser severity until we know the cause and discover it really is that severe?   * Say we know the cause of something causing a symptom, and the symptom is severe. We have a strategy to mitigate that symptom, but the solution has a possibility of one or more failures before a success, and will nevertheless take time to implement. Do we hold off on sounding the severe alarm until we complete the mitigation steps, and still see the data going sideways?   * Say we know the cause of something causing a symptom, but the cause is out of our control, and we will not be able to mitigate the symptom until the cause is rectified by a third-party. Does this deserve the same severity of alarm as if the data loss were the responsibility of our code.   * If we sound false alarms too often, we run the risk of losing even more trust, because now we seem incompetent about the failure modes of our system. Is it worth delaying alarms, or tempering their severity, to avoid losing trust in our ability to know when and how our system is breaking? Is following up on high severity alarms to lessen the severity level enough mitigation, or has the damage already been done when the severe alarm goes out? The reason I ask this is because I sounded what turned out to be a false alarm this morning, due to some data that looked initially to be way out of what I expected. Further research demonstrated that it was just a run against unusual data, and so the inconsistency I saw was to be expected. Along with this, I had to go back and rerun a few things that failed, and had to wait for these to finish before my data consistency checks would mean anything at all. Another member of my team called me on this, and made the point that I should not have sounded the alarm, and should've instead either said nothing until I was certain, or reported a less severe status until I was certain that the data was in a severely compromised state and that it was our responsibility for it being that way. By doing so, I am not helping us restore trust. So, with this in mind, I'd like to ask the following questions: **when would you sound the alarms, and at what severity** , for batch job issues like the one I describe above, knowing that it has a history of problems? Also, **are we focussing on the wrong things in building back trust by trying to assure we send off alarms as little as possible**?


Is Domain Driven Design useful / productive for not so complex domains?

When assessing a potential project at work, I suggested that it might be advantageous to use a domain driven design approach to its object model. The project does not have an excessively complex domain, so my coworker threw this at me: > It has been said, that DDD is favorable in instances where there is a > complex domain model (“...It applies whenever we are operating in a complex, > intricate domain” Eric Evans). What I'm lost on is - how you define the complexity of a domain? Can it be defined by the number of aggregate roots in the domain model? Is the complexity of a domain in the interaction of objects? The domain that we are assessing is related online publishing and content management.


Where to start to learn C/C++ Embedded Linux Programming

I'm an experienced software engineer and an advanced Linux user. I already know C and C++. I've developed C applications on Unix in the past and C++ (mostly on Windows). I would like to start to learn how to program on embedded Linux systems. I'm particularly interested by the ARM plate-form and the Beagle Board. I would like to learn how to do low level programming in C/C++ (device drivers, interfacing with BeagleBoard peripherals, compiling customized kernels, etc). Could you point me to the best (free or not too expensive) ressources on the Internet? The best beginner books to learn to program C/C++ on Linux for ARM?


What is programming like in the Japanese language?

Is the code written in Japanese? Are filenames in English? What about like a C preprocessor? Is that still in English? Are comments in Japanese? Examples would be nice too.


Saving Multiple Sizes of Images

We have lots of user-generated images on our site. When users upload their images, we only store the original. However, depending on the page, we show different sizes of those images (small, medium, large, original). Is it necessary to store all sizes of these images or is there a better way? Currently, we are resizing them with CSS but this is really slow.


Header comment format

I realize that the "header comment" format varies from programmer to programmer, but what would be an example of a "good" header comment?


Has anyone collated a comprehensive list of all the prototype-programming style javascript work?

I'm looking for a comprehensive (or as close as possible) list of all the prototype-programming style javascript work done to date. Does anyone know of such a list somewhere, or have the knowledge to compile it somewhere and then reference it here?


Can you explain me why multiple threading need lock?

Assume these threads run in single core cpu. As a cpu only run one instruction in one cycle. That is said, even thought they share the cpu resource. but the computer ensure that one time one instruction. So is the lock un-necessary for multiplethreading?


Estimated errors in implementation comparison

I've been working on improving an existing library to be more maintainable after trying to implement a feature I wanted and found the code to be hard to alter. The library is a node.js grunt plugin called grunt-contrib-jshint and my implementation is in a repo called grunt-jshint-bfs. I've run a code analysis tool called plato that generates a source analysis report that includes metrics line total/average lines of code, maintainability and estimated errors in an effort to compare the code bases for code quality purposes. The trouble I'm having is comparing the estimated errors between the two projects, since one has 2 files and the other has many more files it would seem that the exposure to errors would increase, or am I reading that wrong? Here is a link to my repo's report and the grunt-contrib-jshint report for comparison.


How to implement an algorithm out-of-core?

I want to implement a parallel clustering algorithm "out-of-core" in CUDA. My CPU has **12GB** of RAM and GPU has **4GB** of it. What I want is that the entire dataset should be on the disk, and I can pick blocks of data from it, put the blocks on CPU memory, pass them to the GPU, process it there and store the result back on disk. The step complexity of the original (in-memory) algorithm is **O(logN)** , N-> no. of data points. For the external memory algorithm, suppose M points can fit in the memory at once, then according to me, the running should be               (N/M)*(logM)      (N/M) -> equals the number of such sets of points that will have to be put in memory and during each pass, logM time to process it. How does this running time relate to the I/O time between disk and memory, i.e., have I already considered the I/O time by using (N/M) or am I leaving something out? Is this analysis correct, or do I need to know more about Input/Output to implement an algorithm using external memory?


How to deal with hints/tutorial mode?

Currently I'm working on an basic application that has a 'tutorial mode'. Initially hints (bubbles with text) will be displayed above various ui elements, explaining how they work. Currently I have a main view which contains a hint object that can be updated (position, text, etc.) and I'm dispatching update events from the various views that need to display a hint. In most cases when the user click a hint, it disappears, but there are a few situations when the user must perform another action(like dragging-dropping an element, clicking another,etc.) to progress. Phew, that's the background in a nutshell. My main question is: Should there be dispatching events from various views and handle the hints centrally or should hints only be handled locally within each view ? What's the recommended approach ?


I want to program, but I can't find the time if I want to maintain my grades

I'm a high school senior, and I'm applying for various colleges. Among them, Stony Brook, which I understand has a very good CS program. My grades are good, so I'm not concerned about getting into college; however, I _do_ want to get into Computer Science Honors. The Honors courses are smaller, and the core sequence is two courses rather than three (though since I'm in AP Computer Science, which I find to be a joke, I don't really benefit from the compressed lessons). However, they want a 93 GPA (amongst some great SAT scores that I already have), and I'm at a 93.24. I want to maintain this so I can get into the program and enjoy the smaller class sizes. Great, except that the studying I do in high school (three AP courses, including CS) eats heavily into the time I'd like to spend programming. If I had zero homework after school, or even no school, then I would jump on my computer immediately and continue this one program I'm working on, which is ironically something that outputs the courses I want to take in college in a neat and formatted HTML file. That's why I can't wait to get to college. I did the math, and on average I'd be in class much less in college than in high school, freeing me up to program (which I'd be doing a lot of anyway). Of course, I do make time in the evenings to relax so I can maintain sanity and sleep; but by then, it's close to bedtime, and I'm not as "on the ball" as I'd like to be, especially since I try to get to bed by 11 (maybe midnight). Weekends seem to be a theoretically good time to program, if I don't have homework, but why limit myself to two days of the week? I might also be good for mornings, but if I'm sitting through a Forensic Science lecture then how will I know? I do have around six months of independent C++ studying under my belt, as well as some Processing. You can see a bit more, plus two projects, on my site; obviously, I give a damn about making cool things, that's not the issue. Yes, I do want to make games, thanks for guessing, but that will come later on once I have some experience under my belt. I also have a study hall in school, but this may not actually be the best time for me to program; my school actually gives computers to its students, but does not allow them to bring their own from home. My development environment is there, but not here, and shifting code back and forth really breaks the flow and makes things difficult, in my opinion. Also, Code::Blocks doesn't seem to work on my school computer, which really blows. (I spent today's study hall writing this sob story up.) Ultimately, what I ask here is, what advice can you guys offer in setting aside time to program? I'm something of a perfectionist, which I really hope won't be my downfall. I'm currently at a point where I have to compromise to get my coursework done; I'm behind on some calculus, for instance, and didn't study very much for my test today because I spent last night reading The Communist Manifesto and a chapter about Russia from my AP Comparative Government textbook. Oh, and I own an Arduino if that inspires any solutions.


How to properly design classes for a big project?

If we need to represent classes in a class diagram for a big project that is not completely designed yet, and the classes have to be actual tables in a database, how would we predict and design the classes? Let's say we have a project that is going to have more than 15 tables, do all these tables need to be classes in the class diagram? How would classes be designed in this kind of situation? The language that is being used is Java and the class diagram has to prepared in UML. I know how to design them, I just don't know if the tables should represent the classes in this case.


Algorithm to reverse engineer permutation

I have a sequence of permutations formed using these strings: `"A"`, `"BC"` and `"D"`. The permutations are:               BCAD     ABCD     BCDA     DABC     ADBC     DBCA       Now I need to reverse engineer this; i.e. I have a text file containing the sequences, I should be able to tell the strings that are used to construct the permutations. What algorithm I can use?


Android network Lib development

I have to develop an Android library that should frequently communicate with a server in the background. Access to the lib Object should be guaranteed everywhere in the Apps that will use it, so I decided to extend the Application class from Android API and return the instance created when an App is started, every time it's needed. The lib sends frequent polls to the server (Not the best practice, I know. But it's a given system and still experimental). If there's a message for the App to be parsed, it should call some kind of listener, which has to be registered by the App. When onPause is called the Lib should continue the communication for a defined time. So my questions are:   * Would it be the best way to implement the lib as an intent service?   * Is it the right approach to extend the Application class?  This is my first library project on Android, so excuse me if some of the questions seem to be too basic.


How would you evaluate object oriented design skills?

what kind of insights or questions would lead you to determine a person's OOAD skills.


Java vs C#: What should a junior programmer (just finished degree) consider when entering the programming world?

**I just want to hear some pro and con's - it's obvious that there is no right answer** So would Java be a better choice for a long term career? Or should I opt for .Net since it could be the platform having all the latest advances? **I just want to hear others point of view, so please don't close this question just because it's being subjective**


Evaluating Software Maintenance

**1. When to treat a software as deployed and when to start charging for maintenance ?** In most of the cases the software we make is deployed on the web at early stages to enhance the testing process from the client side. This means that bugs keep arising and we keep fixing them alongside development. Not just that, as the clients use it, they come to know of modifications required which creates a pile of extra work for us. Because of no demarcation line between development, deployment and maintenance stages its hard to understand when to charge for what. **2. How to charge for software maintenance ?** I read that vendors charge 15%-22% generally for softwares annually. That being a fixed fee what happens if the maintenance takes more time then expected ? What happens if the system runs fine or without issues for an year ? Does the client still pay maintenance ? **3. How to charge for non-application specific improvements ?** We use a core engine to build business applications. Improvement in that engine means improvements, new functions, etc can be made available to all clients without modifying their application layer. Should that be included in maintenance as free upgrades ? **4. How to charge for maintenance in case of hourly contracts ?** If we work on an hourly project most of the times the scope of the project keeps expanding but that doesn't require a revaluation of the project because the increase in scope equates to increase in hours and hence increase in budget. But most of the times due to increase in the scope the bug fixing and maintenance work also gets included in the development time. Is that good ? Or should there be a demarcation between deployement and maintenance even for hourly projects ?


Maintaining Regex in a .net application

I am sure everybody has had his/her share of regex woes. We have a big application with around 30 developers working on a mvc3 web application , and the two fold regex validations (front-end and server side) is becoming a nightmare to maintain. Is there a way to keep all the regexes in one place ? so that they can be used as attributes for entities and also be used for validations in the controller?


How do you learn to effectively use more than one framework

Someday, my leader told me that _don't reinvent the wheels, use framework built-in classes._ (with a serious mood) when I implement some algorithm has been supported by .NET fx. And seriously, I didn't know about these support before, cause this is the first time I work with .NET).   So I have this questions. For example, for building an Web-App we have some ways:   1. C# with ASP.NET framework   2. Java with JavaEE (and friends like Struts, Spring v.v.) framework.   3. PHP with Zend framework.   4. ... It just takes about 1 months to learn language (C#, Java, PHP...), BUT learning to use a framework **effectively** takes you at least SOME YEARS working (to know every bit of code has been built-in).   So, _how do you learn to use effectively 2 (or more) frameworks?_ Any ideas are welcome!


Best algorithm to correlate similar articles

which is the best way to correlate and group similar articles? I mean something like Google News, which groups under a single topic different articles from different sources. I'm not interested in something much sophisticated, it is just important to be efficient in terms of speed and resources needed. I can live with a correlation only on short text like the titles of the articles, not the article itself. I read a paper which talks about tuples of two or three words (best with three) to extract and use to produce a score to achieve the correlation, but it's way too much academic for me


Addressing the fact that primary keys are not part of your business domain

In almost all circumstances, primary keys are not a part of your business domain. Sure, you may have some important user-facing objects with unique indices (`UserName` for users or `OrderNumber` for orders) but in most cases, there is no _business need_ to overtly identify domain objects by a single value or set of values, to anyone but perhaps an administrative user. Even in those exceptional cases, especially if you are using global unique identifiers (GUID), you will like or want to employ an alternate key rather than expose the primary key itself. So, if my understanding of domain-driven design is accurate, primary keys _need not_ and thus _should not_ be exposed, and good riddance. They're ugly and cramp my style. But if we choose not to include primary keys in the domain model, there are consequences:   1. Naively, data transfer objects (DTO) that derive exclusively from combinations of domain models will not have primary keys   2. Incoming DTO's will not have a primary key So, is it safe to say that if you are really going to stay pure and eliminate primary keys in your domain model, you should be prepared to be able to handle every request in terms of unique indices on that primary key? Put in another way, which of the following solutions is the correct approach to dealing with identifying particular objects after removing PK in domain models?   1. Being able to identify the objects you need to deal with by other attributes   2. Getting the primary key back in the DTO; ie, eliminating the PK when mapping from persistence to domain, then recombining the PK when mapping from domain to DTO? EDIT: Let's make this concrete. Say my domain model is `VoIPProvider` which includes fields like `Name`, `Description`, `URL`, as well as references like `ProviderType`, `PhysicalAddress`, and `Transactions`. Now let's say I want to build a web service that will allow privileged users to manage `VoIPProvider`s. Perhaps a user-friendly ID is useless in this case; after all, VoIP providers are companies whose names tend to be distinct in the computer sense and even distinct enough in the human sense for business reasons. So it may be enough to say that a unique `VoIPProvider` is completely determined by `(Name, URL)`. So now let's say I need a method `PUT api/providers/voip` so that privileged users can update `VoIP` providers. They send up a `VoIPProviderDTO`, which includes many but not all of the fields from the `VoIPProvider`, including some flattening potentially. However, I can't read their minds, and they still need to tell me which provider we are talking about. It seems I have 2 (maybe 3) options:   1. Include a primary key or alternate key in my domain model and send it to the DTO, and vice versa   2. Identify the provider we care about via the unique index, like `(Name, Url)`   3. Introduce some sort of intermediate object that can always map between persistence layer, domain, and DTO in a way that does not expose implementation details about the persistence layer - say by introducing an in-memory temporary identifier when going from domain to DTO and back,


Is creating and writing to one large file faster than creating and writing to many smaller files in Python on Linux?

If using Python on a Linux machine, which of the following would be faster? Why?   1. Creating a file at the very beginning of the program, writing very large amounts of data (text), closing it, then splitting the large file up into many smaller files at the very end of the program.   2. Throughout the program's span, many smaller files will be created, written to and closed.  Specifically, the program in question is one which needs to record the state of a very large array at each of many time-steps. The state of the array at each time-step needs to be recorded in independent files. I've worked with C on Linux and know that opening/creating and closing files is quite time-expensive, and fewer open/create operations means faster programs. Is the same true if writing in Python? Would changing the language even matter if still using the same OS? I'm also interested in RAM's role in this context. For example -- correct me if I'm wrong -- I'm assuming that parts of a file being written to will be placed in RAM. If the file gets too big, will it bloat RAM and cause problems in speed or other areas? If an answer could incorporate RAM that would be great.


Setting variable in constructor or within method

I have a class which contains two methods. These methods add & remove an object to a datastore. The class which contains these methods has a no arg constructor but each of the two methods takes a variable amount of parameters for the addition / removal. Should these methods be static and if not should the method parameters be initialized within the structure as instance variables instead of at the method level ? pseudo code :                  class Utility {                 public Utility(){         }              public void add(String arg1, int arg2, boolean arg3){         //add logic here         }              public void remove(int arg1, char arg2, float arg3){         //remove logic here         }         }


When to use DI and when to create yourself in Java

I've a decent amount of OOP with various languages but am pretty new to Java. I'm reading through a lot of tutorials where large numbers of objects are created within the code of a class, and I'm trying to run through them but build versions of the classes in the tutorials that do Dependency Injection instead of instantiating all the classes themselves. But Java is not like other languages I've used in that pretty much everything is an object. If I was to literally inject everything then the result would be very messy and hard to follow. Obviously you wouldn't inject String objects, and I'm guessing there are other objects you wouldn't inject, but I'm not sure where the line should go. At what point does DI stop being the right thing to do, and when does it start being a burden? How do you decide pragmatically what to inject and what to just instantiate? FYI, the tutorials I'm doing are http://edn.embarcadero.com/article/31995 and http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html for building a simple client and server. I'm not copying them line for line though, I'm trying to create equivalent classes that follow best practice


GPL question : web application using Imagick and GhostScript => Which would be the final licence?

I am a bit confusing and I need your help to undertand my problem. I have developed a web application (PHP, JQuery) for one of my customer. Recently, my customer ask me to add a new feature permitting PDF to JPG conversion. After web browsing, I have discovered that iMagick (Apache licence) PHP extension with GhostScript (GPL licence) is the only solution. But, as my customer want to sell the web application to others companies, I have to use non-GPL licences. By the way, this feature is OPTIONAL and the final user must download and install manually iMagick and GhostScript if he his interesting by using the PDF conversion. Is there someone to tell me if the fact to use Imagick to convert PDF to JPG (and therefore use GhostScript) turns my current proprietary licence to GPL? And what about if I don't use Imagick but call GhostScript using PHP exec() function? Is there others non-GPL projects to convert PDF to JPG that I could use with PHP? Any help would be greatly appreciated.


Is there a way to calculate whether to spawn a new thread or use current thread

I am building an interpret DSL in which parallelism is part of the language - the user simply states that a calculation can be done in parallel and the interpreter _may_ decide whether to make the calculation in parallel or not. Since it is not always helpful to do parallel calculations, specially for very small jobs (context switch, memory copying between cores, etc may actually make the program slower). I want to know if there are any "best practices" available that can calculate (with high degree of certainty) whether to do a new calculation in the current thread or spawn a new thread for the calculation. Note that since my language is interpreted, I can do all kinds of monitoring on the executed program and make this decision depending on how the program executes (kind of a JIT compiler). **Update** By "Spawn" I didn't mean that I will create a new thread, but transfer the processing to a different thread, maybe from a thread pool. Note that even when using a thread pool there is overhead of possible memory transfer between processor cores and stuff like that, so even in this case the amount of work should be relatively high.


How do big companies of software developers check for bugs in their programs?

I was wondering how big companies of software developers check for bugs in their programs. Do they just test it on several computers?


Managing Spanish Code

We have a new project from a client who is Spanish and has all his Java code and comments, variables, method names in Spanish. We are not permitted to convert it into English and then use them. If any of you have worked in such a condition, can you advice what can be done to mitigate this risk as we have to do new developments and this is a major show stopper.. Their Java project has a mix of EJBs, Struts, Custom Framework and more than 10000 Java Files with atleast total of 200k lines of code (min. estimate) and is deployed using Weblogic Server 10 Regards, Dazzlers


MVVM application architecture, where to put dependency injection configuration class, BusinessLayer and Common interfaces?

Planning my architecture for an MVVM application I come to this:   * MyApp.UI      * View   * MyApp.BusinessLayer      * ViewModel   * MyApp.DataAccessLayer      * RepositoryImplEF   * MyApp.DomainLayer      * DomainObject     * RepositoryInterface   * MyApp.Common      * Logging     * Security     * Utility (contains some reflection method used by many levels)     * CustomException   * MyApp.UnitTest I was inspired by Domain-driven-desing, test-driven-development and onion architecture but not sure to have done all well. I am not sure of a couple of things:   1. where to put dependency injection configuration class? In the common project?   2. where to put BusinessLayer interfaces? in Domain layer?   3. where to put Common interfaces? in Domain layer? But Common in referenced from domain (for some reflection utilities and for DI if the response to 1. is yes) and circular reference isn't good


What is a "task pool"?

I have searched for many websites for a definition of "task pool", but most descriptions are very vague. Anywhere I can find a precise definition of it? More details.   * Are dependencies allowed in task pool?   * Can a running task exchange data with other running tasks?      * To phrase conversely, are tasks permitted to accept data _only_ prior to start and permitted to publish results _only_ after the task has finished?   * What keeps track of the temporary resources (memory, CPU etc) that are used by tasks?   * How to define weights that will encourage efficient task assignment?      * For example, if one task needs to pass a lot of data to the next task, it may make sense to run the next task immediately following the first task, and as close to the first thread / CPU / machine / cluster (locality) as possible   * What about tasks that are not known (do not exist) in the beginning, but were "created" later?


how to model a connection to a resource, with rudimentary event processing

For my simple MUD client I'm using Apache Telnet (no, not ssh). A mud client is a strange beast: > Generally, a MUD client is a very basic telnet client that lacks VT100 > terminal emulation and the capability to perform telnet negotiations. ... > Standard features seen in most MUD clients include ANSI color support, > aliases, triggers and scripting. - Wikipedia I would **like** for a not-yet-written `Controller` to have a reference to `TelnetConnection` and just use it for a higher level of abstraction for I/O, but all attempts to prise this class apart fail for me. `TelnetConnection` seems to take on responsibility for everything, and then some, and just keep growing.               package telnet;          import java.io.IOException;     import java.io.OutputStream;     import java.net.InetAddress;     import java.net.SocketException;     import java.util.Deque;     import java.util.Observable;     import java.util.Observer;     import java.util.logging.Logger;     import org.apache.commons.net.telnet.TelnetClient;     import player.GameAction;     import player.DataFromRegex;     import player.Regex;          public class TelnetConnection implements Observer {              private static Logger log = Logger.getLogger(TelnetConnection.class.getName());         private TelnetClient telnetClient = new TelnetClient();         private InputOutput inputOutput = new InputOutput();         private Regex regexParser = new Regex();         private DataFromRegex data = null;         private Logic logic = new Logic();              public TelnetConnection() {             init();         }              private void init() {             try {                 int port = 3000;                 InetAddress host = InetAddress.getByName("rainmaker.wunderground.com");                 telnetClient.connect(host, port);                 inputOutput.readWriteParse(telnetClient.getInputStream(), telnetClient.getOutputStream());             } catch (SocketException ex) {             } catch (IOException ex) {             }             inputOutput.addObserver(this);         }              private void sendAction(GameAction action) throws IOException {             log.info(action.toString());             byte[] actionBytes = action.getAction().getBytes();             OutputStream outputStream = telnetClient.getOutputStream();             outputStream.write(actionBytes);             outputStream.write(13);             outputStream.write(10);             outputStream.flush();         }              private void sendActions(Deque<GameAction> gameActions) {             while (!gameActions.isEmpty()) {                 GameAction action = gameActions.remove();                 try {                     sendAction(action);                 } catch (IOException ex) {                 }             }         }              @Override         public void update(Observable o, Object arg) {             String line = null;             if (o instanceof InputOutput) {                 line = inputOutput.getLine();                 log.fine(line);                 data = regexParser.parse(line);                 Deque<GameAction> gameActions = logic.getActions(data);                 sendActions(gameActions);             }         }              public static void main(String[] args) {             new TelnetConnection();         }          }      Part of the difficulty lies within the `InputOutput` class, which is adapted from `IOUtil` from Apache. (For some reason, I cannot include the link to to the Apache source code.) Once I send the `InputStream` to `InputOutput` there needs to be callback using `Observable` to then send the String data for matching and searching? And then get back **what** after matching and searching the text? The trick being, in terms of I/O:   1. capture console input   2. print remote output from the MUD server to the console like regular telnet   3. some regex/etc on the remote output, _concurrent_ with open, unterminated streams.  This last requirement seems to make an odd beast for which I cannot envision the flow of control and data.


Should architect or dev lead tell teammate where to add their code before coding a new feature?

I have experienced with two kinds of team. After a feature is assigned to me, one kind of dev lead tell me the exact file or class to add my code, another kind of team just say the story or requirement to me. The latter job is hard, if the software I am working on is too big to grasp the structure. Should senior guys tell the place to add the code before coding?


Why should I add CHECK CONSTRAINT?

Following is a table creating script created by Entity Framework using the model shown in http://codereview.stackexchange.com/questions/14077/is-it- proper-tpt-inheritance. In this script, there are two alter statements. What is the need for the second ALTER statement? SCRIPT               CREATE TABLE [dbo].[SellingItems_Book](     [Title] [nvarchar](max) NULL,     [Id] [int] NOT NULL,      CONSTRAINT [PK_SellingItems_Book] PRIMARY KEY CLUSTERED      (     [Id] ASC     )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,      ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]     ) ON [PRIMARY]          GO      First Alter                ALTER TABLE [dbo].[SellingItems_Book]  WITH CHECK ADD  CONSTRAINT [FK_Book_inherits_SellingItem] FOREIGN KEY([Id])     REFERENCES [dbo].[SellingItems] ([Id])     GO      Second Alter               ALTER TABLE [dbo].[SellingItems_Book] CHECK CONSTRAINT [FK_Book_inherits_SellingItem]     GO


Interfaces on an abstract class

My coworker and I have different opinions on the relationship between base classes and interfaces. I'm of the belief that a class should not implement an interface unless that class can be used when an implementation of the interface is required. In other words, I like to see code like this:               interface IFooWorker { void Work(); }          abstract class BaseWorker {         ... base class behaviors ...         public abstract void Work() { }         protected string CleanData(string data) { ... }     }          class DbWorker : BaseWorker, IFooWorker {         public void Work() {             Repository.AddCleanData(base.CleanData(UI.GetDirtyData()));         }     }      The DbWorker is what gets the IFooWorker interface, because it is an instantiatable implementation of the interface. It completely fulfills the contract. My coworker prefers the nearly identical:               interface IFooWorker { void Work(); }          abstract class BaseWorker : IFooWorker {         ... base class behaviors ...         public abstract void Work() { }         protected string CleanData(string data) { ... }     }          class DbWorker : BaseWorker {         public void Work() {             Repository.AddCleanData(base.CleanData(UI.GetDirtyData()));         }     }      Where the base class gets the interface, and by virtue of this all inheritors of the base class are of that interface as well. This bugs me but I can't come up with concrete reasons why, outside of "the base class cannot stand on its own as an implementation of the interface". What are the pros & cons of his method vs. mine, and why should one be used over another?


What Does It Usually Mean for a Feature to be "Supported"?

I'm currently working some testing for a particular area of an application. I had to write some automated tests for a particular feature but due to the circumstances, this was not easy to do. When I asked one of the other testers about it, he mentioned that the same features exist in a sister application our company produces but isn't documented anywhere (end-user documentation or otherwise). He also said that the feature doesn't typically get tested at all in the sister application and isn't usually tested in the application I work on. Apparently this feature isn't heavily used but removing it would require a fair bit of work so the benefit-cost ratio doesn't work out. All of this has left me with some questions. Other than "The documentation says so" or "We told the client it is", what usually makes a feature "supported" versus an unsupported feature?


How to manage long running background threads and report progress with DDD

Title says most of it. I have found surprising little information about this. I have a long running operation of which the user wants to see the progress (as in, item x of y processed). I also need to be able to pause and stop the operation. (Stopping doesn't rollback the items already processed.) The thing is, it's not that each item takes a long time to get processed, it's that that there are usually a lot of items. And what I've read about so far is that it's somewhat of an anti-pattern to put something like a queue in the DB. I currently don't have any messaging system in place, and I've never worked with one either. Another thing I read somewhere is that progress reporting is something that belongs in the application layer, but it didn't go into the details. So having said all this, what I have in mind is the following.   * User request with list of items enters the application layer.   * Application layer gets some information from the domain needed to process the items.   * Application layer passes the items and the information off to some domain service (should the implementation of this service belong in the infrastructure layer?)   * This service spins up a worker thread with callbacks for both progress reporting and pausing/stopping it.   * This worker thread will process each item in it's own UoW. This means the domain information from earlier needs to be stored in some DTO.   * Since nothing is really persisted, **the service should be singleton and thread safe**   * Whenever a user requests a progress report or wants to pause/stop the operation, the application layer will ask the service. Would this be a correct solution? Or am I at least on the right track with this? Especially the singleton and thread safe part makes the whole thing feel icky.


How to write reusable code in node.js

I am trying to understand how to design node.js applications, but it seems there is something I can't grasp about asynchronous programming. Let's say my application needs to access a database. In a synchronous environment I would implement a data access class with a read() method, returning an associative array. In node.js, because code is executed asynchronously, this method can't return a value, so, after execution, it will have to "do" something as a side effect. It will then contain some code which does something else than just reading data. Let's suppose I want to call this method multiple times, each time with a different success callback. Since the callback is included in the method itself, I can't find a clean way to do this without either duplicating the method or specifying all possible callbacks in a long switch statement. What is the proper way to handle this problem? Am I approaching it the wrong way?


Should Junior Programmers be involved as code reviewers in the projects of Senior Programmers?

One of my team members, a junior programmer, has impressive programming skills for his level of experience. And during code reviews, I believe in emphasizing learning, not pointing out mistakes. But should junior programmers be involved in code reviews for more senior programmers? Or should code reviews be attended only by programmers with corresponding experience?


What types of processes have to be reflected in flowchart?

In visual programming, there are many events which support our application tasks. So, along with user defined processes, should these also be in flowchart or not? What about the constructors of classes, are they supposed to be shown in flowchart or not?


What methods to you use to promote programmer awareness in an API or custom architecture?

If you are developing your own architecture or heavily use anothers vendors API, how do you promote awareness to the programming staff? For example, say you use Infragistics controls for you C# winforms apps - the controls have boatloads of methods, some quirks, and a best way to use them for your application. How do you promote the knowledge transfer thru your programming staff? Wiki's? Email? Blogs?.


How can I practice design patterns and refactoring in a deliberate way?

I was reading the book Refactoring to patterns and was wondering how I can get chance to practice the skills, because without deliberate practice on new ways to refactor and use patterns, my skills won't improve. But office work requires me to finish each task as quickly as possible. Most of the time, the project's design and architecture isn't controlled by me, I can only follow the similar style as the existing code. Sometimes there is a project with a bad design, but there is also another developer whose design skill is better than me and he already has the whole plan to refactor the project, so that I'm just following his plan. How do I get opportunities to practice?


Do enterprises use TIOBE ratings for programming languages?

Does the TIOBE rating of programming language play a prominent role in the selection of programming language in enterprise computing?


Should concrete classes avoid calling other concrete classes, except for data objects?

In Appendix A to _The Art of Unit Testing_ , Roy Osherove, speaking about ways to write testable code from the start, says, > An abstract class shouldn't call concrete classes, and concerete classes > shouldn't call concrete classes either, unless they're data objects (objects > holding data, with no behavior). (259) The first half of the sentence is simply **D** ependency Inversion from SOLID. The second half seems rather extreme to me. That means that every time I'm going to write a class that isn't a simple data structure, which is most classes, I should write an interface or abstract class first, right? Is it really worthwhile to go that far in defining abstract classes an interfaces? Can anyone explain why in more detail, or refute it in spite of its benefit for testability?


Ruby: The Bad Parts

I recently read Crockford's book "Javascript: The Good Parts" and one of the underlying premises was that programming languages can have bad sets of features which programmers should avoid. I'm a Rubyist and whilst I love the language there's always value in getting perspective. So, **what do you see as the worst feature (e.g. methods, classes, practices) in Ruby?** My intention here is not to start an argument about the merits of the language itself or its speed and so on. Rather I'd prefer a discussion of what features you consider dangerous / troublesome / painful to use, based on past experiences.


Development-led security vs administration-led security in a software product?

There are cases where you have the opportunity, as a developer, to enforce stricter security features and protections on a software, though they could very well be managed at an environmental level (ie, the operating system would take care of it). Where would you say you draw the line, and what elements do you factor in your decision? ## Concrete Examples ### User Management is the OS's responsibility Not exactly meant as a security feature, but in a similar case Google Chrome used to not allow separate profiles. The invoked reason (though it now supports multiple profiles for a same OS user) used to be that user management was the operating system's responsibility. ### Disabling Web-Form Fields A recurrent request I see addressed online is to have auto-completion be disabled on form fields. Auto-completion didn't exist in old browsers, and was a welcome feature at the time it was introduced for people who needed to fill in forms often. But it also brought in some security concerns, and so some browsers started to implement, on top of the (obviously needed) setting in their own preference/customization panel, an `autocomplete` attribute for `form` or `input` fields. And this has now been introduced into the upcoming HTML5 standard. For browsers that do not listen to this attribute, strange hacks* are offered, like generating unique IDs and names for fields to avoid them from being suggested in future forms (which comes with another herd of issues, like polluting your local auto-fill cache and not preventing a password from being stored in it, but instead probably duplicating its occurences). In this particular case, and others, I'd argue that this is a **user setting** and that it's the **user's desire** and the **user's responsibility** to enable or disable auto-fill (by disabling the feature altogether). And if it is based on an internal policy and security requirement in a corporate environment, then substitute the user for the administrator in the above. I assume it could be counter-argued that the user may want to access non- critical applications (or sites) with this handy feature enabled, and critical applications with this feature disabled. But then I'd think that's what security zones are for (in some browsers), or the sign that you need a more secure (and dedicated) environment / account to use these applications. * I obviously don't deny the ingeniosity of the people who were **forced** to find workarounds, just the necessity of said workarounds. * * * ## Questions That was a tad long-winded, so I guess my questions are:   * Would you in general consider it to be the application's (hence, the developer's) responsiblity?   * Where do you draw the line, if not in the "general" case?


When creating a library for a simple program, what must I do to protect others from its lack of thread safety?

When creating a library for a simple program, is it more cost effective to make it thread safe or is there a way to detect the program's use in a multithreaded program and ASSERT() or otherwise determine (preferably at compile or link time) that it may create problems. Related help for this question would be automated tool support for finding potential problems with thread safety, programming language features that enforce it,


Should Swing knowledge be required from Java programmers?

Swing is an integral part of the Java API. It is also the most popular GUI framework for Java. I still wonder, should every Java programmer still know, or at least be pretty familiar with, Swing (possibly excluding web developers)? There are alternatives (e.g. SWT), but they are not very widely used (compared to Swing). What do you think about requiring Swing knowledge from Java programmers? If such knowledge is important, to what degree? Are the basics enough or not? The reason I wonder is because I really don't like Swing but wonder if I still should brush up my skills in it. I'm able to create simple GUIs in it, but I would definitely not say that I know Swing well.


Where to get experience with Big Data?

I have a strong interest in creating and learning about highly scalable web sites and applications which deal with Big Data. For example, many world class web companies and startups such as Twitter, Facebook, Google, etc deal with massive amounts of data and their software engineers use tools such as Hadoop/MapReduce, Cassandra/memcache, and other algorithms and techniques and tools to make sense of this data. To me this is a very interesting and challenging area and much more invigorating than just creating yet another e-commerce or web portal for a commercial company. Naturally working at a typical software development firm won't get you experience with this level of massively distributed data processing opportunity, and very few if any people have access to cpu clusters to run Hadoop, DryadLinq, etc. I wanted to inquire if there are certain geographic areas in the countries which have companies dealing with such Big Data problems - Silicon Valley would be an obvious one, any others? Also, feel free to mention any non-obvious startups and companies which are dealing with such challenging problems. EDIT: Just read this recent article by Matt Welsh of Harvard on his (sabbatical) at Google and the scale of problems he's working on (he sounds clearly excited): Computing at scale, or, how Google has warped my brain EDIT: Found another new link on getting experience with large scale data at government institutions Tackling Large Scale Data in Government Thanks,


When should I make the first commit to source control?

I'm never sure when a project is far enough along to first commit to source control. I tend to put off committing until the project is 'framework- complete,' and I primarily commit features from then on. (I haven't done any personal projects large enough to have a core framework too big for this.) I have a feeling this isn't best practice, though I'm not sure what could go wrong. Let's say, for example, I have a project which consists of a single code file. It will take about 10 lines of boilerplate code, and 100 lines to get the project working with extremely basic functionality (1 or 2 features). Should I first check in:   1. The empty file?   2. The boilerplate code?   3. The first features?   4. At some other point? Also, what are the reasons to check in at a specific point?


Continous Delivery TFS

Is it possible to achieve Continuous Delivery using TFS e.g. Windows Service? There are > 1000 posts on how to use msdeploy with TFS for WEB projects. I am trying to understand why there are no resources such as blogs, articles, msdn or best practises for Continuous Delivery for Windows service using TFS. I am not sure tow to achieve the following without any working reference materials. This is so frustrating.   1. Archive existing codebase on Remote server for Service as well for Web project not on Integration Server please!    2. How To Stop services on Remote server not on Integration Server    3. Copy New code Base on Remote Server    4. Start Services


On the frontier between work and home

I think we've all been there: You hear of someone say "hey, wouldn't it be nice if platform X had feature Y?" You look around (on SO!), the feature really doesn't exist, even though it probably would be useful in many contexts. So it's pretty generic. Your mind wanders for a bit. "How tough would it be? Well, it'd probably be just a snippet. And an ad-hoc function. And maybe a wrapper." And boom, before you know it, you've spent a dozen hours of **your free time** implementing a FooFeature that's really neat and generic. The kind of code you might not even have the time to spit and shine at work, that would be a bit rushed and not so documented. So now you wonder "wouldn't this be useful to others?" And you've got your blog, maybe a CodeProject account, and your colleague who asked if FooFeature exists might, haphazardly, come accross that blog entry, had it existed before they told you. On the otherhand, the NDA agreement. It's sort of vague and general. It doesn't forbid you from coding at home, but it's clear on sharing company code, that's a big NO. But this isn't company code. Or is it? Or will it be? So, what do you do with code (that's more than just a snippet) you wrote in your off time with universality in mind but an idea that came from work, and that will most likely be used at work? Can it be published?


Pitfalls in the Grails Framework

What are some of the biggest issues/pitfalls with using the Grails framework? I'm learning the framework now, and I really like it, but I need to know what major issues I may encounter when using it and how to avoid them.


Is there a name for the new "shake phone" interface convention?

Some mobile applications leverage the fact that smart phones have motion sensitivity to provide a "shake" feature. For example, I believe Urban Spoon has an app with which you can view a recommendation for a nearby restaurant; if you don't like the recommendation then you can shake your phone and it will immediately come up with another one. Is there a **word** for this new interface pattern/idiom/convention (or whatever you want to call it)?


Will taking courses in system administration help land a programming job?

I just completed a B.S. in Computer Science from a less-than-reputable college, and I am having trouble finding a job. Looking around for ways to find a job, I came across an institute that teaches system administration. Their claim is that, after finishing the course, I will be in a much better position than "normal" Java programmers and my salary will grow "exponentially". I don't buy that claim, but additionally, he kept saying that this course will help me choose jobs in country of my choice as there are very less people available in this particular domain. When asked why the salary grows "exponentially", he drew an analogy where he said it was "for the same reasons heart specialists are paid more than orthodontists". This is because the job profile will be maintaining important data and make sure that availability of the systems which is very critical in fields like health care and Banking (I am not sure about this claim). My whole point is, I am very interested in programming. Will taking a course in systems administration help me at all? Are any of the claims he's made reflective of reality?


To Repository Or Not To Repository

When I first learnt about Domain Driven Design, I was also introduced to the repository and unit of work patterns that once seemed to be top notch for the cool kids that threw SQL queries like cavemans against databases. The deeper I got into that topic, the more I learnt that they don't seem to be necessary anymore because of _ORMs_ like **EF** and **NHibernate** that implement both unit of work and repositories into one API, called session or context. Now I'm unsure what to do. To repository or not to repository. I really understand the argument that such leaky abstractions only over-complicate things while adding absolutely nothing that may simplify data access, however, it doesn't feel right to couple every possible aspect of my application to e.g. **Entity Framework**. Usually, I follow a few simple guidelines:   1. The domain layer is the heart of the system, containing entities, services, repositories...   2. The infrastructure layer provides implementations of domain interfaces of a infrastructural concern, e.g. file, database, protocols..   3. The application layer hosts a composition root that wire things up and orchestrates everything. My solutions usually look like this:               Domain.Module1     Domain.Module2         IModule2Repo         IModule2Service         Module2     Infrastructure.Persistence         Repositories             EntityFrameworkRepositoryBase     MyApp         Boostrapper             -> inject EntityFrameworkRepositoryBase into IRepository etc.      I keep my domain layer clean by using a `IRepository<'T>` which is also a domain concern not depending on anything else that tells me how to access data. When I now would make a concrete implementation of `IModule2Service` that requires data access, I would have to inject `DbContext` and by this, coupling it directly to the infrastructure layer. ( _Coming to Visual Studio project, this can end up really tricky because of circular dependencies!_ ) **Additionally** What can be an alternative to _depositories_ and _fucktons of works_? CQRS? How does one abstract a pure infrastructural framework?


structure problem in Relational DBMS creation

For learning and understanding purpose, I currently want to try to make a small relational `DBMS` with simple features like (for now) only sequential reading/writing and **CREATE TABLE** , **INSERT** , **SELECT** , **UPDATE** and **DELETE** management. I am currently on the " _think_ " part of the project and I am stuck on the way to store the read data in memory. First I was thinking of putting them properly on a structure, but the problem is that tables are all different, know the type of each column is not an issue, but I am not sure C provide a way to make fully dynamic structure. My second and current idea is to make a simple `char array` of the required length and just get the data by order with cast. But I am not sure if it is the good way to do that part, so I wanted to ask for your opinion and advices about that. Thanks in advance for your help. * * * nb: I hope my question is enough clear and understandable, I still lack of pratice in english


Conceptual question regarding the portability of a software from desktop to mobile

I am planning to create a web solution for the desktop, I would be dividing my task into three steps   1. Design   2. Coding   3. Automated use case I am wondering if in the future I have to port my web solution as mobile phone native application. How would I do that? Will I go back again to the design phase to redesign or will I just recode some of the already written stuff meant to be for the desktop?


Standard semantic name for 3rd table in 3NF

For 3 tables that are in 3NF, a many-to-many relationship, is there a standard name or term to describe the 3rd table, the one that associates the other tables? Basically, I'm looking for a semantic way to name the 3rd table. **Example** You have two tables: _users_ and _widgets_. A user can have multiple widgets and a widget can be owned by multiple users. What is the most semantic name for the 3rd table? In the past, I've used the following at one time or another:   * userWidgets   * userWidgetAssn (association)   * userWidgetXref (cross-reference) In my example, userWidgets is probably my top choice, but it doesn't always work as cleanly depending on the table names. Is there an industry standard?


Developing With Ruby/Rails Easier, Faster Than Developing With PHP/CakePHP?

What is your experience when developing web applications using one of these two languages/frameworks? Which have you found to be more convenient and faster to develop with?


Best way to implement database design for a set of entities

Lets say I have a scenario like so: I have many claims to get money from another entity and this claim has to go through two gateways. This claim is sent from an origin system and can possibly be rejected at each gateway. If the claim is rejected at either gateway, one or more messages will be sent back to the origin system that indicate why it was rejected at that gateway. Here's a diagram: ![enter image description here](http://i.stack.imgur.com/RTBvY.png) Note that the some attributes of messages of a rejection from Gateway #1 are different from #2 in my actual system, so they are not the same type of entity. Now, my requirement is to create a reporting system that can display various aggregations of that data by designing a database layout for it. The reporting needs to be able to aggregate by claim cost, number of claims, and be able to display reports at the rejection message level too. Another requirement is to be able to see if a claim was resubmitted through the process based on an ID representing an overall claim process. From my company there appear to be two routes to go about creating the database table layout for this reporting system, listed here: Have one table that displays all attriutes of the claim, and both rejection levels and put all necessary attributes of those entities as different aggregations on that table (denormalized). Or... Create a table layout in which there is a table that represents the claim, a table that represents a rejection at gateway 1, and a table that represents a rejection at gateway 2, with the claim table being the parent of the other two. Keep in mind that rejections at both gateways #1 and #2 contain different attributes. What is the best route to choose between these two choices? Is it situational, as in is there a best option depending on other requriements, and if so, can you explain what those requirements might be?


In Android, is there any reason to set up a content provider for a local database?

I have an android application with a custom content provider set up to load data asychonously. The database is a local file so I'm not sure if I needed to set up a content provider at all. Sometimes I just need to do something like get a name back from a short list by id. Is it ok to mix the content provider pattern with simple direct database calls, i.e open, query, close type of code blocks?


Functional Programming, JavaScript and UI - some neophyte questions

In the discussion here, the comments in the accepted answer suggest that I approach the given code from a functional perspective, which was new to me at the time. Wikipedia said, among other things, that FP "avoids state and mutable data", which includes according to the discussion global vars. Now, being that I am already pretty far along in my project I am not going to learn FP before I finish, but:   1. How is it possible to avoid global vars if, for instance, I have a UI whose entire functionality changes if a mousebutton is down? I have a number of things like this.   2. Why was there a strong negative reaction among some experienced coders to implementing FP in JS? When I brought up what seemed to me to be supportive comments by Crockford, people got even madder. Are there strong arguments against using fp in JS? What constitutes a "functional language" and why is JS "not it"?