How to hide AOP implementation dependency without breaking encapsulation?

I have the concept of a `SlowLoading` thing:               public interface SlowLoading {       boolean hasLoaded();     }      I also have a component `MyComponent`:               public interface myComponent{       void doSomething();     }      My implementation covers both:               public class MyComponentImpl implements SlowLoading, MyComponent {        // omitted for brevity     }      I have a container (interface omitted for brevity) which returns `MyComponent`:               public class MyContainerImpl implements MyContainer{       @Inject private MyComponent component;            @Override           public MyComponent doSomething(){         // magic happens         return myComponent;       }     }      I also have an AOP component that intercepts the return of slow loading things and implicitly waits for them to load before returning:               @Pointcut("execution(SlowLoading+ *(..) )")       public void returnsSlowLoadingThing() {     }      However, at present the `MyContainer` method is not proxied, since the return value does not implement `SlowLoading`. What is the best way to encapsulate this behaviour? Options I've considered:   * Make `MyComponent` extend `SlowLoading`. This feels like a code smell and breaking of encapsulation - bleeding implementation into the interface. A client does not care if it is slow loading or not.   * Inject `MyComponentImpl` directly into my container and return it explicitly (co-variant returns). Again, this feels like it is breaking encapsulation and the point of programming to interfaces, but feels better than the above, since it is done at a lower level and hidden behind the interface (implementation detail). However it is breaking the encapsulation of the AOP functionality which should be orthogonal and transparent.   * Perform the AOP wait before invoking a method on a `SlowLoading` thing. This seems the most appropriate, but I've not been able to get this working so far.


Collaboration between a Graphic Designer and Expression Blend developer?

I'm new to the programming world and also a little bit confused. My brother would like to work with me on some program. I'm a graphic designer so he asked me for UI and all it's elements. I would really help him as much as it's possible so I have found Expression Blend for Visual Studio. At first it looked great but after few minutes I've started to understand that I totally don't know What to do with my project. Lets assume that I have already made an Interface. Even made in Blend. Now, how can I give it to him so he could implement the UI? How to export and how to give it to him. For example, He works on separate PC and I need to export the project and give it to him for implementation. I know everything about Graphic Design but nothing about coding. I know that he uses Visual Studio :) I have been working in a web company so my workflow was very easy. It was only to send well prepared PSD file. With Blend I don't know what's next after the design part is finished.


Decision for Unchecked Exceptions in Scala

As a java programmer, I have always been critical of Unchecked Exceptions. Mostly programmers use it as an en-route to coding easiness only to create trouble later. Also the programs (though untidy) with checked exceptions are much robust compared to unchecked counterparts. Surprisingly in Scala, there is nothing called Checked Exceptions. All the Java checked and unchecked are unchecked in Scala. What is the motivation behind this decision? For me it opens wide range of problems when using any external code. And if by chance the documentation is poor, it results in KILL.


A programmer should concentrate on at least how many languages?

For me I am C# and Java person. I find these 2 languages are quite similar so its easier for me to crossover each other. I'm not sure if its good idea to pick up other different languages. Any thoughts?


How to make Classic ASP interesting if you are stuck with it?

I used to work on a really small outsourcing company (4 programmers and the boss), then when the stress and the frequent long shifts made the situation unbearable I made the switch to a better paid job with a more relaxed schedule that allows me some more free time. The problem, however, is that for the most part, everything is coded in Classic ASP that interfaces with a custom made C++ queueing system that stores everything in AS400 systems. My boss used to be one of the developers that made the initial efforts towards this, and naturally won't ever approve a switch to another languages / technologies despite the increasing difficulty that represents developing today business needs with yesterday tools. I'm pretty much stuck coding with Classic ASP in the foreseeable future, and I'm struggling to find ways to make it at least interesting, as I used to work with .NET and Java previously, and I feel like I'm going backwards... Any advice?


How do I "hand over the keys" to a webserver I'm hosting?

I only have a verbal hosting agreement in place with a customer. Unfortunately the relationship has deteriorated to the point of no return, and I'd like to end the hosting agreement and hand them over the root password. This is a virtual dedicated server I pay for, and then they pay me. They are fine with this, but the problem is I don't trust this client even a little bit. Can I get them to sign something saying they release me from liability to changes made on the server once I give them the password? How is the root password usually given to clients who request it while making sure they don't come back later on and blame you for breaking the server? Does simply the act of giving them the root password infer that you are handing over complete control and thus complete responsibility?


Is it significantly costlier to fix a bug at the end of the project?

In a blog post by Andrew Hay, the following axiom was posited: > It costs significantly more to fix a bug at the end of the project that it > does to fix the same bug earlier in the project. However, this doesn't seem certain, especially after reading a blog post on Less Wrong, and the data I've seen to back it up is extremely old. Is this still axiom accurate today?


how to ask in the interview if the project is new development or maintenance?

How do you ask the potential employer in the interview if the project you will be working on is Support and Maintenance or new development? Last time in the interview I asked this question and I was told its a support + new development but it turned out to be support + enhancements. I don't want to make the same mistake again and get into something like this. Most of the time people interviewing will tell its a support + new development but thats not what it turns out to be after accepting the job. So what kind of questions will get the right answer if the project is really a new development or its just support and patching and hope it works kind of a project.


How do I pass a variable's value from one class into another? (C++)

I have a class ("Class A", we'll call it) which calculates the value of a private variable (which we can call numLoaves) with a public function. I need to use the value of numLoaves in a public function in Class B. What is the best and most efficient way to pass in this value? I'm new to programming and have been looking for a solution for hours with no luck. Note: The function in Class B is void and must be this way. I can't use global variables or objects, pointers, friend functions or friend classes. The variable must be private. Thank you!


Java serialization - advantages and disadvantages, use or avoid?

Serialization is used for persistence in Java. It may be okay to persist a few objects using serialization. But, for a large number of objects, ORM, Database etc might be better. It seems that serialization is useful only for small jobs. May be I am wrong. So please tell me what are the advantages of serialization over non-serialization methods ? When should it be used and when should it be avoided ? This question came to my mind after seeing DZone article Is Object Serialization Evil? And these are the lines that gave rise to my question: > If you look at Java and its session objects, pure object serialization is > used. Assuming that an application session is fairly short-lived, meaning at > most a few hours, object serialization is simple, well supported and built > into the Java concept of a session. However, when the data persistence is > over a longer period of time, possibly days or weeks, and you have to worry > about new releases of the application, serialization quickly becomes evil. > As any good Java developer knows, if you plan to serialize an object, even > in a session, you need a real serialization ID (serialVersionUID), not just > a 1L, and you need to implement the Serializable interface. However, most > developers do not know the real rules behind the Java deserialization > process. If your object has changed, more than just adding simple fields to > the object, it is possible that Java cannot deserialize the object correctly > even if the serialization ID has not changed. Suddenly, you cannot retrieve > your data any longer, which is inherently bad. > > Now, may developers reading this may say that they would never write code > that would have this problem. That may be true, but what about a library > that you use or some other developer no longer employed by your company? Can > you guarantee that this problem will never happen? The only way to guarantee > that is to use a different serialization method.


Can I create and publish an iPhone app by building it in a second hand Mac?

I have never published an app to app store. I have a chance to buy an apple mac from someone. Is it possible to use that to publish to app store? What if the first owner was also a developer? If I buy Mac with the only intention of publishing an app should I only go for a new one to get developer license or I can do it in a second hand Mac also?


In-house framework

Recently I graduated from university/college and immediately landed myself a job. The company has versions of software it gives to it's clients, however the software is largely, or rather entirely, built on an in-house framework. This in-house framework almost abstracts everything from the 'developer' in terms of lean Java code and instead provides helper methods for almost EVERYTHING. For example, creating a UI and interfacing with the back-end is done entirely on top of their framework using their 'API' if you will. My immediate thoughts are now - Do a year of experience and get out otherwise I will be locked in and too afraid to leave in the future. My questions are: Is this common practice in the industry? Will this stagnate my skills? Should I bail?


Writing your own framework or using an existing one?

I know there are similar questions to this one, and I've read most of them. Most of the answers to these questions are talking about "cost-effectiveness" and "time-saving" aspects of the frameworks, which are huge reasons in favor of using frameworks. I'm a pretty new .NET developer and I'm trying to learn stuff like WPF, MVVM, layered architecture design, dependency injection, logging, database access, test-driven development, and many more different technologies/techniques. Most of the resources that I find regarding such topics start with an extremely simple example to "show" why you should use given technology/technique, which honestly looks quite ok with that simple example, but **_doesn't really make sense for someone who didn't deal with real-world problems these technologies/techniques help with_**. After the simple example that makes me wonder what that specific technology/technique really solves, they usually go on and say "Hey, you know what, there's a framework for that called ..., let's just use it for the rest of the examples." Dependency injection? Just use Ninject. You want to fake stuff? C'mon just use Moq. MVVM? You're kidding me? just use MVVM Light Toolkit! Which is great, really. All these tools, I'm sure, make the life easier for all the developers out there. But my problem is,   1. I'm trying to use TDD, but I have never experienced the problems people experienced while they were developing stuff without TDD, which in the end made them come up with such a technique. I understand the concept behind, theoretically I can see why it was created, but in practice I am not experienced enough to see a code that would benefit from TDD. Because I haven't seen much.   2. I have never had problems developing a huge application that I needed to de-couple stuff and went "Oh my god! That is ridiculous! I need to find a technique so that I won't have this much trouble next time." and found out about "Dependency Injection". All the small things that I have developed so far worked fine without the need of dependency injection.   3. I have never written a WPF application that made me feel like things should be easier, presentation layer should be separate, there should be data binding. Hell, I haven't even written one WPF application! So all these things make me think like I am going to use all these tools, without experiencing first-hand any real world situation that cultivated the creation of them. But at the same time, I can't try to write a huge business application in WPF without using MVVM or a good layered-design and experience all the problems people experienced in the past to appreciate all these new technologies/techniques. Because there are people out there developing stuff, getting further ahead, releasing things that work. I'll be left behind because of my obsession with trying to learn everything out there to learn. And besides, **_these things are not easy to learn without first experiencing the problems yourself._** But then, at the same time I have those nightmares that I start working in a new company and people tell me "You can't code your own MVVM framework? You always need to use Prism? Hahahahaha!" and they go around pointing and laughing at me in circles. I feel like I'm a lesser programmer. I feel like I don't have what it takes to create a framework on my own. I feel like I am only able to put things together, which are created by other "better" people. I would like to ask all the experienced people out there, what strategies have you used throughout your career? Do you always use existing frameworks? Do you create pet projects to learn about why those frameworks exist? To make a long story short, what constitutes the thin line between using a framework and creating your own? And more importantly, how do you close the knowledge gap that automatically comes up if you use a technology/technique without seeing the real-world problems they help with?


How often have you switched stacks in your career? Has it hurt your career progress?

I started my career writing C#. However after an year I moved to Java and then after 6 months back to C# where I've been more around 3 years now. I strongly believe that although the basic principles do not change and are reapplied learning a new stack (and the supporting frameworks) is always a big investment. How often have you switched stacks in your career? Has it ever hurt your career progress? Do you like working with people who have worked on multiple stacks but have lesser knowledge of the respective stacks or with people who have worked on a single stack and have a deeper understanding of the ins and outs of it?


User friendly scheduling feature

I'm trying to add a scheduling feature to my web scraping application that will let the user schedule scraping jobs so he can, for instance, perform a job every Monday, or every 2 hours or stuff like that. On one end, I could make a very simple scheduler that let you pick a specific date and time and pick a time interval that would indicate how often to execute the job starting at the specified date and time. So if, for instance, I pick Dec 31 at 2:00 pm and choose 1 day as my interval, the job would run every day at 2:00 pm starting Dec 31. But what if he wants to run the job every Saturday and Sunday, or three times a day on Sundays? On the other end, I could embed some kind of scripting language that will let the user use any logic he wants, but this would be overkill for me and for the user. He _doesn't_ need to run a job every day of the month that is prime number or anything like that. So this is a common sense question, not a programming one. How would you implement this, or, do you know any similar kind of scheduling job in any other kind of application? I looked at the scheduler in my antivirus but this one is extremely plain and simple.


Using Subversion as an artifact repository vs a specific artifact management tool

TL;DR: Why use something like Apache Archiva or Sonatype Nexus as an artifact repository instead of Subversion? The build system I use currently has a lot of binary blobs (images, sound files, compiled binaries, etc), both as input and output to our builds. Our system for managing these is very ad hoc; some are checked into our Subversion repository alongside our code, some are stored elsewhere outside any formal version control. I'm looking at consolidating this, so we have something that's more self- consistent and easy to use, and which separates binary artifacts from code. Google tells me there are a selection of artifact repositories available (Archiva, Nexus, Artifactory, …), but from reading around, I can't see any advantage to using these over Subversion. That will look after the binaries for us – it already does that for some of our binaries, we'd just want to rearrange the repository layout to separate them from code – and has the notable advantage that we already have Subversion servers and expertise. So. What's the advantage of using a dedicated artifact management system over using a general version control tool like Subversion?


How to design website workflow?

I have been thinking about this for really long time without reaching an optimum answer. First of all, I'm a medical doctor who loves programming but never really studied it, except for home learning and lots of years of playing around with code in my free time. Currently I'm trying to build a small project to manage my clinic, to do that I started by created a list of options I want to be able to do. Example:   1. active patient record.   2. authentication with different roles (eg. patient,nurse,dr)   3. appointment schedule (include calendar to schedual vacinations/surgeries etc with a reminder)   4. allow doctor to create his own plugins.   5. dashboard for doctor to view his statistics Then I started with codeigniter/mysql/php/jquery and started coding. My steps during development:-   1. 1st database. ![enter image description here](http://i.stack.imgur.com/51QXJ.png) I started by creating all my tables that I will need.   1. Created all my models to handle these tables (1 master model that handle basic read/write/update/verify while also considering my table relations After that I start to code my views and controllers. I first created view HTML, then create controller that will handle this view, and started coding functions to make the view interactions work. Example when coding the appointment view(controller booking.php): ![enter image description here](http://i.stack.imgur.com/CM6BO.png) created this layout and made table td's clickable, when user click : jquery get (booking/add_patient_form) and pop it up when user save : post to booking/save -it save appointment then reload index() function etc.. and I continued same steps of creating view then its controller -that contain all the logic this view needed - to accomplish whole project. At the end I had all my target functions working fine, but since there was **no PLAN from beginning** and as the whole project was punch of brain storming and debugging with no what so ever plan, after I went so far in this project i find my self stuck with maintainability and flexibility! and unable to link them together. I have feeling that every page on website is completely isolated from other and I can't even recall how each page is loaded and what functions are inside without peeking! Is there anyway I can recover this and get a design out?


How does authentication work with ASP.NET (using Live ID and\or Windows Authentication)

I'm primarily a .NET desktop app programmer. Coming into the web world has been difficult. I'm trying to convert one of my Silverlight apps into HTML. But I'm having a hard time figuring out the authentication system. I'm trying to read up on Live ID authentication and Windows Authentication but I'm having a hard time putting it all together in my head. Perhaps you can help? # My App Framework My client application is a TypeScript (javascript) HTML page (or pages). And the server is a WCF Data Services REST API hosted in ASP.NET. The service works with a SQL database. # The Problems (Claims Based) When I look at something like Live ID authentication, it's known as claims- based authentication, right? So if I had this implemented correctly, someone comes to the website, I need to verify that they are logged in. How do I do that from a client-side HTML page? Do I have a recurring timer that is validating the login every 30 seconds or something? Or is that done server- side on each call to the service? I know that if they aren't logged in, I need to send them to the live login page, once they log in, the live page will redirect them to my server with the authorization token in the query string (or something like this). At this point though, what do I do 5 minutes down the line when they make a call to the webservice for data? Is that token sent on every call to the server some how? How do I validate that when they call the service, it is actually them? Do I have to wrap every service call in a ValidateUser() method or something? I have a user ID in the database that I would have to match with their user token somehow. # The Problems (Windows Authentication) The previous problem still exists here. How do I know that every call from the client is still them? Additionally though, I need to understand what do I do from the HTML side to the server side to authenticate them and then continue the authentication. # Conclusion I cannot really find any sort of explanation that conceptually explains all of this information and gives me the big picture of how it all works. I'm really hoping someone here can fill in these gaps and give me a better idea on how to implement the client and server authentication. Thanks! # Update I found a great book that really explains a lot of this. It's entitled "A Guide to Claims-Based Identity and Access Control". It's part of the patterns & practices series. Thanks to all for your answers and put me on the right track.


What advantages does developing applications for smartphones have over developing the same application as a web application?

Let's take the Facebook application as an example. Why did they develop an application when the users could just access to their page and do the same? For me that represents more maintenance and more cost because for each feature added to the web application that feature will have to be added to the smartphone application as well. So why would I want to develop more than once (for each patform iOS, Android, etc) when I could just have one web application? What benefits do I get? The only one that comes to my mind is GPS feature. **EDIT** : My question is more oriented towards business applications that are going to be used only by some members of the company, it's not about selling the application (private use). So contrary to what some answers say about that by developing as a smartphone application it will benefit from more sells because of the "smartphone stores" for me this point is not important because the application is for private use. By developing the application as a web application it means that it can be accessed through smartphone browser and also in a PC (any capable browser), but developing as a native application would limit this to only some kind of smartphone so we would be limiting the use. On the other hand developing it as a web application means that in order to access the application an Internet connection must be available. So keeping this in mind how would you convince your boss to write the application for a given smartphone platform (iOS/Android) vs developing it as a web application?


Tutorial dependency -- how to do I learn to code by myself?

Here's the thing: I have been learning to code in jQuery (not raw JS) and PHP for about 3 months now. During this time, I have learned a lot of different things, discovered how a web application is built, how web servers work, how databases work, and how I should really learn JavaScript rather than leaning on jQuery. But, I have found myself depending on tutorials and online guides to accomplish a given task; and this really affects my sense of accomplishment, so to speak. I'd never be content with myself, even after building the whole script, because someone had to point it out to me. Because I couldn't get it right by myself. Basically, I have no clue how to "begin" building something from scratch unless I see someone else's implementation first. How do I achieve such a mindset where I will be able to recognize which steps do I have to take in order to go about coding an idea, application, function, etc., without any need of tutorials or examining foreign code. How to move on to the next step, so to speak. TL;DR: How to stop depending on tutorials and write code without someone telling you what to do.


Retrieving hierarchy of tree-nodes stored in relational database

I have a hierarchical ADT that I want to store in a database. Nodes have exactly one parent element that is a node as well. Multiple nodes can have the same parent node. My current approach uses an adjacency list with a table structure similar to the following:               +----------------+------------------+------+-----+---------+----------------+     | Field          | Type             | Null | Key | Default | Extra          |     +----------------+------------------+------+-----+---------+----------------+     | node_id        | int(10) unsigned | NO   | PRI | NULL    | auto_increment |     | node_name      | varchar(255)     | NO   |     | NULL    |                |     | parent_node_id | int(10) unsigned | YES  | MUL | NULL    |                |     +----------------+------------------+------+-----+---------+----------------+ where parent_node_id stores other node_id values and cascades on update and delete. To display a node's hierarchy, I implemented a loop in my script that queries for the respective parent_node_id, which can result in 5 to 10 database queries for a node. This struck me as incredibly inefficient, but I am at a loss as to how to avoid this. From my limited understanding of the inner workings of relational databases, I have deduced that stored procedures is not necessarily the way to go, since the issue seems to be with my approach to how I am storing my ADT.   I looked at discussions on how to store trees in databases, but couldn't find anything that addressed my specific needs, which are:   * The integrity of the node hierarchy is important, which to me rules out storing the complete hierarchy in a column (Path Enumeration.)   * Whenever I retrieve a node, I will also need to query for it's complete hierarchy.


How to get rid of my "Factory" class' countless else if statements

This is a web application based on actionscript 3. I have all of my modules enumerated in a class, but I never know which modules actually come from database. Let's say I have 20 modules in my application, but the user only has access to 10 of them. All I get are 10 strings from database (the module names) whenever the user clicks a module this string goes through the twenty else if statements until it matches the enumerated value and then it is displayed on screen. Is there a way to optimize this? The modules are not flex modules per say, they are just lazy instantiated components.


algorithm to extract "possibilities" from a tree

From a given tree, subsequent trees have to be generated. Nodes can be marked as "variant" in the given tree (the example uses an asterisk to mark the node). All possible combinations between the variants form the resulting trees. From the following tree:               - Product         - Packaging *             - Small box             - Heavy box *                 - Eco                 - Non-eco         - Delivery *             - Standard             - Express      The following 6 trees should be generated:               - Product         - Packaging              - Small box         - Delivery             - Standard          - Product         - Packaging             - Small box         - Delivery             - Express          - Product         - Packaging             - Heavy box                 - Eco         - Delivery             - Standard          - Product         - Packaging             - Heavy box                 - Eco         - Delivery             - Express          - Product         - Packaging             - Heavy box                 - Non-eco         - Delivery             - Standard          - Product         - Packaging             - Heavy box                 - Non-eco         - Delivery             - Express      Is there an elegant algorithm for this (recursive solution)?


How to handle passing multiple dependencies in a module hierarchy

So I have my application consisting of a number of modules in a module hierarchy. Furthermore let's also assume each module is a class and we have a tree of classes where the classes at the top are using the classes below, to make it more simple. A `class A1` at the very bottom may depend on some input parameters. `class B1` is above `class A1` and is creating and using instances of `class A1`. Therefore it has to pass the dependencies needed by the instances of `class A1` into them. If it can't create these dependencies from some operations, `class B1` now has it's on dependencies but additionally the dependencies of `class A1`. The higher we go the more these dependencies will add up so that the toplevel `class` will need to know all the dependencies unless they can be created at a lower level. This means if `class A1` my program is dependent on the current `temperature`, I have to pass this to the toplevel `class` which then passes it to the next `class` and so on until it arrives at the very bottom in `class A1`. If I do that, I make the state explicit but it also means that I have methods or classes that take many parameters. **Variables** What if the `temperature` is may change while the application is running - is there a way to avoid passing it all the way down the class tree without giving away explicit state? How would you guys handle this? **Constants** What if the `temperature` is a constant that will never change while the program is running? Does this give us more options to avoid passing it always as an argument? I could see someone using a global configuration (singleton) but it will make it harder to test right? I could also pass not the `temperature` itself but a configuration object. This would mean `class B1` does not receive for example a `temperature` and a `airpressure` parameter but gets a configuration object passes it to `class B1` and `class B2` where `class B1` only needs the `airpressure` and `class B2` only needs the `temperature`. Is that a good approach? What are the pros/cons?


global try-catch in presentation layer

I have a 3-layered app structured as follows.   * Presentation Layer (ASP.NET MVC project)   * Business Logic Layer (Services for controllers in PL)   * Data Access Layer (Repositories) Each Controller in PL interacts with its service in BLL, which in turn has access to Repositories in DAL. Is it a good practice to do a "global" try-catch in the PL? That way if exception is thrown in DAL, for example, I can display the error message to the user. Or is there a better way to do this?


When would I use pseudocode instead of flowchart?

I'm a student working with various techniques of programming, and I've come across pseudocode and flowchart. I know that these are both used in order to think through the problem before actually programming, but I have a few questions with this.   1. When would I use pseudocode to plan out and when would I use flowcharts? Or is it better to do both before actually programming. Particularly for a small arcade sort of game in JAVA since that is my next project.    2. I've noticed that pseudocode is very similar to the actual code rather than flowcharts. Would this make pseudocoding better because you essentially copy/paste the pseudocode into your program (of course, you have to change it to fit the language. I understand that part).   3. Is it practical to use both of these while programming? Particularly the same game mentioned earlier. Thanks.


Dependency injection ; good practices to reduce boilerplate code

I have a simple question, and I'm not even sure it has an answer but let's try. I'm coding in C++, and using dependancy injection to avoid global state. This works quite well, and I don't run in unexpected/undefined behaviours very often. However I realise that, as my project grows I'm writing a lot of code which I consider boilerplate. Worse : the fact there is more boilerplate code, than actual code makes it sometimes hard to understand. Nothing beats a good example so let's go : I have a class called TimeFactory which creates Time objects. _For more details (not sure it's relevant) : Time objects are quite complex because the Time can have different formats, and conversion between them is neither linear, nor straightforward. Each "Time" contains a Synchronizer to handle conversions, and to make sure they have the same, properly initialized, synchronizer, I use a TimeFactory. The TimeFactory has only one instance and is application wide, so it would qualify for singleton but, because it's mutable, I don't want to make it a singleton_ In my app, a lot of classes need to create Time objects. Sometimes those classes are deeply nested. Let's say I have a class A which contains instances of class B, and so on up to class D. Class D need to create Time objects. In my naive implementation, I pass the TimeFactory to the constructor of class A, which passes it to the constructor of class B and so on until class D. Now, imagine I have a couple of classes like TimeFactory and a couple of class hierarchies like the one above : I loose all the flexibility and readability I'm suppose to get using dependancy injection . I'm starting to wonder if there isn't a major design flaw in my app ... Or is this a necessary evil of using dependancy injection ? What do you think ?


How to show or direct a business analyst to do data modelling?

Our business analysts pushed hard to collect data through a spreadsheet. I am the programmer responsible for importing that data. Usually when they push hard for something like this, I never know how well it will work out until a few weeks later when I have time assigned to work on the task of programming the import of the data. I have tried to do as much as possible along the way, named ranges, data validations, etc. But I usually don't have time to take a detailed look at all the data and compare to the destination in the database to determine how well it matches up. A lot of times there will be maybe a little table of items that somehow I have to relate to something else in the database, but there are not natural or business keys present that would allow me to do so. Make the best of this, trying to write something that can compare strings and make a best guess at it and then go through the effort of creating interfaces for a user to match the imported data to the destination. I feel like if the business analyst was actually creating a data model, they would be forced to think about these relationships, and have an appreciation for the need of natural or business keys to be part of the spreadsheet for the purposes of smoothly importing the data. The closest they come to business analysis is a big flat list of fields, and that would be fine if it were like any other data dictionary and include data types+relationships, but it isn't. They are just a bunch of names. No indication of what type of data they might hold, and it is up to me to guess. When I have pushed for more detail, they say that it is just busy work. How can I explain the importance of data modelling? How can I tell them what it is and how to do it? It feels impossible, because they don't have an appreciation for its importance. They do however, usually have an interest in helping out in whatever way they can, it's just this in particular has never gotten a motivated response.


sqrt c# vs sqrt c++

An idea why the c# version of sqrt (System.Math.Sqrt) is ~10 times slower than c++ version ? Futhermore, C# version seems to have one extra digit of precision. I have run my test under MSVC2012. I have used double and call System.Math.Sqrt once before doing the bench in order to force Jit


Is there an accepted term for a DSL implemented in a "standard" programming language?

The Wikipedia article for domain-specific languages seems only to refer to actual _languages_. However, I've heard the term "DSL" used to refer to unique-looking coding paradigms encouraged by libraries in "standard" languages. From Ruby on Rails, for example (from here):               create_table :posts do |t|       t.string :name       t.string :title       t.text :content            t.timestamps     end      That is Ruby code. It's not it's own language, but it's a unique coding style encouraged by a library in order to make coding in a specific domain more readable. Is there a separate term for this?


Interface Dependencies or Abstract Classes

I have a decision to make and I am wondering what would be the better solution. I am refactoring an older application and intend to really get into the nuts and bolts of it. There are 8 report types currently and one of the modifications are to allow different reports to be "saved" in different ways. My two thoughts on it were   1. Have an Abstract Class with an abstract save method, then each report type can define its own way of doing things. Possibly have other abstract classes inheriting from that one, each implementing a virtual `Save()` method. Then the report classes can inherit from the one with the relevant save mechanism.   2. Have a report interface, which has a method signature like               void Save(ISaveMechanism saveMechanism);      Then have an interface with a `Save()` method, then each report type can use `saveMechanism.Save();` and just use the concrete implementation required. Would either solution cause more issues/drawbacks than the other? This project doesn't currently have any associated unit tests but if given time, it would be good to add some later.


Coincidence or rule?

I was reading about Assemblies (modules, which Microsoft CLR works with). The Assembly contains so called Manifest, which by definition describes a set of files in the Assembly. I know that Android applications also contain a file called Manifest, which also describes a set of files contained in the application. Is this simply a coincidence? Or are there some commonly accepted rules in software development to name "special" files?


Would knowing Python help with creating iPhone applications?

Here is what the apple site says: > With Snow Leopard, Mac OS X makes it easy to use scripting languages as full > application development tools. Snow Leopard ships with support for the > RubyCocoa Bridge and the PyObjC bridge. These two bridges give developers > access not only to system APIs, but to Cocoa frameworks such as AppKit and > Core Data, enabling you to build fully native Mac OS X applications in Ruby > or Python. The RubyCocoa and PyObjC bridges allow you to freely mix code > written in Objective-C with code written in the scripting language. You can > quickly build prototypes and then optimise by implementing performance- > critical pieces in Objective-C. How could Python help in this case?


How far should I expose this status enum?

I wrote a little app to manage an arbitrary series of tasks (e.g., call a SQL sproc and capture out-vars, run another app, run an SSIS package) with dependencies between tasks. Each task has a status (waiting to start, failed and waiting to retry, failed and abandoned, succeeded, etc.). Internally, each `Task` object has a field of the `TaskStatus` enum type. There's a `TaskManager` object which starts tasks and monitors their successes and failures, and a `Dashboard` WinForm which displays progress. Should I expose each `Task`'s status as an enum throughout the app, or only to `TaskManager`, or always expose only the string value? My approach has been to expose the status as an enum, but this means that not only `TaskManager` but also `Dashboard` has a dependency on the possible values for `TaskStatus`. I almost posted this question on code review, but on balance I think it fits better here, sense it's mostly a matter of principle. `Dashboard` only interacts with `Task.Status` in a two places. First, its value is displayed in a `DataGridView` which summarizes all tasks, and this really should use a text value instead, if only to allow for prettier values. Second, status values are compared when the Status column is sorted, and obviously this will work either way. `TaskManager` is the iffy part. For example, a `TaskManager` has props `NumTasksRunning`, `NumTasksComplete`, and `NumTasksWaiting`. Originally, with `Task`s exposing their statuses directly, I put this logic in `TaskManager`:               public int  NumTasksRunning   { get { return _tasks.Count(t => t.IsEnabled && (t.Status == TaskStatus.Running || t.Status == TaskStatus.Aborting || t.Status == TaskStatus.FailedAwaitingRetry)); } }     public int  NumTasksComplete  { get { return _tasks.Count(t => t.IsEnabled && (t.Status == TaskStatus.Succeeded || t.Status == TaskStatus.FailedAbandoned)); } }     public int  NumTasksWaiting   { get { return _tasks.Count(t => t.IsEnabled && (t.Status == TaskStatus.Waiting)); } }      I could move this logic to properties in `Task`, protecting `TaskManager` from needing to know about the enum:               public bool  IsRunning   { get { return _status == TaskStatus.Running || _status == TaskStatus.Aborting || _status == TaskStatus.FailedAwaitingRetry; } }     public bool  IsComplete  { get { return _status == TaskStatus.Succeeded || _status == TaskStatus.FailedAbandoned; } }     public bool  IsWaiting   { get { return _status == TaskStatus.Waiting; } }      However, there are other places where the code is much simpler if `TaskManager` can see tasks' statuses directly:               public void  Abort(Exception ex)         {         State = TaskManagerState.Aborting;              foreach (Task task in _tasks)             if (task.Status == TaskStatus.Running && task.CanAbort)                 task.Abort(ex);         }      Of course I could add a new property to `Task`, maybe called `CanAbortNow` (`CanAbort` means the task can be aborted in principle, separate), but this is just one of several touch points. If I end up with an "IsX" property for every possible value of `TaskStatus`, have I really made the code any easier to maintain? This app is for my personal use, so the choice really only matters in that I'd like to know the "right" way - if there is any consensus.


In my API, how can I make knowing implementation details unnecessary?

Is it feasible that we have a layer of API simply for the reason so that people in the team don't have to understand the actual implementation of the individual components each of us are working on? I had this thought because I started to find that some times when working a project with a team of people (I am new to working in a group), it is kind of difficult to know where to start from. We want to split a huge application into parts so that each of us can concentrate on our own part while at the end of the day, we still want these parts to all work together without having every member to know thoroughly about the actual implementation of every parts. But an API to me, usually serves as an interface for "external" developers to extend on or build new things from our work without having to go directly into the core part. Since we all working in a team, having an API for each components just for us to work among ourselves seems a little overkill and funny. So what is the usual practise when it comes to situations like this? Although I am using Java in my case, I think a correct practise for such situations work for projects of all languages, right?


Is it worth reading the language specification?

I'm wondering if it is worth reading language specifications/standard documents (e.g. The Java Language Specification) if you aren't going to write a compiler/interpreter for the language or something similar? I understand that reading such a book shouldn't be anyone's first exposure to the language, but it could be a great way to learn the finer details of it. Have you ever bothered, and should others?


Refactoring a Single Rails Model with large methods & long join queries trying to do everything

I have a **working** Ruby on Rails Model that I suspect is **inefficient** , **hard to maintain** , and **full of unnecessary SQL join queries**. I want to **optimize** and **refactor** this Model (Quiz.rb) to comply with Rails best practices, but I'm not sure how I should do it. The Rails app is a game that has `Missions` with many `Stages`. `User`s complete `Stage`s by answering `Questions` that have correct or incorrect `Answers`. When a `User` tries to complete a stage by answering questions, the `User` gets a **`Quiz`** entry with many `Attempt`s. Each `Attempt` records an `Answer` submitted for that `Question` within the `Stage.` A user completes a stage or mission by getting every `Attempt` correct, and their progress is tracked by adding a new entry to the `UserMission` & `UserStage` join tables. All of these features work, but unfortunately the `Quiz.rb` Model has been twisted to handle almost all of it exclusively. The callbacks began at 'Quiz.rb', and because I wasn't sure how to leave the `Quiz` Model during a multi-model update, I resorted to using _Rails Console_ to have the `@quiz` instance variable via `self.some_method` do _all_ the heavy lifting to _retrieve every data value_ for the game's business logic; resulting in large extended join queries that "dance" all around the Database schema. ## The `Quiz.rb` Model that Smells:               class Quiz < ActiveRecord::Base       belongs_to :user       has_many :attempts, dependent: :destroy            before_save :check_answer       before_save :update_user_mission_and_stage            accepts_nested_attributes_for :attempts, :reject_if => lambda { |a| a[:answer_id].blank? }, :allow_destroy => true            #Checks every answer within each quiz, adding +1 for each correct answer        #within a stage quiz, and -1 for each incorrect answer            def check_answer         stage_score = 0         self.attempts.each do |attempt|           if attempt.answer.correct? == true             stage_score += 1           elsif attempt.answer.correct == false             stage_score - 1           end         end         stage_score       end            def winner        return true       end            def update_user_mission_and_stage         #######         #Step 1: Checks if UserMission exists, finds or creates one.         #if no UserMission for the current mission exists, creates a new UserMission           if self.user_has_mission? == false             @user_mission = UserMission.new(user_id: self.user.id,                                mission_id: self.current_stage.mission_id,                               available: true)             @user_mission.save           else             @user_mission = self.find_user_mission           end              #######         #Step 2: Checks if current UserStage exists, stops if true to prevent duplicate entry           if self.user_has_stage?             @user_mission.save             return true           else              #######         ##Step 3: if step 2 returns false:          ##Initiates UserStage creation instructions           #checks for winner (winner actions need to be defined) if they complete last stage of last mission for a given orientation             if self.passed? && self.is_last_stage? && self.is_last_mission?               create_user_stage_and_update_user_mission               self.winner                #NOTE: The rest are the same, but specify conditions that are available to add badges or other actions upon those conditions occurring:           ##if user completes first stage of a mission             elsif self.passed? && self.is_first_stage? && self.is_first_mission?               create_user_stage_and_update_user_mission                    #creates user badge for finishing first stage of first mission               self.user.add_badge(5)               self.user.activity_logs.create(description: "granted first-stage badge", type_event: "badge", value: "first-stage")                #If user completes last stage of a given mission, creates a new UserMission             elsif self.passed? && self.is_last_stage? && self.is_first_mission?               create_user_stage_and_update_user_mission                    #creates user badge for finishing first mission               self.user.add_badge(6)               self.user.activity_logs.create(description: "granted first-mission badge", type_event: "badge", value: "first-mission")                  elsif self.passed?               create_user_stage_and_update_user_mission                  else self.passed? == false               return true             end           end       end            #Creates a new UserStage record in the database for a successful Quiz question passing       def create_user_stage_and_update_user_mission         @nu_stage = @user_mission.user_stages.new(user_id: self.user.id,                                                    stage_id: self.current_stage.id)         @nu_stage.save         @user_mission.save              self.user.add_points(50)       end            #Boolean that defines passing a stage as answering every question in that stage correct       def passed?         self.check_answer >= self.number_of_questions       end                 #Returns the number of questions asked for that stage's quiz       def number_of_questions         self.attempts.first.answer.question.stage.questions.count       end            #Returns the current_stage for the Quiz, routing through 1st attempt in that Quiz       def current_stage         self.attempts.first.answer.question.stage       end            #Gives back the position of the stage relative to its mission.       def stage_position         self.attempts.first.answer.question.stage.position       end            #will find the user_mission for the current user and stage if it exists       def find_user_mission         self.user.user_missions.find_by_mission_id(self.current_stage.mission_id)       end            #Returns true if quiz was for the last stage within that mission       #helpful for triggering actions related to a user completing a mission       def is_last_stage?         self.stage_position == self.current_stage.mission.stages.last.position       end            #Returns true if quiz was for the first stage within that mission       #helpful for triggering actions related to a user completing a mission       def is_first_stage?         self.stage_position == self.current_stage.mission.stages_ordered.first.position       end            #Returns true if current user has a UserMission for the current stage       def user_has_mission?         self.user.missions.ids.include?(self.current_stage.mission.id)       end            #Returns true if current user has a UserStage for the current stage       def user_has_stage?         self.user.stages.include?(self.current_stage)       end            #Returns true if current user is on the last mission based on position within a given orientation       def is_first_mission?          self.user.missions.first.orientation.missions.by_position.first.position == self.current_stage.mission.position       end                 #Returns true if current user is on the first stage & mission of a given orientation       def is_last_mission?          self.user.missions.first.orientation.missions.by_position.last.position == self.current_stage.mission.position       end          end      ## My Question Currently my Rails server takes roughly 500ms to 1 sec to process single `@quiz.save` action. I am confident that the slowness here is due to sloppy code, not bad Database ERD design. What _does_ a better solution look like? And specifically:   1. Should I use _join_ queries to retrieve values like I did here, or is it better to instantiate new objects within the model instead? Or am I missing a better solution?   2. How should **`update_user_mission_and_stage`** be refactored to follow best practices? * * * ## Relevant Code for Reference: **`quizzes_controller.rb` w/ Controller Route Initiating Callback:**                 class QuizzesController < ApplicationController         before_action :find_stage_and_mission         before_action :find_orientation         before_action :find_question                 def show       end            def create         @user = current_user         @quiz = current_user.quizzes.new(quiz_params)         if @quiz.save           if @quiz.passed?              if @mission.next_mission.nil? && @stage.next_stage.nil?                redirect_to root_path, notice: "Congratulations, you have finished the last mission!"              elsif @stage.next_stage.nil?                redirect_to [@mission.next_mission, @mission.first_stage], notice: "Correct! Time for Mission #{@mission.next_mission.position}", info: "Starting next mission"              else                redirect_to [@mission, @stage.next_stage], notice: "Answer Correct! You passed the stage!"              end           else            redirect_to [@mission, @stage], alert: "You didn't get every question right, please try again."           end              else           redirect_to [@mission, @stage], alert: "Sorry.  We were unable to save your answer.  Please contact the admministrator."         end         @questions = @stage.questions.all            end            private                 def find_stage_and_mission         @stage = Stage.find(params[:stage_id])         @mission = @stage.mission       end            def find_question         @question = @stage.questions.find_by_id params[:id]       end            def quiz_params         params.require(:quiz).permit(:user_id, :attempt_id, {attempts_attributes: [:id, :quiz_id, :answer_id]})             end            def find_orientation       @orientation = @mission.orientation       @missions = @orientation.missions.by_position       end          end      **Overview of Relevant ERD Database Relationships:** **Mission -> Stage -> Question -> Answer ->** Attempt **< \- Quiz <\- User** **Mission ->** UserMission **< \- User** **Stage ->** UserStage **< \- User** * * * **Other Models:** **`Mission`.rb**               class Mission < ActiveRecord::Base       belongs_to :orientation                 has_many :stages            has_many :user_missions, dependent: :destroy       has_many :users, through: :user_missions            #SCOPES       scope :by_position, -> {order(position: :asc)}            def stages_ordered         stages.order(:position)       end                 def next_mission         self.orientation.missions.find_by_position(self.position.next)       end            def first_stage         next_mission.stages_ordered.first       end          end      **`Stage`.rb:**               class Stage < ActiveRecord::Base       belongs_to :mission            has_many :questions, dependent: :destroy            has_many :user_stages, dependent: :destroy       has_many :users, through: :user_stages                 accepts_nested_attributes_for :questions, reject_if: :all_blank, allow_destroy: true            def next_stage         self.mission.stages.find_by_position(self.position.next)       end     end      **`Question`.rb**                   class Question < ActiveRecord::Base           belongs_to :stage           has_many :answers, dependent: :destroy                accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:body].blank? }, :allow_destroy => true         end      **`Answer`.rb:**               class Answer < ActiveRecord::Base       belongs_to :question            has_many :attempts, dependent: :destroy     end      **`Attempt`.rb**:               class Attempt < ActiveRecord::Base       belongs_to :answer       belongs_to :quiz     end      **`User`.rb:**               class User < ActiveRecord::Base                 belongs_to :school       has_many :activity_logs            has_many :user_missions, dependent: :destroy       has_many :missions, through: :user_missions            has_many :user_stages, dependent: :destroy       has_many :stages, through: :user_stages            has_many :orientations, through: :school            has_many :quizzes, dependent: :destroy       has_many :attempts, through: :quizzes                      def latest_stage_position         self.user_missions.last.user_stages.last.stage.position       end          end      **`UserMission`.rb**               class UserMission < ActiveRecord::Base            belongs_to :user       belongs_to :mission            has_many :user_stages, dependent: :destroy          end      **`UserStage`.rb**               class UserStage < ActiveRecord::Base            belongs_to :user       belongs_to :stage       belongs_to :user_mission     end


Return magic value, throw exception or return false on failure?

I sometimes end up having to write a method or property _for a class library_ for which it is not exceptional to have no real answer, but a failure. Something cannot be determined, is not available, not found, not currently possible or there is no more data available. I think there are three possible solutions for such a relatively _non- exceptional_ situation to indicate failure in C# 4:   * return a magic value that has no meaning otherwise (such as `null` and `-1`);   * throw an exception (e.g. `KeyNotFoundException`);   * return `false` and provide the actual return value in an `out` parameter, (such as `Dictionary<,>.TryGetValue`). So the questions are: _in which non-exceptional situation should I throw an exception?_ And if I should not throw: _when is returning a magic value perferred above implementing a`Try*` method with an `out` parameter_? (To me the `out` parameter seems dirty, and it is more work to use it properly.) I'm looking for factual answers, such as answers involving design guidelines (I don't know any about `Try*` methods), usability (as I ask this for a class library), consistency with the BCL, and readability. * * * In the .NET Framework Base Class Library, all three methods are used:   * return a magic value that has no meaning otherwise:      * `Collection<T>.IndexOf` returns -1,     * `StreamReader.Read` returns -1,     * `Math.Sqrt` returns NaN,     * `Hashtable.Item` returns null;   * throw an exception:      * `Dictionary<,>.Item` throws KeyNotFoundException,     * `Double.Parse` throws FormatException; or   * return `false` and provide the actual return value in an `out` parameter:      * `Dictionary<,>.TryGetValue`,     * `Double.TryParse`. Note that as `Hashtable` was created in the time when there were no generics in C#, it uses `object` and can therefore return `null` as a magic value. But with generics, exceptions are used in `Dictionary<,>`, and initially it didn't have `TryGetValue`. Apparently insights change. Obviously, the `Item`-`TryGetValue` and `Parse`-`TryParse` duality is there for a reason, so I assume that throwing exceptions for non-exceptional failures is in C# 4 _not done_. However, the `Try*` methods didn't always exist, even when `Dictionary<,>.Item` existed.


What is good way to maintain library project without redundancy?

I am an Android developer, while I am developing a new project I often find I need to import a library project, so in every new project I need to to copy my library project and then I can add. Is there any better way to have single copy of my library project which I can then import into every one of my other projects without copying the same (library) project over and over again? I am using BitBucket.org to host my code.


What document should describe usage of a third party library in a project?

A customer of my employer has recently requested new features for some legacy code, and since the authors of the program are no longer here, I've been assigned to implement the new features. I've been provided with some high-level documents that are mostly from early stages of the project: the project definition, black-box testing procedures, research analysis of the initial phase of the project, and so on - nothing at a technical level. The code makes extensive use of a third party library (Lemur Indri) for indexing and retrieval of indexed materials, but there's no documentation of how we use this library, or why it was chosen. I've spent a lot of time just learning about the library itself and how we use it; I feel like this is wasted time. During a meeting with my supervisor I mentioned that it would have been nice if the developers of our system had written some documentation about the library and how we use it. I told him that it would have saved a lot of time for me, but I couldn't convince him that this type of thing is essential. I think writing such documentation helps future developers to get a grip on the system and perform modification faster. If there should be such document, what would it be called, or should it be included in one of the design documents?


Type of license to use that forces to keep a reference to the authors

I have a small open source library that I've written.   I want people to use it while forcing them to keep the authors attribution (a 2 liner in each file) when redistributing it or using it in their project. Would the MIT license work? or what type of license should I use


how do we clear new programming concept

In IT world, new latest technologies are generated daily. Every time, every programmer need to learn something & then clear it conceptually to implement. All new technologies are built on some basic concepts. But, these technologies have their own area of development & a developer is supposed to grasp it from very basic. This seems like starting from very beginning to reach till current. What is the best & fast way to learn and grasp a new developed technology ?


Should I have a blog to be a better programmer?

I read a few questions about how you can benefit from reading blogs, but I wonder what is really the impact of writing one. I had mine, but I neglected it (not having the time, not having fun with it (and I really try to avoid things that are not fun)) and now it's dead. Should I try harder on it? Or I can keep developing (pun) my abilities without having to maintain a blog?


C++11 support for higher-order list functions

Most functional programming languages (e.g. Common Lisp, Scheme / Racket, Clojure, Haskell, Scala, Ocaml, SML) support some common higher-order functions on lists, such as `map`, `filter`, `takeWhile`, `dropWhile`, `foldl`, `foldr` (see e.g. Common Lisp, Scheme / Racket, Clojure side-by-side reference sheet, the Haskell, Scala, OCaml, and the SML documentation.) Does C++11 have equivalent standard methods or functions on lists? For example, consider the following Haskell snippet:               let xs = [1, 2, 3, 4, 5]     let ys = map (\x -> x * x) xs      How can I express the second expression in modern standard C++?               std::list<int> xs = ... // Initialize the list in some way.     std::list<int> ys = ??? // How to translate the Haskell expression?      What about the other higher-order functions mentioned above? Can they be directly expressed in C++?


Training old timey fortran programmers to better code design. hints?

I need to quickly train Fortran 90 developers into object oriented design, good coding, and general coding practices to make code maintenance easier and accessible to everybody. Their current style is the usual:   * long routines that do too much   * modules are aggregated in "family mode" (routines that have something to do with different kind of objects who share a common use are all in one module, instead of having different modules for different type)   * huge globals module with hundreds of variables   * general un-greppability of identifiers This is just out of my head. I did a course to one of them explaining OO and modularization in terms of a Pen (with methods such as uncap(), and members like inkLevel) and I was very successful in diverting his point of view. I also gave him the exercise to code in OO style a very simple textual adventure, where the player can move around rooms. I also introduced the concept of patterns and antipatterns. I would like to know any hints and suggestions on how to perform this task at best. Thanks


Can graphics in the public domain be used in commercial software?

For example: http://commons.wikimedia.org/wiki/File:Epithalamus.png Could I take an image file like that, splice it apart, and use it in an application that would be sold?


Developing web sites that imitate desktop apps. How to fight that paradigm?

Supposse there's a company where web sites/apps are designed to resemble desktop apps. They struggle to add:   * Splash screens   * Drop-down menus   * Tab-pages   * Pages that don't grow downward with content, context is inside scrollable area so page is of a fixed size, as if resembling the one-screen limitation of desktop apps.   * Modal windows, pop-ups, etc.   * Tree views   * Absolutely no access to content unless you login-first, even with non-sensitive content. After splash screen desapears, you are presented with a login screen.   * No links - just simulated buttons.   * Fixed page-size.   * Cannot open a links in another tab   * Print button that prints directly ( not showing printable page so the user can't print via the browser's print command )   * Progress bars for loading content even when the browser indicates it with its own animation   * Fonts and color amulate a desktop app made with Visual Basic, PowerBuilder etc. Every app seems almost as if were made in Visual Basic. They reject this elements:   * Breadcrumbs   * Good old underlined links   * Generated/dynamic navigation, usage-based suggestions   * Ability to open links in multiple tabs   * Pagination   * Printable pages   * Ability to produce a URL you can save or share that links to an item, like when you send someone the link to an especific StackExchange question. The only URL is the main one.   * Back button To achieve this, tons of javascript code is needed. Lots and lots of Javascript and Ajax code for things not related with the business but with the necessity to hide/show that button, refresh this listbox, grey-out that label, etc. The coplexity generated by forcing one paradigm into another means most lines of code are dedicated to maintain the illusion of a desktop app. What is the best way to change this mindset, and make them embrace the web, and start producing modern, web apps instead of desktop imitations ? EDIT: These sites are intranet sites. Users hate these apps. They constantly whine about them, but they have to use them to do their daily work. These sites are in-house solutions, the end-users have no choice but to use them. They are a "captive audience". Also, substitution will not happen because of high costs. But at least if that mindset is changed, new developments would be more web- like.


How to avoid or minimise use of check/conditional statement in my scenario?

I have scenario, where I got stream and I need to check for some value. If I got any new value I have to store it in any of data structure. It seems very easy, I can place conditional statement if-else or can use contain method of set/map to check either received is new or not. But the problem is checking will effect my application performance, in stream I will receive hundreds for value in second, if I start checking each and every value I received then for sure it effect performance. Anybody can suggest me any mechanism or algorithm to solve my issue, either by bypassing checks or at least minimize them?


Why to use web services instead of direct access to a relational database for an android app?

I searched on the web how to access in an efficient manner to a central database at a remote location and I met suggestions to use web services instead direct access (i.e. JDBC etc ) to a database.I wonder the reason of that and any other suggestions.


What is the common definition of a Hacker?

I'm wondering if the term Hacker means different things to different people. When most people hear the word hacker what are the first things that come to mind?


Use decorator and factory together to extend objects?

I'm new to OOP and design pattern. I've a simple app that handles the generation of Tables, Columns (that belong to Table), Rows (that belong to Table and have Columns) and Values (that belong to Rows). Each of these object can have a collection of Property, which is in turn defined as an enum. They are all interfaces: I used factories to get concrete instances of these products, depending on circumnstances. Now I'm facing the problem of extending these classes. Let's say I need another product called "SpecialTable" which in turn has some special properties or new methods like 'getSomethingSpecial' or an extended set of Property. The only way is to extend/specialize all my elements (ie. build a SpecialTableFactory, a SpecialTable interface and a SpecialTableImpl concrete)? What to do if, let's say, I plan to use standard methods like addRow(Column column, String name) that doesn't need to be specialized? I don't like the idea to inherit factories and interfaces, but since SpecialTable has more methods than Table i guess it cannot share the same factory. Am I wrong? Another question: if I need to define product properties at run time (a Table that is upgraded to SpecialTable at runtime), i guess i should use a decorator. Is it possible (and how) to combine both factory and decorator design? Is it better to use a State or Strategy pattern, instead?


Should I use the factory design pattern for every class?

I've been writing a website in PHP. As the code becomes more complex, I keep finding problems that can be solved using the factory design pattern. For example: I've a got a class `Page` which has subclasses `HTMLPage`, `XMLPage`, etc. Depending on some input I need to return an object of either one of these classes. I use the factory design pattern to do this. But as I encounter this problem in more classes, I keep having to change code which still initiates an object using its constructor. So now I'm wondering: is it a good idea to change all code so that it uses the factory design pattern? Or are there big drawbacks? I'm currently in a position to change this, so your answers would be really helpful.


What core principles would you want in a library?

Theres talk about what syntax and feature you like in a programming language; i'll now ask what core principles or feature would you like in a library in your favorite (or any) language? An example is having adding list += anotherList valid as oppose to only allowing list += listElement (although some may see this as a bad idea)


Is there a clean separation of my layers with this attempt at Domain Driven Design in XAML and C#

I'm working on an application. I'm using a mixture of TDD and DDD. I'm working hard to separate the layers of my application and that is where my question comes in. My solution is laid out as follows               Solution         MyApp.Domain (WinRT class library)             Entity (Folder)                 Interfaces(Folder)                     IPost.cs (Interface)                 BlogPosts.cs(Implementation of IPost)             Service (Folder)                 Interfaces(Folder)                     IDataService.cs (Interface)                 BlogDataService.cs (Implementation of IDataService)         MyApp.Presentation(Windows 8 XAML + C# application)             ViewModels(Folder)                 BlogViewModel.cs             App.xaml             MainPage.xaml (Contains a property of BlogViewModel         MyApp.Tests (WinRT Unit testing project used for my TDD)      So I'm planning to use my ViewModel with the XAML UI I'm writing a test and define my interfaces in my system and I have the following code thus far.                   [TestMethod]         public void Get_Zero_Blog_Posts_From_Presentation_Layer_Returns_Empty_Collection()         {             IBlogViewModel viewModel = _container.Resolve<IBlogViewModel>();                  viewModel.LoadBlogPosts(0);                  Assert.AreEqual(0, viewModel.BlogPosts.Count, "There should be 0 blog posts.");              }      `viewModel.BlogPosts` is an `ObservableCollection<IPost>` Now.. my first thought is that I'd like the LoadBlogPosts method on the ViewModel to call a static method on the BlogPost entity. My problem is I feel like I need to inject the IDataService into the Entity object so that it promotes loose coupling. Here are the two options that I'm struggling with:   1. Not use a static method and use a member method on the BlogPost entity. Have the BlogPost take an `IDataService` in the constructor and use dependency injection to resolve the BlogPost instance and the `IDataService` implementation.   2. Don't use the entity to call the `IDataService`. Put the `IDataService` in the constructor of the ViewModel and use my container to resolve the `IDataService` when the viewmodel is instantiated. So with option one the layers will look like this > ViewModel(Presentation layer) -> Entity (Domain layer) -> IDataService > (Service Layer) or > ViewModel(Presentation layer) -> IDataService (Service Layer)


Places of historic significance in the field of programming?

Professions like art, history and literature have countless museums in their honor, but even regular non-entertaining fields like transportation and medicine have some destinations that could be of interest to the enthusiast. What about programming ? Are there any places of interest or historic significance that could amuse people with an interest in programming ?


Computing integration with the Trapezoidal Rule

I am trying to implement the trapezoidal rule programmatically but am having trouble finding a good way to input the function of x and then have a loop which will iterate through for each sub-interval finding the area of the trapezium and adding the results and returning it. Any help would be awesome.


What is the nicest (user-friendliest) way to tell a user about "Access Denied" error?

Our software implements a layer of role-based security to secure data access, in the form of access control lists. Whenever a user tries to do something that isn't allowed, the software layer will receive an "access denied" error code or exception. Having seen how our customers react to such "access denied" messages, and their negative impression to our software as a result, I've been thinking about how we should modify that message to make it less stressful. I understand that the best way to reduce such frustration is to simply hide the UI actions that a user is not authorized to do. However, our UI is very feature-rich and it is not always possible to predict whether a UI action will result in access-denied error. From a user's point of view, it would be nice if the user can be told "what went wrong", i.e. explained in the same way that a human IT administrator would explain. My question   * From a user-friendliness standpoint, what is the best way to present an "access denied" message without offending or frightening the user?   * From a software design standpoint, what design methodologies can be used to reduce the chance of a user seeing an access-denied situation? * * * Some thoughts   * If there is a security rule that says someone is forbidden from viewing a piece of data, then:     * If the user has low trust (e.g. general public), no explanation for the "access denied" should be given because any partial information could be used against the security.     * If the user has partial trust (e.g. an employee in the customer's organization whose rank is not high enough, or works in a different department), perhaps some explanation can be given to the user so that the user knows what security rule is being enforced?   * However, occasionally some security setup is based on "denied by default", meaning that in the absence of a rule _granting_ access, nobody can access anything.     * In this case, it is much harder for a software system to explain to the user why the "access denied" occurred. Maybe it is a configuration error (a human error)? Maybe a security rule is indeed being enforced in the way of the lack of a "access granting rule"? * * * Related: Methodologies for Managing Users and Access?


What's a good way to explain the need for pointing to a pointer?

Understanding what a pointer (an address) is, is fairly easy and an eleven- year old can understand it. But how do we express why we have a need for a pointer to a pointer? what is a very pedagogical example? Does it extend to pointing to a pointer to a pointer (and/or onward)? ## Example problem > T[][] does not decay to a T** ## Example problem 2               brainfuck command   C equivalent     (Program Start) char array[30000];                     char *ptr=array;     >   ++ptr;     <   --ptr;     +   ++*ptr;     -   --*ptr;     .   putchar(*ptr);     ,   *ptr=getchar();     [   while (*ptr) {     ]   }


Is "frontend" generic term or it is used only in web design?

When I read about frontends, it always mentiones webpages. Can it be used in different contexts, e.g. desktop applications?


The application I wrote is listed as malware. How to fix it?

I have a program that I wrote in Delphi. The program is available for download, but some antivirus like Norton detects it as malware, while other antivirus, like AVG, has no issues with it. Moreover, Google Chrome also gives a malware warning when you want to download the program from my website. Is there some way to prevent this, apart from putting the EXE file in a ZIP file?


Where does this concept of "favor composition over inheritance" come from?

In the last few months, the mantra "favor composition over inheritance" seems to have sprung up out of nowhere and become almost some sort of meme within the programming community. And every time I see it, I'm a little bit mystified. It's like someone said "favor drills over hammers." In my experience, composition and inheritance are two different tools with different use cases, and treating them as if they were interchangeable and one was inherently superior to the other makes no sense. Also, I never see a real explanation for _why_ inheritance is bad and composition is good, which just makes me more suspicious. Is it supposed to just be accepted on faith? Liskov substitution and polymorphism have well- known, clear-cut benefits, and IMO comprise the entire point of using object- oriented programming, and no one ever explains why they should be discarded in favor of composition. Does anyone know where this concept comes from, and what the rationale behind it is?


Code Smell: Inheritance Abuse

It's been generally accepted in the OO community that one should "favor composition over inheritance". On the other hand, inheritance does provide both polymorphism and a straightforward, terse way of delegating everything to a base class unless explicitly overridden and is therefore extremely convenient and useful. Delegation can often (though not always) be verbose and brittle. The most obvious and IMHO surest sign of inheritance abuse is violation of the Liskov Substitution Principle. What are some other signs that inheritance is The Wrong Tool for the Job even if it seems convenient?


Code reuse via inheritance

I have a set of classes that are all dealing with some related tasks. These tasks do have different inputs and outputs. This causes it to become impossible to have the tasks done via shared code without having this code be a pile of if-else statements handling all the different cases. Now someone refactored this code to use inheritance - there now is an abstract base class that holds methods for each of which it is used by some of the deriving classes, for some of which they get overridden or nullified and some of which are always called though not always applicable for the deriving class. Furthermore the inheritance is not used for polymorphism at all, just code reuse. I cringed a bit when I noticed this refactoring was done and that it happily got through code review. The codebase I am working with has existed for quite a while and is full of these kind of things, and most people don't understand the issues. I'm thus looking for a good overview of why inheritance should not be abused like this, esp including all the problems it causes.


When is it suitable to use inheritance

I recently had a small "argument" about inheritance with a friend. I think people overuse it a lot. Intuition tells me that that the only good reason for class inheritance is polymorphism - when there is a case that you want to treat uniquely object of different but related classes. Our argument was about having a BaseEntity class for Entity Framework that only has Id property. My friend says it's good because he can have generic repositories then. W don't agree with him.   1. Usually there's no such thing as a generic repository, you'll end up with "Refused bequest" smell.   2. What's the point of treating let's say a user and an invoice uniquely? These are 2 totally different things. Unfortunately I couldn't make any good points in spite of "it makes no sense". :) After a while I also realized that I drifted away from inheritance itself and now I tend to use interfaces instead. Actually in my recent web project (quite a big one) I can't recall any inheritance. Now I'm not sure when it is an appropriate technique anymore. So guys, please help me here.   1. What do you think about what I wrote?   2. Can you find any arguments I can use against my friend?   3. When it really is a good practice to use inheritance? (Please be specific and throw some examples) Please don't try to explain to me what the inheritance is all about. I'm very familiar with that and I used it a lot. Like I mentioned above, over time I just drifted away from it, because I couldn't find the right usage for it. Simply interfaces seem to be a better approach to me in most cases.


Demonstrate bad code to client?

A client has asked me to do a redesign of their website, an ASP.NET Webforms application that was developed by another consultant. It seemed like a relatively straightforward job, but after looking at the code, it's clear that's not the case. This application was not written well. At all. It is extremely vulnerable to SQL injection attacks, business logic is spread throughout the entire application, there is a lot of duplication, and dead end code that does nothing. On top of that, it keeps throwing exceptions that are being smothered, so site appears to run smoothly. My job is to simply update the HTML and CSS, but much of the HTML is being generated in business logic and would be a nightmare to sort out. My estimate on the redesign is longer than the client was aiming for. They are asking why so long. How can I explain to my client just how bad this code is? In their mind, the application is running great and the redesign should be a quick one-off. It's my word against the previous consultant. How can I give simple, concrete examples that a non-technical client will understand? **Update** Thanks for all the responses. The SQL injection attack demonstration makes sense and I will demo this in a test environment. That is just one part of many problems in this application. I was looking for ways to explain why other parts (such as html being generated in the data layer) would need to be replaced with better practices in order for the html and css update to take place. There are many good suggestions here which I'll piece together when I talk with my client.


Custom vs. browser-native scrollbars

Including customizable, JavaScript-based scrollbars (and scrolling functionality in general, i.e. bind the control to the mouse scroll wheel) in your webapp can be a great temptation. However all solutions I could find were developed by individuals (which can equal lack of formal or future support). In addition I fail to remember any mainstream site using them. In my particular case, no-JavaScript or IE6/odd-browser environments are not intended to be supported. Should custom scrollbars be avoided nowadays? If not, what's the best option one can choose?


Determinism of functions using PRNG in Clojure and functional languages

I'm a bit surprised by a sentence found in the book _"Clojure Programming"_ (1st [and only as I write this!?] edition), page 78: > It should be obvious that it's impossible to deterministically test a > function that depends upon a random number generator Well, to me it's not obvious at all. First in the context the book definitely talks about a PRNG (that sentence just follows a mention of _java.util.Random_ , which is a PRNG), not a real random source. Seen that functional languages that do support higher-order function can be, well, passed functions... Why not simply pass the random generator function itself to the function you want to be able to deterministically test? If I've got something like the following function (it's just an example) and the PRNG itself is deterministic, why would it be impossible to deterministically test the following function:               (defn shuffle-deck [deck  last-generated-number   prngf]           ...)      I realize that instead of keeping a (global?) reference to your random generator, you need to keep a reference to the last generated number (and update it accordingly) but that's basically it. You can then test/reproduce the behaviour of any function using a PRNG as long as you pass the PRNG and 'the random number you're currently at'. It's not unlike deterministic game engines (like Blizzard's Warcraft III) where the replays only contains the player inputs, the time at which they happened and the overall seed to the PRNG. Basically I'm a bit confused: I've always seen PRNG as something that is not "real randomness" and I've got the impression that functional languages accepting higher-order function make it particularly _easy_ to reproduce behavior of functions depending on PRNG. So, is that sentence of the book (which I found a great book btw) complete rubbish? I sure do not find it "obvious" at all...


What are the personal benefits from writing a boost library

Among the reasons for a developer to publish a self-written library as open source library, there is definitely fame. Now when it comes to Boost Libraries, they are available and promoted in a very anonymous and impersonalized form. The name of the author will be readable in the documentation and source files, but be honest: How many of you could tell me the names of the authors of `boost::shared_ptr`, ... without looking? And its not just about the names. Even if you do not know the name of the author of something your using, you still somehow identify it with "the author" and other stuff he did or maybe his website, where you found it. All these authors' identities are eradicated by the acceptance to Boost. (At this point I really want to thank all boost authors for their selfless and extremely professional efforts.) I know, they had there reasons, but what about the following case: Suppose, I had a marvelous and elegant solution to a C++ problem, that had bugged whole generations of programers. The implementation: \- standard compliant   * No use of Macros   * type-safe   * requires the user to write the minimum possible boilerplate code with no - I repeat: NO - code repetion   * zero memory footprint    * NO runtime overhead   * fits in a header file of about 100 lines of code. What should I do with it? Should I bother going the burdensome path of the Boost acceptance process? If yes, what's in there for me? While this sounds selfish, in the end everything you do should have some positive cost/benefit ratio.


What must be done to allow a development team to minimize difficulties as new team members are added?

I work at a small Web Dev firm, and have been handling all the PHP/MySQL/etc. for a while. I'm looking at improving our practices to allow for easier collaboration as we grow. Some things I have in mind are:   * Implementing a versioning system (source control)   * Coding standards for the team (unless mandated by a certain framework, etc.)   * Enforcing a common directory structure for our Desktops (for backup purposes, etc.)   * Web-based task/project/time/file/password/contact management and collaboration app(we've tried a bunch; I may just create one) What do more experienced developers view as necessary first steps in this area? Do you recommend any books? One thing to consider is that the bulk of our daily tasks involve maintenance and adding minor functionality rather than new projects, and the team size will be between 3 and 5. I just found a related question about teams that will be expanding from a solo developer.


what does it mean when a nested function isn't assigned to a var?

I'm referencing this link about closures: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work This is specifically about javascript. In the second answer with 956 votes, The author returns the nested function "sayAlert" after assigning it to the var keyword as shown below. (Example 3)               function say667() {     // Local variable that ends up within closure     var num = 666;     var sayAlert = function() { alert(num); }     num++;     return sayAlert;     }     var sayNumber = say667();     sayNumber(); // alerts 667      However in the next example (Example 4), the author assigns the following functions, "gAlertNumber", "gIncreaseNumber", and "gSetNumber", without the var keyword. Then the author is able to call the nested functions as follows.               function setupSomeGlobals() {     // Local variable that ends up within closure     var num = 666;     // Store some references to functions as global variables     gAlertNumber = function() { alert(num); }     gIncreaseNumber = function() { num++; }     gSetNumber = function(x) { num = x; }     }          setupSomeGlobals();     gIncreaseNumber();     gAlertNumber(); // 667     gSetNumber(5);     gAlertNumber(); // 5          var oldAlert = gAlertNumber;          setupSomeGlobals();     gAlertNumber(); // 666          oldAlert() // 5      I tried adding the keyword var to the begging of each nested function, but in my console it returns an error. So I'm assuming there's a difference between the two. But I don't know what this tactic is called and why it works...


What aspects make websites load faster?

I want to know what aspects in VPS hosting packages are related to performance for the website which will make it faster in loading for the end useres. And does RAM really matter?


Servlet : Usage of Constants.java class vs context param

I'm just wondering whether to keep some of my variables in Constants class or keep it in web.xml Say, I want to keep a variable of Facebook graph API prefix or `api_key`, `client_id` From my understand, the difference between Constants.java and web.xml is web.xml is easier to rewrite on compile using ant. So, you can replace your variables in web.xml according to what environment you are building you app for. (`client_id` varies by development environment/production environment, for example) If I understand it right, then Facebook graph API prefix should be kept in Constants.java (because it always is "https://graph.facebook.com/") and `api_key`, `client_id` should be kept in web.xml? What's the proper way to use them?


Global variables in javascript

I don't consider myself a highly skilled javascript developer, but I thought I got one thing right for sure: don't create global variables unless you really have to. I've been learning `angularjs` lately and discovered one strange thing, almost everywhere in code samples for angular you can find constructions like the following.               'use strict';          /* Controllers */          var phonecatControllers = angular.module('phonecatControllers', []);          phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone',       function($scope, Phone) {         $scope.phones = Phone.query();         $scope.orderProp = 'age';       }]);      Source: official example app https://github.com/angular/angular- phonecat/blob/master/app/js/controllers.js So I assumed I might be missing/misunderstanding something. Any thoughts except "since it's demo code, they don't care"?


Breaking up classes and methods into smaller units

During code reviews a couple devs have recommended I break up my methods into smaller methods. Their justification was (1) increased readability and (2) the back trace that comes back from production showing the method name is more specific to the line of code that failed. There may have also been some colorful words about functional programming. Additionally I think I may have failed an interview a while back because I didn't give an acceptable answer about when to break things up. My inclination is that when I see a bunch of methods in a class or across a bunch of files, it isn't clear to me how they flow together, and how many times each one gets called. I don't really have a good feel for the linearity of it as quickly just by eye-balling it. The other thing is a lot of people seem to place a premium of organization over content (e.g. 'Look at how organized my sock drawer is!' Me: 'Overall, I think I can get to my socks faster if you count the time it took to organize them'). Our business requirements are not very stable. I'm afraid that if the classes/methods are very granular it will take longer to refactor to requirement changes. I'm not sure how much of a factor this should be. Anyway, computer science is part art / part science, but I'm not sure how much this applies to this issue. EDIT: Check out: What is the ideal length of a method?


What would be a good  way to request comments?

In the project/team I'm working the frequency of comments is a little low. One reason might be that it is not clear to the long-time devs what lines in the code _really_ needs a comment (each part of the project has quite fixed devs). To increase this we plan to let team members review the code and check in "requests for comments", which the main dev of that part should replace with useful comments.   * Do you think this could work?   * If "yes": what tags should we use to mark? (e.g. //TODO please comment)   * Can you think of alternatives for this process? Edit: I appreciate your answers about best practice in commenting and writing code, and I completey agree. But my question targets the cases where refactoring is not an option (not wanting to change working code, not wanting to "accuse" main dev of producing code that needs refactoring,...) - so only more or better comments are an option (at least for this question).


What performance can we expect from std::string's c_str()? Always constant time?

I've been doing some needed optimizations lately. One thing I've been doing is changing some ostringstreams -> sprintfs. I'm sprintf'ing a bunch of std::strings to a c style array, ala               char foo[500];     sprintf(foo, "%s+%s", str1.c_str(), str2.c_str());      It turns out that Microsoft's std::string::c_str() implementation runs in constant time (it just returns an internal pointer). It appears that libstdc++ does the same. I realize the std makes no guarantees for c_str, but its hard to imagine another way of doing this. If, for example, they copied into memory they'd either have to allocate memory for a buffer (leaving it up to the caller to destroy it -- NOT part of the STL contract) OR they'd have to copy to an internal static buffer (probably not threadsafe, and you have no guarantees on its lifetime). So simply returning a pointer to an internally maintained null terminated string seems to be the only realistic solution.