Does Object Oriented Programming Really Model The Real World?

I've seen it commonly repeated the object oriented programming is based on modelling the real world, but is it? It seems to me that is not true of anything outside of the business layer. My GUI classes/data access classes aren't modelling anything in the real world. Even in my business layer I've got classes like observers, managers, factories, etc. which aren't real world objects. I try to design my classes to take advantage of things like encapsulation but is the real world encapsulated? While some objects I create are modelling real world objects, would not pre- OOP code do the same? I doubt that OO was the first people to include concepts like Customer in their code bases. But OO is really about how to model things, and that method of modelling doesn't seem inspired by the real world to me. So: does object oriented programming really model the real world? **EDIT:** If your going to post yet another answer telling me how awesome OO is, you haven't understood the question. The question is about how we describe OO, not OO's merits.


When is it worth NOT using a Factory?

I'm employing TDD quite a bit these days and really enjoying myself - everything seems to flow better and be naturally better constructed and organized. However, while writing a bit of IO code, utilizing `System.IO.Stream`s, and I was wondering - when is it ever worth not using a factory? Because in `Stream`s case, it certainly seems better to not use a factory. Generally, for more complex types that I have defined, such as a class that controls the authentication of something and interfaces with a database, you would probably use a dependency injection container and have this resolved at runtime without ever needing to _actually_ create one. However, in some circumstances, when you need to create a lot of these instances, you would create a Factory to construct that type - such as:               class Foo       Foo(Bar bar, Foobar foobar, Fuzz fuzz)       ...     end      Here, because you don't want to expose how to directly create this object to the clients that need it, you expose a Factory that will create them and inject that into the client instead. This has the benefit of allowing you to replace the factory at any time you want with something else and is generally used for creating instances of types which have derived types.               class FooFactory        void Create(Bar, Foobar, Fuzz)     end      However, back to my `Stream` point - would it even be worth creating a Factory for a decorator around a Stream? For example, in my project I have `BinaryDataStream`, which reads my data from a Streeam. The BinaryData is in a custom format, and takes a Stream argument in it's constructor. Using `new` seems to violate everything I know that I've learned since I started using TDD, **because I am giving the dependent in which it needs to know explicitly about how to get it's collaborator** However a factory seems overkill. Thoughts? EDIT: I think I need to clarify. I don't mean avoiding new() all the time, as obviously it has it's use in tying up dependencies and the like. **however** , I meant in the following situation (copy-pasta from comments): > What I meant was that I have been told it is intrinsically evil to use the > new() operator to a collaborator from inside the type that uses the > collaborator, and that it is better to either a) pass an injected type or b) > pass a factory (if you need to create an unknown number of those types). By > using new() inside the collaborator you tie how to create that object and > where to create it directly to the thing that requires it, and that it is > better to inject a preconfigured instance into the constructor if you need > one instance of it, or inject a factory into the constructor if you need to > create multiple/undetermined number of instances


What is the pattern name for using method chaining to build an object?

I frequently use a pattern where I using method chaining to setup an object, similar to a `Builder` or `Prototype` pattern, but not creating new objects with each method call, instead modifying the original object. **Example:**               new Menu().withItem("Eggs").withItem("Hash Browns").withStyle("Diner");      Just wondering if there is a name for this pattern and whether it is considered an anti-pattern, because although it can read more fluently, it can lead to long method chains.


Android vs iPhone development

Which is a better career Android vs iPhone app development. Android has the advantage of beingopen source while iPad/iPhone is one of the best product in the market and Apple is leading the mobile industry now. What would be pros and cons of each career and can iPhone developers move into Android easily? Please let me know if anyone has a experience in either of these areas


Does code generation increase the code quality?

Arguing for code generation, I am looking for some examples of ways in which it increases code quality. To clarify what I mean by code generation, I can talk only about a project of mine: We use XML files to describe entity relationships in our database schema, so they help us generate our ORM framework and HTML forms which can be used to add, delete, and modify entities. To my mind, it increases code quality because human error is reduced. If something is implemented incorrectly, it is broken in the model, which is good because the error might appear sooner since more generated code is broken too. Since I was asked for the definition of **code quality** , let me clarify this, what I meant is **software quality**. **Software Quality** : It is not one attribute but many, e.g. efficiency, modifiability, readability, correctness, robustness, comprehensibility, usability, portability etc. which impact on each other.


Data structure for file search

I've asked this question before and I got a few answers/idea, but I'm not sure how to implement them. I'm building a telecom messaging solution. Currently, I'm using a database to save my transaction/messages for the network stack I've built, and as you know it's slower than using a data structure (hash, linkedlist, etc...). My problem is that the data can be really huge, and it won't fit in the memory. I was thinking of saving the records in a file and the a key and line number in a hash, then if I want to access some record then I can get the line number from the hash, and get it from the file. I don't know how efficient is this; I think the database is doing a way better job than this on my behalf. Please share whatever you have in mind.


Is it a good idea to develop website that only has little access to DB? CRUD will be done by calling API provided by separate internal backend system

I'm going to start developing an application in near future. This application consists of :   1. Back-end system. This system provides API to be used by client. This system connects to data store and 3rd party API.   2. Data Store : Can be relational or nosql data store.   3. Client : Client will be a website and mobile applications. My reasons are below :   1. I want to prevent duplicated SQL query and 3rd party API call in website application side. The application and website will be developed by different developers. Only back end system developers that can make query or call 3rd party API. All website developers should only use API provided by back-end system   2. In my opinion, the website is also a client just like the mobile application. If the mobile apps get their data from back-end system API, why the website shouldn't be the same.    3. I heard twitter is using similar idea (I can be wrong though). Its website is using twitter API just like their mobile application. My primary concern to this architecture is that the website performance will be lower compared than If the website can make query or 3rd party API call directly. Is there any other pros and cons that I should think about ?


Is there any technology for dynamic assignment of execution context for programs that target many platforms with widely varying runtime performance?

This may very well be nothing new and probably exists, but I've never learned about it and would like to. The simplest way to be more specific is just to give an example. I was on the bus and downloaded a Text to Speech appliation onto my Android phone. I know that the speech synthesizer might run on my phone but probably runs on a remote server. In the near future I bet the processors in phones will go up and some people will have phones that could do the work but some will not. In the scenario I just describe, the ideal situation might be if the execution environment dynamically pulled code to locally execute and/or pushed code back to be remotely executed. I realize there are plently of frameworks for remote object calling, but do any of them pre-suppose the above?


Use of separate threads or singe thread

In my project, on a security system, I was using a socket to get the details of the client and then store it in a database (his IP and port he connected from and service he accessed). I was wondering if the fetching of the details and storing them in a database should be done in separate threads or a single thread. Which is the more advantageous approach?


Looking for recommendations for a database design 101 class

I've been tasked to train a new MS Access developer that's moving into my department in a couple weeks. I'm not completely certain what his knowledge level is, but from what I've seen he knows very little if anything about basic design concepts like normalization. I don't think he even knows much VBA and is still primarily macro/wizard driven. There's no budget in my department for training, so free options are the only ones I could use. What resources could be recommended to help me teach him some of the basics and start developing a foundation to build on to get him up to speed?


Web security course?

I'd like to do a course about web security. I've seen some certifications that could be interesting:   * CIW Web Security Professional   * CISSP® - Certified Information Systems Security Professional   * Certified Secure Software Lifecycle Professional What do you know about these certifications? are they recognized? I'm not trying to become a hacker, I just want to ensure I have enough knowledge about web security to cope with today internet. From my inexpert point of view, "Certified Secure Software Lifecycle Professional" looks exactly as I want, the problem is that it cost more than 500 bucks! Why certification? well, I want to learn but I would like also have a way to demonstrate to a future employer/customer that I had to study and pass exams, not only attend to a course. Regards.


Tips/Process for web-development using Django in a small team

We're developing a web app uing Django and we're a small team of 3-4 programmers — some doing the UI stuff and some doing the Backend stuff. I'd love some tips and suggestions from the people here. This is out current setup:   1. We're using Git as as our SCM tool and following this branching model.   2. We're following the PEP8 for your style guide.   3. Agile is our software development methodology and we're using Jira for that.   4. We're using the Confluence plugin for Jira for documentation and I'm going to be writing a script that also dumps the PyDocs into Confluence.   5. We're using `virtualenv` for sandboxing   6. We're using `zc.buildout` for building This is whatever I can think of off the top of my head. Any other suggestions/tips would be welcome. I feel that we have a pretty good set up but I'm also confident that we could do more.


User Stories about Automated tasks, who is the user?

Following the formal user story style: > As `<user>`, I want `<goal>` so that `<benefit>`. How can stories be written when there isn't an obvious user-interaction taking place, as in the case of automated processes like nightly invoicing?


Who's the author/creator of the Repository Pattern?

I´m pretty sure it´s not the gang of four. I have a feeling this is a newer pattern. Where was it first published/mentioned?


How do I format negative user stories?

Following the formal user story style: > As `<user>`, I want `<goal>` so that `<benefit>`. Our team has found difficulties in expressing things where there is a desire by the system's owners to do something which negatively affects the user. As an arbitrary example, let's say owner wants to have the system charge customers every time they check their email. Following the formal style of user stories, you might write this as follows: > As a customer, I want to be charged every time I check my email so that the > system owner can increase their revenue. Obviously the customer has no desire to be charged; the story becomes jarring to read and the language is getting in the way of the facts. How could the requirement be written differently?


When opening pdf's in browser, why is "inspect element" available and "view source" not?

When opening pdf's in Chrome and Firefox, the "view source" button is greyed out. "Inspect elemet," however, reveals HTML. Are the browsers simply downloading the file and generating html to display it?


How should I handle two crons that update the database?

I'm working on a Bitcoin-clone block explorer (specifically Mincoin) which has a block timer of about 1 minute. For those unfamiliar with Bitcoin, basically a new data structure called a block is propagated to the network about every minute. A block itself holds a lot of information, but three things are the most important:   * The previous block before it   * The next block in the chain   * A data structure containing transactions on the network So sometimes in Bitcoin there is a "reorganization" which means the network finds that some of the most recent blocks are not valid and it switches over to another miner's branch. At the moment every 1 minute I get all of the new blocks from the network and I store them into my database. However when a reorganization happens I was previously unable to delete and re-do the block structure of my database. Now that I've written that functionality in, I'm encountering a new problem. I've got a function that looks in the past 100 blocks and checks if the hash of the block is the same as what my Mincoin client reports. If there was a reorganization, then some blocks will be different. I find the first block that is different and I delete from the database the block before it (so that block can point to the correct new one that will be found), the block itself, and all records of all blocks and transactions that happen after it, then rebuild from there. The problem is the process of finding and deleting each transaction within the deleted blocks takes more than one minute because of the large amount of data, even though the fields I'm searching on are indexed. So I'm worried that the 1 minute cron I've put on the program will cause a problem where it starts to write again from the database at the same time the process of deleting from the rebuilding function is happening. I'm using PHP and PDO so I have a PDO transaction for the rebuilding function, but this just adds more confusion. If the PDO transaction starts deleting records, then during that process a new cron finds some new blocks and writes them to the database, then the PDO transaction ends, which data will be stored? Will it cause an error? How is the best way to handle this -- should I write some field into the database that controls the regular cron (simply put a switch 0 or 1 for on and off) and keep the switch disabled while the rebuilding function is doing its thing? I'm not sure how to structure the flow of this program to ensure I am not causing my database to have inaccurate data in it.


What's missing in ASP.NET MVC?

I think that most people would agree that ASP.NET MVC is one of the better technologies Microsoft has given us. It gives full control over the rendered HTML, provides separation of concerns and suites to stateless nature of web. The last version of the framework gaves us new features and tools and it's great, but... what solutions should Microsoft include in new versions of framework? What are biggest gaps in comparison with another web frameworks like PHP or Ruby? What could improve developers productivity? What's missing in ASP.NET MVC? Why is this missing feature important? How do you do without it now?


Static factory vs factory as a singleton

In some of my code, I have a static factory similar to this:               public class SomeFactory {              // Static class         private SomeFactory() {...}              public static Foo createFoo() {...}              public static Foo createFooerFoo() {...}     }      During a code review, it was proposed that this should be a singleton and injected. So, it should look like this:               public class SomeFactory {              public SomeFactory() {}              public Foo createFoo() {...}              public Foo createFooerFoo() {...}     }      A few things to highlight:   * Both factories are stateless.   * The only difference between the methods are their scopes (instance vs static). The implementations are the same.   * Foo is a bean that does not have an interface. The arguments I had for going static was:   * The class is stateless, therefore doesn't need to be instantiated   * It seems more natural to be able to call a static method than to have to instantiate a factory The arguments for the factory as a singleton was:   * Its good to inject everything   * Despite the statelessness of the factory, testing is easier with injection (easy to mock)   * It should be mocked when testing the consumer I have some serious issues with the singleton approach since it seems to suggest that no methods should ever be static. It also seems to suggest that utilities such as `StringUtils` should be wrapped and injected, which seems silly. Lastly, it implies that I'll need to mock the factory at some point, which doesn't seem right. I can't think of when I'd need to mock the factory. What does the community think? While I don't like the singleton approach, I don't seem to have a terribly strong argument against it.


Abstracting complexity of transactional key value store

Our application stores settings in the platform's "transactional key-value store".               prefs.edit().putInt("a", 1).commit();      int a = prefs.getInt("a");      I'd like to refactor our code for the following goals:   * Better type safety (ex.: int a = prefs.getA(); prefs.setA(1);)   * Hide away the complexity of storing values It looks like I need a Preferences class and a class to translate it to/from storage.               public class Preferences {         private int a;              public int getA() {             return a;         }              public void setA(int a) {             this.a = a;         }     }          public class PreferencesMapper {         IValueStore valueStore;              public PreferencesMapper(IValueStore valueStore) {             this.valueStore = valueStore;         }              public void save(Preferences prefs) {             this.valueStore                     .edit()                     .putInt("a", prefs.getA())                     .commit();         }              public Preferences load() {             Preferences prefs = new Preferences();                  prefs.setA(this.valueStore.getInt("a"));                  return prefs;         }     }      Now the weak typing is concentrated in that single class and the rest of the application is more robust. However, the code still leaks load/save complexity and I wonder if it's necessary.               Preferences p = preferenceMapper.load();     p.setA(1);     preferencesMapper.save(p);      I think the ideal situation, with respect to single responsibility design, is to have a single Preferences class that knows how to load/save (or delegates to something else on its own). I'm looking for direction on making this situation better.


What is the path to become a manager/CIO/CTO?

From your experience, what must be taken or done to become a manager/CIO/CTO when your background is computer science/programming? Do I need to take a management degree (MBA) in order to become a manager or to have career in management level? Anybody care to share?


Does SOA service composition actually work in practice?

One of the main SOA service design principles is Service Composability principle (https://en.wikipedia.org/wiki/Service_composability_principle). The idea is that by composing new services using existing ones as building blocks, one can rapidly develop new services. Kind of analogously to how you call exising methods of objects when you implement new methods. This is where much of productivity boost from SOA is supposed to come from. ![enter image description here](http://i.stack.imgur.com/xsmJJ.jpg) Does someone really do this in practice? I have seen this repeated endlessly in written text, but have not experienced working real world implementations myself. Most of the text also omits any mention of **transaction handling** , which seems to me to be the biggest obstacle in realizing composable services. First, you really do need to tackle the transactions problem before you can compose any non-trivial services. Sure, if the example has services "findCurrentTime()" and "writeLogMessage()" its easy to not worry about transactions, but not when having real world examples such as "depositMoney()" and "withdrawMoney()". I know of two options:   1. Implement real transactions with WS-Atomic Transaction or such   2. Implement compensation-based solution which compensates call to A with "cancelA()" or somesuch if call to B fails Both of these seem very problematic / close to unusable to me:   * WS-Atomic Transaction      * a _lot_ of complexity, most advice that I found just warns "pain in the ass, dont do it"     * support is limited, for example if you take open source ESBs, main alternatives ServiceMix, Mule or WSO2 do not support it   * compensations      * implementing the handling of compensations seems very complex to me. What do we do if service A succeeds and we never get an answer from service B and do not know if it failed or succeeded? Handling such logic manually (as implementor of compositing services) makes me want to slit my wrists - this is the kind of work some tool should do for me!.     * I also dont see how you can have compensation methods in non-trivial services. Say your service A is "depositMoney()" and that succeeds, some other action quickly transfers the money elsewhere, and then we receive "compensateDepositMoney()", what do we do now? Seems like a big can of worms. To me it seems that **service composition is such a fundamental SOA principle that you really do not get the benefits of SOA if you cannot (conveniently) compose services**. What's the reality? 90% of SOA users use "criplled SOA" without real service componsition? Or most users do in fact use service composition and I am exaggerating the difficulty of it?


What algorithms would be useful for designing a stock market simulator?

We are in the process of building a stock market simulation game. The frontend design is ready but we are clueless about how exactly the back-end algorithms are to be designed. What algorithms should we be looking at implementing in order to get this working? We're coding in PHP/RoR/Python. If there's an open source system that already exists that we could look at that would be an added bonus.


How long should we generally spend writing unit tests for a new feature or bug fixing?

When I have to implement a new feature or fix a bug, I usually try to recreate the situation with a test. I sometime spend around 3 hours coming up with fixtures and writing the test. The actual feature implementation or bug fixing takes less than 1 hour. Does anyone else out there spend at least 3 times longer to write a test compared to actually implementing a feature or fixing a bug? What's the acceptable ratio of time spent writing test to writing code?


Should I be looking up the answers to programming exercises?

I have recently started my journey to learn programming, and got my self a book on Objective-C. The thing is though: I get stuck quite often, trying to figure out how to solve the different exercises. I am quite new, currently on chapter 5 and trying to figure out how to do the different exercises. I get stuck and can't solve the exercise, so I look up the solution on the official forum and try to understand how they solved it. Then I keep thinking that the authors intention must to be able to do the following exercises, so I get a little worried about not being able to do all exercises. So I was wondering: is it bad learning behaviour to look up the solution online, and try to understand the method behind the solution, or should I keep sticking with that method, and learning it somehow sooner or later? What did you do when you were in the same learning process as me?


Is timing exactly how much time each team member spends on a story useful in Scrum?

One of my colleagues has suggested timing how much time each team member spends on each user story. This seems to me likely confusing for the dev team during the iteration, and misleading as a metric for story estimation in future planning meetings. Do any of you have experience with such a system and any thoughts on how useful or disruptive it might be?


Do I really need oop for my kind of job? After 10 years I think I don't

After 10 years of writing something like business logic for my company I realized that for 95% of my code I just don't need any special OO techniques. For years I tried to get better with all that OO stuff. But with every book or article I got more confused and the resulting code was uglier and harder to maintain. And it always felt wrong and much to complicated. The point is, that my job is very easy from an technical point of view. Read stuff from a database (not really SQL), do some calculations and maybe write something back to the database. Handling errors and transactions correctly is the biggest issue. I found out, that the easiest way to express myself in c++ for what I have to code is to write plain functions. Maybe handling parameters with structs from time to time. But that's almost it. I wrote some helper classes, that I need on a regular base, but that is not necessary very often. But in the past I surrounded every little or large peace of code with a class. And that is also what my co-workers from the c# department are doing and telling me all the time. My question is, what is going wrong with us, that we think, that we can solve every software development problem by throwing just more OO techniques on it? I needed 10 years to figure out that less is more. I looked through the book written by this guy from Romania who does a lot of magic with templates. And I thought: "Man, this looks so interesting - why are you just not needing it??" Since this here is for Q&A: How much OO do you need to get your job done? And how often do you think, that you are doing something more complicated that necessary just because you have read about a new cool idea. And what do you do to not get into the overdesigning trap?


Is it appropriate for a class to only be a collection of information with no logic?

Say I have a class `Person` that has instance variables `age`, `weight`, and `height`, and another class `Fruit` that has instance variables `sugarContent` and `texture`. The `Person` class has no methods save setters and getters, while the `Fruit` class has both setters and getters **and** logic methods like `calculateSweetness`. Is the `Fruit` class the type of class that is better practice than the `Person` class. What I mean by this is that the `Person` class seems like it doesn't have much purpose; it exists solely to organize data, while the `Fruit` class organizes data and actually contains methods for logic.


Term for Performance Issues Due to Looping

Is there a term for performance issues caused by someone creates a loop that performs hundreds or thousands of actions that could have been done in bulk? My example is that I keep running into loops that loop through a group of IDs and then perform a single query for each ID to retrieve the associated row instead of creating a single query.


Organizing ASP.Net Single Page Application with Nancy

As a personal project, I'm creating a single page, asp.net web application using Nancy to provide RESTful services to the single page. Due to the complexity of the single page, particularly the JavaScripts used, I've think creating a dedicated project for the client side of web development and another for service side will organize and simplify the development.               solution       |       +-- web / client side (single html page, js, css)       |    - contains asp.net project, and nancy library        |      to host the modules in application project folder       |       +-- application / service (nancy modules, bootstrap for other layer)       |       .       .       . and other layers (three tier, domain driven, etc)       .      Is this a good way of organizing a complex single page application? Am I over- engineering the web app, incurring too much complexity?


Will Metro-style Apps replace Desktop Apps?

Microsoft Windows8 supports new Metro-style apps, and Metro apps don't use Win32; they run on WinRT. I wonder if the Metro-style Apps was invented for only tablets. Does Microsoft hope that Metro-style apps eat all old Desktop Apps finally, or will they go with the two platforms until 2020?


On what basis would you split donation money among your open source team members without any strife?

I am a developer of an open source project which is hosted in SourceForge. It started out as a little app then after some releases, it got more and more popular and it started consuming more time and responsibility from me. So I have enabled the donation option in SourceForge. I'm passionate to continue developing it for free but if (ever) any money comes in, how should I split it with my team?   1. Should I split the amount equally among the number of team members? (50-50 as it is two-member team now)   2. Number of classes, commits or any other valuable submissions by team members?   3. Any other idea? What would you do in such situation? Please give your opinions.   I hope this question will be useful for others.


What's the reasoning behind the "I" prefix naming convention for interfaces in .NET?

I know the "I" convention has been around since COM, but I've never understood why it hasn't been reconsidered like every other naming convention before .NET has. Consumption wise, the only thing that separates an interface from, say, an abstract class, is that they can be multiply inherited. But everything after Visual Studio 2003 has shown type signatures in tooltips, so it's as useless as all the other Hungarian notations that have been discarded. I also thought it might be so that you can have a basic implementation of the interface with the same name, e.g. `Message` inheriting `IMessage`, but most of the .NET libraries have gone for adding the word "Base" at the end (e.g. `System.Collections.ReadOnlyCollectionBase`) instead -- and this makes more semantic sense. COM interop seems to be another possible reason -- but it's not as if the wrapper classes that it generates are perfectly idiomatic .NET, so I doubt that that was an aesthetic consideration. In one of my newer projects I've forgone the convention entirely, and it feels just fine. Is there something I'm missing?


What should I include in my repositiory from IDE projects

I want to add a project which in this case is created in Netbeans but this question is general for most IDE's. It's simply, what should I include in my repository. For example Netbeans creates a nbproject folder, eclipse creates a .settings folder etc. should I include these in my repository, what are the advantages/disadvantages of including or not including project specific settings. In this case it's a personal project so I don't imagine that other people will start working on it, but it would be nice to add the bare minimum of project settings so the project itself will be easy to start work on different machines.


Verification for value of test standards

We are currently developing a concept for our tests standards. Up until now, we don't have standards. All we do is to tell the developer to write tests. Now we have the following basic idea: We will use the coverage metric described in Developer Testing blog article Selecting Developer Testing Metrics to visualize the status quo. We won't make demands how much percent the code has to be covered. Nonetheless we want some kind of control. Therefore we will check if the coverage has significantly reduced over time. If this is the case the whole team will be informed. There should be no personal blaming. To encourage the developer to write more tests we will ask them to do the estimate of a feature with the tests in mind, so that they have enough time do write the tests. We don't have much experience in test standards. Is this a good approach? Is this metric useful? And what do you think about our strategy to control the team members? **EDIT** Some additional information regarding Sklivvz's post. We have nearly no code covered. Overall it is about 25%. Some components are just not covered. Our problem is, that our developers - mostly people with 10+ years experience - don't write tests at all. Therefor we invests much time in fixing bugs found by our testing team. What we want, is to have more assurance that we don't break something by implementing another thing and that we don't make the same bugs. Additional it would be nice to let the tests guide our team members to make a better architecture in their components. I personally have seen it in a component where I came in later and had refactored the whole component at some point, because it was not even a little bit testable. We develop a software platform which grows several years now. Therefor we have much code which is not covered by tests. Like I said above we want to motivate our team members to write tests for their components which they are currently developing.


Why are so many HTML tables used in page markup?

I'm trying to get into web development, so I started learning HTML, CSS, and javascript. I've been coming along really well with javascript, but I still can't make anything with HTML and CSS to save my life. I was going to ask for some places or tips to improve, but I know the question has been asked countless times and would just get deleted, so I figured I would just view the source of some other people's websites. What I keep seeing is tables left and right. Is there a valid reason to use tables?


Haskell memory efficiency - which is the better approach?

We are implementing a matrix compression library based on a modified two dimensional grammar syntax. Now we have two approaches for our data types -which one will be better in case of memory usage? (we want to compress something ;)). The grammars contain NonTerminals with exactly 4 Productions or a Terminal on the righthand side. We will need the names of Productions for equality checks and grammar minimization. The First:               -- | Type synonym for non-terminal symbols     type NonTerminal = String          -- | Data type for the right hand side of a production     data RightHandSide = DownStep NonTerminal NonTerminal NonTerminal NonTerminal | Terminal Int          -- | Data type for a set of productions     type ProductionMap = Map NonTerminal RightHandSide          data MatrixGrammar = MatrixGrammar {         -- the start symbol         startSymbol :: NonTerminal,         -- productions         productions :: ProductionMap             }       Here our RightHandSide data saves only String names to determine the next productions, and what we do not know here is how Haskell saves these strings. For example the [[0, 0], [0, 0]] matrix has 2 productions:               a = Terminal 0     aString = "A"     b = DownStep aString aString aString aString     bString = "B"     productions = Map.FromList [(aString, a), (bString, b)]      So the question here is how often is the String "A" really saved? Once in aString, 4 times in b and once in productions or just once in aString and the others just hold "cheaper" references? The Second:               data Production = NonTerminal String Production Production Production Production                     | Terminal String Int           type ProductionMap = Map String Production      here the term "Terminal" is a bit misleading because its actually the production that has a terminal as right hand side. The same Matrix:               a = Terminal "A" 0     b = NonTerminal "B" a a a a     productions = Map.fromList [("A", a), ("B", b)]      and the similar question: how often is the production a saved internally by Haskell? Possibly we will drop the names inside the productions if we don't need them, but we are not sure right now about this. So lets say we have a grammar with about 1000 productions. Which approach will consume less memory? Finally a question about integers in Haskell: Currently we are planning on having name as Strings. But we could easily switch to integer names because with 1000 productions we will have names with more then 4 chars (which i assume is 32 bit?). How does Haskell handle this. Is an Int always 32 Bit and Integer allocates memory that it really needs? I also read through this: Devising test of Haskell's value/reference semantics \- but I can't figure out what that exactly means for us - I'm more of a imperative java child then good functional programmer :P


How to manage potentially outdated data from WikiMedia API

I am writing a web application that pulls small parts of articles from Wikipedia and presents them to users. I do not wish to delete entries of the articles because I do not want to be sending a ridiculous amount of requests to the WikiMedia API, putting unnecessary load on them. My question is, since Wikipedia is by nature, collaborative and dynamic, what would be the best way to serve reasonably updated content to users (the content does not have to reflect the current article 100%, but it shouldn't be too far behind) without constantly querying their servers? I'm leaning towards storing the snippets of the articles in my database along with a timestamp and whenever an user requests an article with a timestamp over x days, I would re-query the API and update the entry in my database. The other problem with that is I am grabbing the articles via client-side Javascript, then calling an API on my server to store it. Updating an article would look like: User queries article -> my server returns article -> client-side checking decides the timestamp is too old -> client-side re-queries WikiMedia and displays the content to the user -> client-side fires request to my server to store the data. This seems like it could be done better, but I do not want to be querying WikiMedia directly from my server... How could I make this better? Architecture: SlimPHP framework, RethinkDB + PHP driver, jQuery/JS, HTML, CSS


Using python to parse log files?

My first useful projects as a programmer has been python scripts that parse out relevant information from log files and do some analysis. I've bumped around and found my way to some functional solutions, but have a sneaking suspicion there are more efficient approaches. I will outline my current process with the 4 basic steps:   1. Clean up the source data: In the more involved scenarios I have a text file that is generally some sort of CSV variant. "Generally" because it might require a first pass to clean up outlier situations before I can effectively use the CSV module.    2. Write clean data to temporary text file: After cleaning up each line, I write the line to a fresh text file.   3. Read in clean formatted temp text file using the CSV module: I've assumed that reading the data in using the standard CSV module would be reasonably efficient method and ideal because then I can easily extract values from specific columns in each line.   4. Extract relevant values: Now I can easily traverse the whole file grabbing relevant data. I append the data to lists which I use to do the actual analysis.  The big red flag for me is that I'm traversing all of my data so many times. Maybe I should spend more time trying to find patterns in the data so I can extract the important values on the first pass? Also with larger logs (20,000+ lines) one of my scripts takes 15-30 seconds. That seems rather slow. What are areas of optimization? Be it a modification of the current design, or a completely different approach.


SaaS maturity level 2, how i can build configurable SaaS?(Technics and patterns)

According SaaS maturity model a SaaS is level 2 if is configurable, but how i can get started in this concept?how patterns and Technics, i can use to enable my SaaS?


Where has Cloud Computing gone?

I have been hearing about this term for close to 5 years now. I have read about services from Microsoft (Azure), but I have never saw it adopted in the mainstream usage. The thing I am trying to understand is this:   1. What happened to cloud computing? Is the infrastructure at present insufficient to implement this?   2. Is it still in its infancy?   3. Is it being used in other forms, like all the services Google seems to provide (plus Plus Google OS, etc)?   4. If it has failed, then why?


Creating an automated test framework for UI smoke testing

I am doing my thesis on the subject of automated UI testing at a company that applies continuous integration to their projects. The company builds intranets in Microsoft SharePoint 2013 and my task is to create an automated test framework that can be used on any project as a smoke test, and that integrates with the continuous integration model. The company uses Team Foundation Server 2010 and Visual Studio 2012. All the builds are done on a separate build server that is specified in the build definition. I have set up CI for my own demo server, and I have access to a separate server that I intend to use as a Test Controller and Agent, that will run all the tests on the deployed projects. I have a few, perhaps not very clear, questions that concern this.   1. My idea is to write test methods using Selenium, and package them into a DLL-file that can be loaded to all new projects when they are set up. The tests will only apply to standard SharePoint UI's. Together with this I will include a `config.xml` that specifies which site is to be tested. I'm using Selenium with the standard unit testing tools of Visual Studio. Are there any other options that might be better suited for my intentions?   2. I have understood that I can specify DLL-files that contain tests in the build definition for TFS, would that be possible for the way I plan to write the tests, or does that option only apply to DLL-files that are created in the solution? If not, can I add them as a reference and expect them to be run by the testserver, assuming they match the pattern for test assemblies?   3. The company would like to let developers add in separate custom tests, and have suggested me to write the test framework in such way that they can implement an interface or something similar. They want to be able to write fully customized Selenium tests, and my thoughts on this is that it would be easier just to let them add a separate DLL with their own tests and let the test server run them separately? Are there any other good ways of "merging" an existing test suite with custom written tests?


Embedding XACML PDP?

I need to implement a flexible Access Control system for a framework used by a couple of .NET applications. I have looked into Attribute-Based Access Control (ABAC) and XACML and this seems to provide the necessary flexibility to make decisions not only based on the user identity, but also on information about the requested resource. Typicial scenario where I need this: > Allow access to patient files only to doctors who are assigned to the > patient. However externalizing the authorization to a third party provider or another PDP server because would mean a network call every time the PEP (the application) performs an action that has to be authorized. **Does it make sense to use XACML with an embedded PDP?** I.e. the application transforms authorization decisions to XACML requests, then calls an embedded PDP module with the request which resolves it, queries the DB for resource and policy information and generates a XACML response. Or is XACML only useful in distributed Access Control scenarios? Is it generally more useful to implement a custom access control system if I don't plan to externalize the decision making point?


Is it possible to go back to a previous statement c++

So I'm learning the basics with C++, and I've created a small text based shopping mall which asks the user if they'd like to buy an item. If the user responds with yes, or any variant of yes, it'll list an array of items, from which you can then type in the name of the item you want to buy and it'll say "thanks, you've bought x item, goodbye" and the program will stop. If you decide to put no, it'll say "you have selected no, are you sure you wouldn't like to go back and buy an item". If you put yes, it'll list the array of items again for you to select, however, what i'd like for it to do is to then 'abide' by the previous if statement (as if you were saying yes to the first question). Hopefully you catch what i'm on about! Thanks. EDIT: unsure what's so unclear about the question 'what i'd like for it to do is to then 'abide' by the previous if statement (as if you were saying yes to the first question).' I'm asking if it's possible to go back to a previous if statement that's mentioned earlier on in the code, however, I realise that it's probably not possible and I'm now trying to figure out another way of doing so. Thanks.


If this isn't a user story, what is it?

I'm with an org that is trying to transition to Agile. One thing that I've been struggling with is what they call user stories. In my experience, a user story would be this: > Use should be able to accomplish task x using tool y During the sprint, we'd then design a solution to enable this. However, this is what we're writing: > User should click on button A to go to page B to read text C where they will > then select option D which will then redirect them to page E. Data F will be > saved to the database. To me, this reads as a solution, which is what the sprint is for. Are the scenarios where the latter is actually a proper user story? Or, if not, is there a proper term for that type of detailed "solution description" within an Agile process?


Important non-technical course for programmers?

What kind of non-technical training course do you suggest for a programmer? Example could be public speaking course, presentation skill, English, business writing, or anything not related to programming or software engineering itself.


Where does the git flow release message go?

When creating a release with git flow like:               git flow release finish <branch_name>      I'm prompted for a release message. I grepped around to see where this go, but no succes. Any idea?


Refactoring obscurely commented code

In refactoring code, I came across code that had comments. Looking closer at the comments, I could see that the code was clearly not doing what the comments said. **Without access to the coder nor documentation** , and without clear direction regarding the code (i.e. defects as to the fact that the code is operating incorrectly), is the best practice to assume that the code is correct, and clean up the comments?


Is there any evidence that drugs can actually help programmers produce "better" code?

I just read this quote from Steve Jobs: "Doing LSD was one of the two or three most important things I have done in my life." Also a quote from that article: > He was hardly alone among computer scientists in his appreciation of > hallucinogenics and their capacity to liberate human thought from the prison > of the mind. Although **I am aware of the fact that Jobs was not a programmer** , this quote got me thinking if there's any evidence to support the theory that drugs can help make a "better" programmer.   * Has there ever been a study where programmers have been given drugs to see if they could produce "better" code?   * Is there a well-known programming concept or piece of code which originated from people who were on drugs? EDIT So I did a little more research and it turns out Dennis R. Wier actually documented how he took LSD to wrap his head around a coding project: > At one point in the project I could not get an overall viewpoint for the > operation of the entire system. It really was too much for my brain to keep > all the subtle aspects and processing nuances clear so I could get a > processing and design overview. After struggling with this problem for a few > weeks, I decided to use a little acid to see if it would enable a > breakthrough, because otherwise, I would not be able to complete the project > and be certain of a consistent overall design[1] There is also an interesting article on wired about Kevin Herbet, who used LSD to solve tough technical problems and chemist Kary Mullis even said > "...that LSD had helped him develop the polymerase chain reaction that helps > amplify specific DNA sequences." [2] EDIT 2 Sadly the question was closed again but there was a great discussion on HackerNews. From HN user pchivers: > From what I understand there is only one study on the relationship between > creativity and LSD: Psychedelic agents in creative problem-solving: a pilot > study. Harman WW, McKim RH, Mogar RE, Fadiman J, Stolaroff MJ. Psychol Rep. > 1966 Aug;19(1):211-27. http://en.wikipedia.org/wiki/Psychedelics_in_problem- > solving... The results suggested that LSD has a positive effect on creative > problem solving. I think it is a shame that no follow-up experiments have > been conducted.


How to deal with a CEO making all technical decision but with little technical knowledge?

Question posted anonymously for obvious reasons. I am working in a company with a dev group of 5-6 developers, and I am in a situation which I have a hard time dealing with. Every technical choice (language, framework, database, database scheme, configuration scheme, etc...) is decided by the CEO, often without much rationale. It is very hard to modify those choices, and his main argument consists in "I don't like this", even though we propose several alternative with detailed pros/cons. He will also decide to rewrite from scratch our core product without giving a reason why, and he never participates to dev meetings because he considers it makes things slower... I am already looking at alternative job opportunities, but I was wondering if there anything we (the developers) could do to improve the situation. Two examples which shocked me:   * he will ask us to implement something akin to configuration management, but he reject any existing framework because they are not written in the language he likes (even though the implementation language is irrelevant). He also expects us to be able to write those systems in a couple of days, "because it is very simple".   * he keeps rewriting from scratch on his own our core product because the current codebase is too bad (codebase whose design was his). We are at our third rewrite in one year, each rewrite worse than the previous one. Things I have tried so far is doing elaborate benchmarks on our product (he keeps complaining that our software is too slow, and justifies rewrites to make it faster), implement solutions with existing products as working proof instead of just making pros/cons charts, etc... But still 90 % of those efforts go to the trashbox (never with any kind of rationale behind he does not like it, again), and often get reprimanded because I don't do exactly as he wants (not realizing that what he wants is impossible).


Are Calls to a WCF Service via JSONP Secure?

I am looking at developing a complete `HTML5/JS` mobile app that can be deployed to Android, iOS and Windows platforms. I am using `DevExtreme` tools to help me do that. I already have a WCF service that serves me with everything I would need for this app. I want to reuse the same and found out how I could use JSONP (since I would be doing cross domain calls) and GET calls to get result from my service. I have implemented the service and have started using the same. I am now second guessing my approach. Is it safe enough to use JSONP calls for all service requests? Especially for things like user authentication, If I send the username and Password over the URL is it safe? I have the service calls secured using SSL but does it really help? If not, what would be a more standard way to do it? ****UPDATE:**** Another issue that I ran into was sending special characters in the GET JSONP call. Something like '\' or '*'. `EncodeURI()`, `EncodeURIComponent()`, `escape()` neither would owrk for these characters. I always got errors for the same and assuming the users will have secure passwords with special characters in them, the whole concept of using GET with JSONP seems to be useless


NoSQL use cases

I am developing an application for my universities student research symposium around the idea of polyglot persistence. I have read Martin Fowlers book and done some other research online about the verious different types of NoSQL db's. I am curious as to what the different use cases are for the different NoSQL databases? Currently I have what Fowler has pointed out (other research was mostly done into API's). Key/Value:   * session data   * user profile   * shopping cart   * basically anything that has a single unique key that can be easily generated and replicated Document:   * event logging   * CMS/blogging   * e-commerce (after the transaction has been completed)   * web analytics Column Family:   * event logging   * CMS/blogging   * counters   * expiring usage Graph:   * connected data   * location based services   * recommendation engine So what other use cases are there? More specifically what are the use cases for each type of NoSQL db that are better than a relational model?


How to prepare for rewriting an application's glue

Assume you have a project that (in your opinion) is mostly decently well written, modularized, etc. and you want to keep much of it's functionality. However, an essential portion of this project is not well designed, and it can't easily be fixed with minor changes. The only way to fix it is to rip out a lot of the code; it's not so bad that you need (or should) start from scratch, but it's very pervasive. Assume that the code is something like 20,000 lines of non-whitespace, non- single curly brace, non-comment Java, C++, C#, PHP or Ruby code. You estimate about 2000-3000 lines need to be thrown out or changed. In the case of something like Java or C#, one of your packages/namespaces will probably be entirely rewritten from scratch, and many of the references to those classes will change. Here's the challenging part: the code that needed to change was the GLUE within the system. Here's a very simple picture that summarizes the problem: ![enter image description here](http://i.stack.imgur.com/bdhY9.png) This is the situation I was in that led to this question: What should I do when I've already waited too long between commits? As you can see, it's not only the parts of the code that were doing the internal processing, but also the parts that were communicating with the other parts of the system. Both the APIs and the internal data structures were insufficient. Attempting to keep both sets of APIs working for incremental changes would have been woefully redundant. I, of course, branched before I did anything, but every change I made produced a product that simply did not work. In many cases I created compile errors. This led to me continually putting off commits, because I thought "yes, I wired these pieces back together, but I still need to implement this other new interface, write this essential functionality, etc." This resulted in the cardinal sin of not checking anything in, a mistake I'd prefer not to repeat should I be in this situation again. This was mitigated by the fact that all my APIs were internal, except that I had to conform to the APIs of the outside world and third party modules, but my wrappers to those sections were changing. One obvious alternate solution would be to just accept the fact that each change will result in a broken overall product, but since you're checking into a branch, it's okay. Especially since I am the only developer working on this code and using these APIs. So maybe that's the right thing to do. Or maybe the right thing to do is try to first refactor the API to the new one, without actually changing the functionality (if possible), even if some arguments are dummy or will eventually be removed, and then incremental changes are a lot more self contained. Or maybe there's a better way entirely?


How to reconstruct this application using design pattern

I am engaging in redesigning a linux c++ server application. The application acts as file relayer in the form of receiving file packets (incuding control packets and data packets) from client A, writing these packets into a local data file then create and update index file, finally start many threads to read the file data and forward these data packets to its receivers such as client B, client C, client D, etc. Flow chart is like: Client A -> Server -> Client B, Client C, Client D, ... Currently the application is using Producer-Consumer pattern to pass data packets among modules, here are some modules we have: SocketModule(contains a thread for listening and reading incoming data of all sockets), SessionModule(for managing user tcp sessions), FileRelayModule(contains many threads for doing jobs like processing incoming packets and writing into local data file, reading local data files and updating index files and forwarding these data packets to receivers via TCP sockets). The problem is that its performance is so bad, take an example, it takes about 15 minutes for Client A to send a file of size 200M to Client B, but I did a p2p file sending and receiving between different machines it takes only 20 seconds. We think the main cause of bad performance is that we store sockets information in a global std::map, then every thread who wants to send out data (to clients) needs to wait for the lock for std::map, thus the application acts like single-threaded application. As the original design of this application doesn't follow principles of design pattern and this results in many issues, so we want redesign it using MVC pattern, adding roles of thread manager and file manager. The first item I think of is to use a ThreadPool, then dispatch every accepted socket into the thread who has the least clients(sockets number). Is this possible or reasonable for this application? What would you do if you were the designer of this project? **[update]**   1\. I will check the project and figure out which part is the real bottleneck of performance   2\. No matter which part is the real bottleneck, we need to reconstruct the application for it to manage the resources such as threads and memory and be easy to maintain. I am gonna do things like following:   1\. Create many classes: CSessionManager for managing tcp session data (contains a thread), CFileManager for doing file relaying and managing all data files and index files (contains a ThreadPool with 32 threads of which contains a sockets map, and a listening socket), CFileServer(contains the CSessionManager and CFileManager). Here CFileServer acts as Controller, the CFileManager acts as Model.   2\. The CFileManager will create a thread pool with 32 threads initialized at the startup. The CFileServer creates a listening socket and puts every accepted socket to CFileManager where the the new accepted socket is set to a thread in the threadpool by querying who has the least sockets. **[update2]**   The threadpool will be designed as following(is it reasonable?):                              std::list<CThread*> workers;                    //each thread would be                    class CThread{                        public:                           PostMsg(CMessage*);                          static void Run();                         private:                          map<int, socketinfo*> sockets;                          std::deque<CMessage*> messageQueue;                    };                         ...                    Other objects will call PostMsg to inform message                    to this CThread and in the run function:                    void CThread::Run(){                          ....                          while(1){                              ....                              //firstly process all messages                              //these messages includes adding socket,                              //deleting socket, or go offline                              CMessage* msg = messageQueue.pop_front;                              if (msg != NULL) {                                 process(msg);                              }                                   //after processing the messages,                              //now read/write the sockets data                              //set readfd and writefd                              ret = select(max, readfd, writefd, NULL, timeout);                                   //now process readfd and writefd                              //read data from readfd, then write to local                               //file read data from local file then write                               //to wirtefd or post a message to controller                             // to remove fd from array.                              ......                          }                    }


What do you call this pattern/technique?

Lately I've used this technique a few times, and I'm trying to figure out if it has a name, if it's one of the patterns, etc. In complicated situations where I might normally have a number of giant select case statements, I've been experimenting with a more plugin-style approach. I create an interface, let's called it IProblemHandler, and maybe that interface exposes a property enumerating the kinds of problems it can handle (IProblemHandler.HandledProblems), or even better, maybe the problem it handles is embedded in the class name - convention over configuration. Then, instead of a select case statement, I call some code that reflects through all the classes in a certain assembly and pulls the ones that implement the interface, then it determines which one is appropriate for the problem at hand, instantiates it, and solves the problem. In the past I've used it as a plugin architecture, but it's turning out to be really useful as a way to handle certain kinds of complexity. It seems like maybe this is the domain of IoC containers and so on. I know the managed extensibility framework does some of this stuff. So... Do you know of a name for this sort of thing?


Why don't schools teach about bad code?

I realized there could be a lot of bad code in a system while writing Java. I wonder why schools don't teach what programming practices are bad. For example, in Java, using a big try/catch block that catches `Exception` is bad, but no one told me. And we see the typical "String + String" concatenation appear in every corner of a program. Isn't it the job of schools, assuming most programmers are taught at a school and not self-taught, to warn students away from the pitfalls in a programming?


Do / how do the various flex frameworks work with Flash Builder

I have been reading about various Flex frame works, Robot Legs, Swiz, Cairgnom (spelling error) and a few others. What I am missing is how they actually work with Flex / Flash Builder. Are they simply libraries that you can use with the Flash Builder IDE? Why should I learn to use one of them instead of just using the IDE as it is?


Benefits of EJBs over POJOs for Jersey JAX-RS Resources

I'm writing a Jersey 1.9 JAX-RS application. I have to use 1.9 because it's the only supported version. I'm trying to decide if there is any benefit to using EJBs as my Jersey Resources, rather than POJOs. My Resources are strictly for my REST API; they delegate to my business service EJB as soon as the domain translation is complete. At present, I'm leaning towards POJOs because it's simpler and I only have a single EJB lookup for my business service that I can centralise in a single utility Class. Either way I'm going to have to do an InitialContext lookup, either for my business service from my JAX-RS Resources, or for the (potentially) EJB Resources from the Jersey Application Class. Is there any performance or architectural benefit to using EJBs as my Resources given that the only thing using them is the Jersey servlet?


Is it better to draw my own graphics or import images?

I am about to start a Tetris clone using Java as my programming language. While I was designing how it'd be done, I've stumbled upon this question: What would be better, if any difference at all, regarding performance 1, to draw my game? For a matter of simplicity, I will use a background grid as an example. The following code will be running in the graphics update loop: 1) To perform the drawing using my `graphics g` variable, such as this               g.setColor(Color.DARK_GRAY);                                                            for(int x = 0; x < COL_COUNT; x++) {                                                        for(int y = 0; y < VISIBLE_ROW_COUNT; y++) {                                                g.drawLine(0, y * TILE_SIZE, COL_COUNT * TILE_SIZE, y * TILE_SIZE);                     g.drawLine(x * TILE_SIZE, 0, x * TILE_SIZE, VISIBLE_ROW_COUNT * TILE_SIZE);         }                                                                                }         or 2) pre-load an image like this:               BufferedImage img = null;     try {         img = ImageIO.read(new File("grid.jpg"));     } catch (IOException e) {     }      and then use my graphics to draw it using Graphics drawImage:               g.drawImage(img, x, y, null)      1 \- _I know that a Tetris game isn't that performance-hungry, but I believe that this doesn't invalidate the question._


How to get rid of fear of not able to solve complex program?

Whenever I start to solve some complex problem and try to solve it by program. I feel demotivated. Instead of feeling excited about it I feel like I wont be able to solve this program its very difficult. I know I can solve it but because of these feelings its takes long time to solve it. Whenever I get a change to solve some tough problem this fear will come to my mind and it will stop me from thinking or will tell me you wont be able to do this etc. This fear has taken over me since long time. I know this is psychological fear but it disturbs me a lot. It stops me from becoming the best programmer I always wanted to be. Please help.


How to add contributors to LICENSE file?

I am the main developer of a library, licensed under the MIT license, and hosted on Github. The Github repository includes a LICENSE file. When someone sends me a pull request, do I have to list those as copyright holders in the accompaning license.txt, or should I list these in a special section there? Am I required to do it? Can I assume, that contributors agree to include their code with the license specified in LICENSE, when they send a pull request?


Which statically typed languages support intersection types for function return values?

> **Initial note:** > > This question got closed after several edits because I lacked the proper > terminology to state accurately what I was looking for. Sam Tobin-Hochstadt > then posted a comment which made me recognise exactly what that was: > programming languages that support intersection types for function return > values. > > Now that the question has been re-opened, I've decided to improve it by > rewriting it in a (hopefully) more precise manner. Therefore, some answers > and comments below might no longer make sense because they refer to previous > edits. (Please see the question's edit history in such cases.) Are there any popular statically & strongly typed programming languages (such as Haskell, generic Java, C#, F#, etc.) that support intersection types for function return values? If so, which, and how? (If I'm honest, I would really love to see someone demonstrate a way how to express intersection types in a mainstream language such as C# or Java.) I'll give a quick example of what intersection types might look like, using some pseudocode similar to C#:               interface IX { … }     interface IY { … }     interface IB { … }          class A : IX, IY { … }     class B : IX, IY, IB { … }          T fn()  where T : IX, IY     {         return … ? new A()                    : new B();     }      That is, the function `fn` returns an instance of some type `T`, of which the caller knows only that it implements interfaces `IX` and `IY`. (That is, unlike with generics, the caller doesn't get to choose the concrete type of `T` -- the function does. From this I would suppose that `T` is in fact not a universal type, but an existential type.) **P.S.:** I'm aware that one could simply define a `interface IXY : IX, IY` and change the return type of `fn` to `IXY`. However, that is not really the same thing, because often you cannot bolt on an additional interface `IXY` to a previously defined type `A` which only implements `IX` and `IY` separately. * * * > **Footnote: Some resources about intersection types:** > > Wikipedia article for _"Type system"_ has a subsection about intersection > types. > > Report by Benjamin C. Pierce (1991), _"Programming With Intersection Types, > Union Types, and Polymorphism"_ > > David P. Cunningham (2005), _"Intersection types in practice"_, which > contains a case study about the Forsythe language, which is mentioned in the > Wikipedia article. > > A Stack Overflow question, _"Union types and intersection types"_ which got > several good answers, among them this one which gives a pseudocode example > of intersection types similar to mine above.


Modules and themes

A module is a collection of files that together build a feature. A feature could be a login, viewing a User profile etc. A theme would contain template files and assets (img, css etc). The problem is how these will work together, say a module has been created and it does exists different themes, I am not interested in having to make template files specifically for a module, how can this be accomplished in a flexible way of still having a decent look. One way could be to use template inheritance, this way the User would only need to make one template file to have the module customized by the look. Anyother ideas on how this can be done?


Should we be completely honest to our clients about a time frame for a project?

I have been having this experience for sometime now, when a client needs a software product and contacts me, the client usually wants to know the time frame on which this product will be accomplished. Usually as a software developer I might not be able to fully determine how long it will take me to finish the job since I may encounter an error that may take me weeks (sometimes months) to solve. If I tell the client the expected time frame based on my analysis i.e. no matter how bad it gets, I should be able to finish the job in lets say 6 months maximum (for example). My client usually says NO! six months is too long, I need it urgently, maximum should be one month. If I refuse to accept the time frame given by the client he may give the contract to another developer who accepts the short time frame of the client and yet does not execute the job in time. On the other hand, if I accept the short time frame of the client and get the contract (knowing fully well that it will be impossible to finish it in time), I will only succeed in getting the contract and then later come up with excuses as to why the job is not completed in time. This now seems to be a norm, but deep down I feel I am learning how to be dishonest in order to get contracts. So is it a bad thing or is it just a business strategy?


Architecture of a "website generator" web application

What is the most maintainable and efficient way to architect a web application who's purpose is to host and generate websites which can be customized to a certain degree? There are a lot of these style of applications in the wild that generate all kinds of sites, from sites that host World of Warcraft guilds to other sites that do wedding site hosting. My question is, what is the basic architecture that these sites operate on? I imagine there are two ways of thinking about this. A central set of code that all sites on the host run against, and it acts differently based on which site was visited. In this manner, when the base code is updated all sites are updated simultaneously. Or, the code for an individual site exists in a silo, and is simply replicated to a new directory each time a site is created. When an update needs to be applied, the code is pushed out to each site silo. In my case, I am working in PHP with the CodeIgniter framework, however the answer need not be limited to this case. Which method (if any) creates a more maintainable and efficient architecture to manage this style of web application?


Better way to search for text in two columns

Here is the scenario. I am making a custom blogging software for my site. I am implementing a search feature. It's not very sophisticated - basically it just takes the search phrase entered and runs this query:               $query="SELECT * FROM `blog` WHERE `title` LIKE '%$q%' OR `post` LIKE '%$q%'";      Which is meant to simply search the title and post body for the phrase entered. Is there a better way to do that, keeping in mind how long it would take to run the query on up to 100 rows, each with a post length of up to 1500 characters? I have considered using a LIMIT statement to (sometimes) restrict the number of rows that the query would examine. Good idea?


Any news on the Next version of WPF?

I've heard of Silverlight 5 from Microsoft. But what about WPF? Is Microsoft planning to discontinue WPF or will there be a new version? We just switched from winforms to WPF and now another transition is going to be tough. Please point me with any links with information on the next version of WPF. Thank you.


Should experienced programmers know database queries?

There are so many programmers out there who are also an expert at Query writing and Database design. Should this be a core requirement to be an expert programmer or software engineer? Though there are lots of similarities in the way queries and codes are developed, my personal opinion is, **Queries** seem to have a different _Structure_ than **Code** and it can be tough to Master both simultaneously due to the different approaches.


svn usage advice

I need an advice about SVN usage. I use Tortoise SVN on my client to deal with a project I am working on. The probjem is that I have two set of bugs top fix on the project. One to deploy till 5 days, and one to deploy till 10 days. I am going to solve all the bugs before the 5fth days but I do not want to deploy the last 5 before the release date (till 10 days). How can I work on two separate codes and the merge all the modification? Is it possible? I have to create a branch?


What's a good way to store/load a word list with thousands of entries?

I'm working on a project that requires a simple dictionary for checking spelling; it will be large, but will lack definitions. The solution we're currently working on has the base word list in a text file, and customizations (extra words, excluded words) in the DB. The entire list needs to be loaded (best cached I think) for paginated display and customization using an existing JS widget, so what's the best way to store and load the base word list? My initial thought was to have a text file with one word per line and write my own loader and cache object, but my boss suggested using a ResourceBundle to leverage the built-in caching. I'm thinking that could be done by using the words as keys with empty values and using the keyset of the bundle. What would be the best solution to this?


Is randomly refactoring code allowed in scrum

Background   * My team uses scrum   * I have currently no task assigned   * There are no more pending task in the backlog   * Today is Labor Day for my client. Not having many things to do today I wanted to start refactoring some code I keep on seeing in the project I am working on, but currently I am not assigned to any sprint task to do any large scale refactoring. Is it OK in **Scrum** if I start randomly refactoring code that I have and have not written that always bother me but don't have time other days to fix it because of other days assignments? What about other days that I have spare time between sprints. I actually do and believe in continuous refactoring. I always do it on the pieces of code that I am working when assigned a story but what about some other code I see that is not currently related to what I am working on at that moment?


necessary to migrate to Web API from MVC controller

Since the released of Web API, I've been wondering whether it's necessary or helpful to migrate/change MVC controllers to use Web API calls. Since it's hard to describe code I'll show an example of what I mean: Current controller, the `_userService` is basically the `Business` layer of the application that is then calling the repository and getting all users.               [HttpGet]     public ActionResult List()     {         var list = _userService.GetAll();         if(list.Any())             return View("List",list);         return View(list.ToList());     }      Would it be better to use Web API, and get the list of the users as JSON object and then bind it to the view with some JavaScript? (possibly knockout if applicable). Not sure if my question is clear enough, so let me know if I have to explain something.


Unit-Tests and databases: At which point do I actually connect to the database?

There are answers to the question on how test classes that connect to a database, e.g. "Should service test classes connect ..." and "Unit testing - Database coupled app". So, in short let's assume you have a class A that needs to connect to a database. Instead of letting A actually connect, you provide A with an interface that A may use to connect. For testing you implement this interface with some stuff - without connecting of course. If class B instantiates A it has to pass a "real" database connection to A. But that means B opens a database connection. That means to test B you inject the connection into B. But B is instantiated in class C and so forth. So at which point do I have to say "here I fetch data from a database and I will not write a unit test for this piece of code"? In other words: Somewhere in the code in some class I **must** call `sqlDB.connect()` or something similar. How do I test this class? And is it the same with code that has to deal with a GUI or a file system? * * * Edit: So far there are some nice answers but I have the feeling that I have not made myself very clear. One final approach: I want to do Unit-Test. Any other kind of test is not related to my question. I know that I will only test one class with it (I so agree with you Kilian). Now, some class has to connect to a DB. If I want to test this class and ask "How do I do this" many say: "Use Dependency Injection!" But that only shifts the problem to another class, doesn't it? So I ask, how do I test the class that really, really establishes the connection? Bonus question: Some answers here boil down to "Use mock objects!" What does that mean? I mock classes that the class-under-test depend upon. Shall I mock the class-under-test now and actually test the mock (which comes close to the idea of using Template Methods, see below)?


How to create better OO code in a relational database driven application where the database is poorly designed

I am writing a Java web application that consists mainly of a bunch of similar pages in which every page has several tables and a filter that applies to those tables. The data on these tables comes from an SQL database. I am using myBatis as ORM, which may not be the best choice in my case, since the database is poorly designed and mybatis is a more database oriented tool. I am finding that I am writing a lot of duplicate code because, due to the database's poor design, I have to write different queries for similar things as those queries can be very different. That is, I cannot easily parametricise the queries. This propagates into my code and instead of populating rows on columns in my table with a simple loop I have code like: get _A_ Data (p1, ..., pi); get _B_ Data (p1, ..., pi); get _C_ Data (p1, ..., pi); get _D_ Data (p1, ..., pi); ... And this soon explodes when we have different tables with different columns. It also adds to the complexity the fact that I'm using "wicket", which is, in effect a mapping of objects to html elements in the page. So my Java code becomes an adapter between the database and the front end, which has me creating a lot of wiring, boilerplate code with some logic intermingled in it. Would the correct solution be wrapping the ORM mappers with an extralayer that presents a more homogeneous interface to the db or is there a better way to deal with this spaghetti code I'm writing? EDIT: More info about the database The database holds mainly phone calls information. The poor design consists of: Tables with an artificial ID as primary key that has nothing to do with the domain knowledge. No unique, triggers, checks or foreign keys whatsoever. Fields with a generic name that match different concepts for different records. Records that can be categorised only by crossing with other tables with different conditions. Columns which should be numbers or dates stored as strings. To sum it up, a messy / lazy design all around.


Is printing to console/stdout a good debugging strategy?

Let's say we have a function like this:               public void myStart()     {         for (int i = 0; i<10; i++) myFunction(i);      }               private int myFunction(int a)     {              a = foo(a);         a = bar(a);         return a;      }          private int foo(int a)     {         //do something here              //something gnarly here              //etc         return aValue;     }          private int bar(int a)     {         // do something here         //return aValue;     }      Now for whatever reason, our code isn't working. Perhaps it's throwing an error, perhaps it's returning the wrong value, perhaps it's got stuck in an infinite loop. The first thing any first year programmer, is print to console/std out, (having learned how to print Hello World before learning to use a debugger). For example to debug this code they might do the following:               private int myFunction(int a)     {         print("before foo: a=" + a);          a = foo(a);         print("before bar: a=" + a);         a = bar(a);              return a;      }          private int foo(int a)     {         //do something here         print ("foo step1: a=" + a);               //something gnarly here         print ("foo step2: a=" + a + " someOtherValue="+ someOtherValue + " array.length= " + someArray.length());          //etc         return aValue;     }          private int bar(int a)     {         // do something here         //return aValue;     }      Now they run the code, they get a big console print out, which they can go through to trace where things are going wrong. An alternative of course, is to set breakpoints and step through the code at each point. One major advantage of printing to console, is that the developer can see the flow of the values in one go, without having to click through steps etc. But the disadvantage is, your code is then riddled with all these print statements that then need to be removed. (Is it possible perhaps to tell the debugger to print only certain values out to a log?, the breakpoints can then easily be added or removed without actually modifying the code.) I do still use console printing as a primary debugging method, I'm wondering how common/effective this is in comparison to something else out there.


How do I (php developer) work with an asp.net developer?

I'm a php developer working on a startup, and my friend, my partner(a developer also), who is building the startup with me, is an asp.net/C# developer. How do we work together collaboratively, as we program in two distinct languages? I know you can use Mono http://mono-project.com to design android applications, (which is java based) by writing C# codes and iOS. Is there any platform or framework we can use to create php apps by writing codes in C# or a framework that can convert C# codes to php, just like Mono?


How to Ignore Bracketing Style in Code Comparison / Diff

How to ignore bracketing styles when doing code comparisons or diffs? We have several formats of bracketing and I would like:               function foo(){     }      to be considered the same as               function foo()     {     }      Right now I use Araxis merge which does a direct line-by-line comparison and we are getting a lot of "false positive" changes.


Is a data service API a good idea?

We currently have a monolithic Rails application that is really three separate applications that make use of the same data. In trying to figure out how to properly compartmentalize and break the mono-app into smaller pieces, it seems apparent that we need to have a central data service that the various pieces can communicate with, because I don't want to have to redefine a model layer for each application and/or copy models between the various applications (DRY). The idea is that since the database/persistance (including concepts like validations) are going to be the same for each component, it would make sense to have a service that can be used to query for data and create/update/delete it. What I'm picturing is essentially a JSON API that sits between the database and my application layer. The API will not immediately be exposed to the "outside world" (although that may be something that occurs in the future); for now, it would just be communicated with internally (ie. to/from a public- facing Rails (or other) app). This API would essentially just abstract persistence logic.   1. Is this a good idea? Are there any pitfalls that I'm not thinking of?   2. If this is a good idea, does anyone know of a Rails ORM or a gem that can be used to coordinate this sort of endeavour? My vision is that once a data service is running, the actual Rails application wouldn't be using ActiveRecord anymore, but rather _something_ which would handle querying the data API.


What makes Common Lisp "big"?

I've been learning both Common Lisp and Racket, and one thing that I consistently hear is that Racket is a much "smaller" language than Common Lisp. I was wondering what this really meant. As far as I can tell, the syntax for Common Lisp isn't that much bigger than for Racket. Basically, I'm wondering what exactly about common lisp is bigger. Does it have more syntax that I just don't know about? Does it have bigger environments? Bigger executables? Bigger libraries? Or some combination thereof? Please, this is not a "which one is better" thread, I would just like to know exactly what "bigger" means.


Dividing monopoly streets in groups

I'm new to object-oriented programming, to java, and to programming in general, and as my first real project I'm trying to program the board game Monopoly. What I've got so far is an array that can store objects of the class _Square_ (which has various subclasses, like properties, the railroads, chance cards etc.). Player objects take turns in moving around on the board, calling a _landedOn()_ method for whatever square they land on. Properties can be marked with an owner, and thus this owner will receive money if someone lands on his property. Everything is going good so far, but there is one little thing that bugs me. I'm unsure about how to elegantly divide the houses in groups, or colors. There are a couple of groups of streets on the board, and you can only buy houses if you own all properties in the group. I can imagine how to program this, but the solution seems a bit dirty and "non-general" to me. How do I make a nice general solution? To clear up: I want to be able to check whether all properties of one type are owned by the same player, in a general way, so that if the groups are changed, a property is added, or changes group, etc., I would not have to change a lot of code.


What is a helper? Is it a design pattern? Is it an algorithm?

Maybe a little tongue-in-cheek, but as I can't find this answer anywhere through Google, so to ensure Programmers Stackexchange has the answer: **What is a helper?** I see the name being used everywhere (module names, class names, method names), as if the semantics were deep and meaningful, but in the context of Computer Science (although I don't have a degree in it), I've never seen a description or definition anywhere! Is it a design pattern? Is it an algorithm? I once worked on a program in which the module and class were both called _somethingsomethinghelper_ (where _somethingsomething_ was fairly generic too) and I promptly renamed it to something that made sense to me, but I feel like I'm missing something here!


Web Development: is there an oasis to the chaos?

I started my programming career a long time ago when I was 14 years old, and I started with a book by James Lee, suggested by a Unix Systems Administrator I met in Barnes and Noble. In a month I had digested that sucker, bought a set of carrier grade servers, and had an AMP stack running -- but never used PHP. The wonder of Perl absolutely captivated me, and I loved it. After learning everything I needed to know about HTML and hosting websites, and making that HTML content dynamic with Perl, and parsing input with regular expressions -- and, admittedly, that also included hacking a couple of HTML files with regular expressions, blissfully ignorant to grammars, let alone Chomsky hierarchies -- cutting my teeth on that stuff was _fantastic_ , especially after I learned to make money with it. It got better and better, but before long; alas, I discovered a new baby. Yes, the evil of the evil, C# and it occupied my attention for a very long time. Oh the _joys_ of static application development captivated me, and before long I had forgotten the whole motivation for me to program: it was no longer about money, but about the intellectual desire and will to hack at problems, and most importantly, make pretty much every single math problem my ... well, not so much. I got out of the whole thing and it wasn't too long before all these standards changed and a boxed website -- which was really never acceptable -- was absolutely positively, well, done. I worked in my field doing everything from botting apps to scraping html webpages regular expressions, and doing computer repair too. I wanted to do this for a living. So I went to college for it, B.S. Computer Science, yep, that's me. Junior year I found out that I was basically a math major, and lo I wasn't frightened because Computer Science reinforced the math and vice versa: I learned to appreciate the _same_ abstraction and formality that I absolutely **loathed** when I first cut my teeth with Perl -- "object orientation?! who needs it!" In a year I'm going to leave this school and seek employment in my field, and I've come to the crude and harsh realization that not _if_ but _when_ I go back out there, less blissfully ignorant of what it _means_ to compute, people are going to want me to develop webpages. I've dodged the bullet so far, but some of my peers haven't -- they seem to actually enjoy coding in the non- homogeneous, parse-html-with-regex, hack modules, PHP wonderland of rubbish and javascript, ..., **nonsense** that is all contained in that whole world. There's answers everywhere: "use joomla," "use wordpress," "heroku/ruby on rails," ..., all of which gets some of these people super excited. Perl is the outlier, and it is such a wonderful language. They're going to want me to make the logo their 8 year old drew in MS Paint look gorgeous when I get stuck trying to vectorize that sucker and plug it into a website and clean it up; they're going to want me to change specifications at every possible turn; and they're all going to want some PHP/ASP.NET nonsense to construct it. I'm just absolutely cringing at the thought of being made to develop websites, my brain is just `nop` sliding me into the financial dooms of programmer hell. I need to know how people at my level or higher console themselves into creating gorgeous and clearly well thought out websites. How do I start over and fall in love with website development, again? Is there a python `from website import awesome` utility or something that I can use? Where do I go? * * * Edit: I've read a lot of comments about this thread, and yes it is long, but I can't think of any material to cut -- I'm really trying to voice my frustration here. Let me clarify a few points though. I don't loathe object orientation, or PHP, and I sure don't have any problem with the more mathematical and formal portion of programming. As far as my math stuff, I'm up to snuff with it. It's funny that one of you mentioned quantitative finance because I have a client with a passion for futures trading; however, at the end of the day my company hired a programmer capable of generating gobsmacks of garbage code so it can be put on a website. To make matters worse, the magnitude of garbage code ... to put it in car terms, it is like riding in the passenger seat with a newly licensed 15 year old driver -- with a manual transmission -- somehow we all get to the grocery store. Yes it works, but the transmission is shot and I need a shower by the end of it all. Web development just seems, well, so unnatural. Going about writing a webpage is as painful for most programmers as reading this post: long, verbose, roundabout the point, and at the end of the day some clever parser figures out what it all means and puts the discombobulated mess into a format the browser can understand. Cheeky, right? Gears are ground down to stubs by the time Javascript lubes it all together. How verbose? Well, let's say that six Linux kernel have less code that your grandma's 6 page website at this point -- there's a Joomla module for that, but you have to have a commercial license to post more than 6 cat pictures at a time. Something as simple as email address validation can perhaps only be compiled into a regex (by the way, which totally is not a regex) by extended Perl compatible regular expressions -- and indeed, that thing is at least 3 pages long and would make a drunk Ken Thompson blush. The worst part of it all is that there has got to be way better languages and frameworks for doing this kind of work. I want round boxes and edges that are beautiful, but I don't want to have to hack in illustrator for half an hour to do it just so I can load it in some div that arbitrarily positions it, according to browser specifications, in a combination that not even Bruce Schneier could enumerate. I need closure, and the functional definition of closure would be nice, but no host will well-support anything but PHP -- assuming PHP can be well-supported in the first place. At one point I was hoping that C# would be my panacea, nope. Maybe I'm not getting a fundamental element of web design. I attempted to get involved in the middleware side of web development, but that didn't work either. A polyglot of perl, python, and some regular expressions later and I had scraped his webpage, only to have a Joomla module butcher my beautifully normalized table. Feel free to mercilessly edit my post at will. ## **Links** ClojureScript: http://himera.herokuapp.com/synonym.html   Dancer: http://www.perldancer.org/documentation