Is it good practice to comment with issue number?

I saw many issue numbers from comments of jQuery code(Actually, there were 69 issue numbers in jQuery code). I think it would be good practice, but I've never seen any guidelines of this practice. If this is good practice, what could be guidelines of this practice?


Sharing SCTP connection with multiple threads

I have an application that needs to run in SCTP environment, I have a question in sharing the connection among multiple threads for packet receiving only, I've tried with the `sctp_sendmsg` and it worked without even locking the threads (is that been taking care of by the OS, in other words, is it thread safe to do that). I've tested many cases with the send and I can't see them out of sync. Anyway, back to the receiving, is it possible to create multiple threads and send each thread the sctp descriptor to start receiving messages? Do I need a lock here or is it ok without lock? I'm using C in linux.


Is saying "if ( $a != null && $a == 5)" the same as "if ($a == 5)"

First off, sorry if this is answered somewhere else. I did a brief search, but wasn't sure how to ask in search terms. I'm looking at some code and came across lot's of statements like this:               if ( ($a != empty_or_null_or_notDefined && $a == 5 )      Is this the same as just saying:               if ( $a == 5 )      ? (language is PHP.)


In which fields does quality of the software product matter as much as the completion time?

Someone told me that if the software product meets clients expectations, it is good quality. But I've worked with Interaction Designers (the same kind of people who made Gmail's interface and usability so cool!), and I've loved working with them because even though they came up with hundreds of changes in requirements, and emphasised on many many subtle details, when the software was complete, I could look at the product and say **WOW**! Sometimes, in a company, the only thing that matters is completing the project on time. As long as it works and as long as the client says it's ok, nobody bothers to improve it. I'm not talking about gold-plating, but I believe that for a programmer to enjoy his (well, maybe her too ;) ) job, they should be able to proudly say that "Hey, I made that software" and that comes only when the product is of good quality. Apart from your opinions on this, **I'd also like to know which fields** (Eg. Aerospace, Finance etc.) could I find companies (or you could mention the company name) where the quality of a product is as important **(and encouraged by the management)** as completing the project on time?


Forcing aggregate root child access through the aggregate root alone

**Context** I'm developing an application using a Domain Driven Design approach. I want to use a design pattern wherever appropriate and apply all SOLID principles. **Scenario** I have an order and I want to allow clients to add order lines to it. Consider the following pseudo code:               class Order         OrderLines[] (readonly)         AddOrderLine(orderLine)          class OrderLine         Product         Amount          class OrderLineFactory         OrderLine Create(product, amount)          class OrderLineRepository         Save(orderLine)      Now lets add an OrderLine to the Order:               Order.AddOrderLine(OrderLineFactory.Create(product: "Chocolate Cake", amount: 3))      By the way, the OrderLineFactory is there because in my case, there is some relatively complex logic involved with creating order lines. This is one of the main reasons for applying the factory pattern. **Problem** The problem is that I could do this instead...               orderLine = OrderLineFactory.Create(product: "Chocolate Cake", amount: 3)     OrderLineRepository.Save(orderLine)      ...and get around the `Order.AddOrderLine` method, effectively short-cutting any checks that are performed in that method (e.g. protecting against duplicates or limiting the order amount). **Working towards a solution** An argument could be that there shouldn't be a `Save` method on `OrderLineRepository`, because an OrderLine isn't an aggregate root. This would (just like I want) render the client incapable of storing the bare OrderLine except from adding it to the Order and saving the Order consequently. However, having a `Save` method on repositories that concern non-root aggregates, allows for saving changes made to them directly, such as:               orderLine = orderLineRepository.Get(31923)     orderLine.Amount = 5     OrderLineRepository.Save(orderLine)      Not being able to save the OrderLine would require me to do something like...               order = OrderRepository.FindByOrderLineId(31923)     order.OrderLines[31923].Amount = 5     OrderRepository.Save(order)      ...which isn't all that efficient or practical. I could add a requirement to provide the (actually redundant) Order ID as well but that would put some unnecessary burden on the client. So lets say I want to stick with my `OrderLineRepository.Save` method and still find a way to stop my client from being able to get around my `Order.AddOrderLine` method. All I can think of now, is dropping the OrderLineFactory and creating a domain service that combines the creation and the assignment.               class OrderService         AddOrderLine(order, product, amount)      So we can:               order = orderRepository.Get(123)     OrderService.AddOrderLine(order: order, product: "Chocolate Cake", amount: 3))     orderRepository.Save(order)      I don't really like the service combining multiple concerns here though, those of creation and assignment. That would call for... a factory... again. Okay, let's consider a private factory then, one that's not available to the client but to the domain service alone. In my case I would get stuck with unit testing and Inversion Of Control. I'd be creating an uninjectable dependency, since my client wouldn't be able to register my non-public factory. **Summary**   * I want my client to be able to create order lines through the Order class and in no other way   * I don't want to mangle multiple concerns in a single class   * I want to keep OrderLine creation outside of the Order class   * I'd like to keep using a factory for that So I'm a little stuck here, trying to find the best way to deal with this. Any suggestions?


A Whiteboard: 'useful!' or 'paper is better'?

Anyone still use a Whiteboard? If so how do you use it and is it actually that useful? Or do you prefer paper instead?


Connection between programming language and solutions

This is a rather philosphical / theoretical question. I am interested in the question, how language (in this case programming languages) and thoughts (= solutions of problems) are connected. I want to know, whether the programming language influences the solutions, I can come up with. For example: I program something in Haskell (functional) and in Java (OOP). Do the general solutions differ fundamentally or are they - aside from syntactic sugar - the same? Do I not just use different algorithms and a different software design, but do I fundamentally change my whole point of view, my concept and my view of the software, depending on the paradigm I am starting from? _(Note: "I" stands for a generic programmer)_ I know, that this question is pretty hard to answer, but I find it very interesting, so I wanted to know, whether somebody has (and might share) a opinion about this.


What is the user-experience best practice for an alternative to popup windows?

I'm still new to web design/development. I'm working on a data entry form for an internal system at work. On the form, the user can select an office from a list queried from a database. (The backend for this is PHP and MySQL, if you're curious.) I would like to add the functionality to allow the user to add an office to the list, among other things, with minimal invasiveness. I don't want to use a popup window since the default behavior for company browsers is to block popups. I've seen this, which shows you how to create an alert alternative in place of a new window. To me that seems like basically the same thing, and not really an improvement except that it would keep the browser from putting a kibosh on the new form. I think it might also be good just to keep the popup/alert functionality out of the picture altogether and opt for a new undisplayed `<div>` that is triggered by a button or doubleclick, autc. and closed by okay or cancel. Like I said, I'm still new to web design/development, and I'm wondering what the currently accepted best practice is for accomplishing this task with the best possible user experience. Update: the real question is "Is there a current best practice for accomplishing this task with the best possible user experience?" The answer may be "no, there are many options and none are more prevalent." What I'm looking for is either that, or "yes, the currently accepted best practice for user-experience in this case is X."


Requirement that code changes within release be reverse compatible with DB schema

I have recently come across a requirement related to our release/SDLC process that seems a little out of the ordinary to me so I am writing this to inquire whether this practice is common and, if not, whether our deployment process should be changed to eliminate a burdensome constraint. I work for a small software shop that makes enterprise software (so not a household name) and we only have a handful yet very large customers. It is a multi-server system management application running on Linux, DB backend, web front end, lots of async I/O and messaging. We roll out upgrades approx. every 2-3 months and our customers deploy them using `deb` or `rpm` (depending on OS) packages we provide them. All the customers deploy the app in a cluster environment with each server instance pointing to multiple database shards. As of late I have been working on some legacy refactoring that significantly changed our DB schema. To make a long story short, I reorganized how we store some data, split some tables into multiple new tables, reduced exposure to race conditions, and made corresponding code changes. Just as I was getting ready to submit my changes, I was informed by our systems architect that, "due to the way our customers deploy upgrades" (each server and each database separately, one by one and can take days if not weeks, during which some of the servers must stay up), we cannot have tightly coupled changes and that all code upgrades must be reverse compatible with the database within a one release cycle period. IOW, **we cannot remove fields from database tables because in all customer configs all servers point to all database shards and we must enable a server to simultaneously work with one shard that is upgraded along with another that is not.** Now, I was befuddled and troubled by this requirement to say the least. It seemed indicative of problems that the way our customers like to deploy changes (taking a long time), as well as their configuration, necessitates us to provide cumbersome dual functionality in parallel. In my particular case, I was told that I need to keep the refactored fields in the old tables for legacy reads while writing into the new tables and then amalgamate the retrieved data. This seems unnecessarily complex to me to say the least. My questions are as follows:   1. Is this requirement unusual for the general configuration I described? I have worked here around six months and I never worked for a product company before, always worked on site that made and deployed apps of their own (like a web site etc.). Is this scenario common in software product companies?   2. Is this phenomenon of necessary reverse DB compatibility indicative of problems with the way our customers like to deploy our software? To my knowledge, they apply our upgrades manually server by server, database by database while maintaining the production function. Should they be using something like `Puppet` or `Chef` to deploy our upgrades in a much shorted timeframe?   3. How should I approach presenting a need to change all of this, it presents a developer inconvenience to say the least having to provide for this bifurcated functionality?


Is using external repositories PCI-DSS compliant

We are considering using BitBucket rather than hosting our Git repositories internally. Does anyone know if this breaks any rules of PCI compliance? I haven't been able to find much information on this.


What are the available tools for creating cross-platform, cross-browser multiplayer online commercial games?

HTML5+Javascript is not viable as the client-side code will be visible and, thus, stealable. Flash is not viable since it's not supported on ipads and thus not cross-platform. Said that, what are the available tools for creating cross-platform, cross-browser multiplayer online commercial games?


From analysis to application

Which learning path would you recommend to be able to create complete application from requirement analysis, design (with various diagrams) to coding and testing? It's not easy to get this knowledge when man does not work for a software company. Is there on the internet some example of this process from requirements to complete application? It won't need to be very complex, something for a beginner who knows UML, database design and a few programming languages (intermediate level). I prefer the resulting application in Python or C (but in C there aren't classes, so maybe here will be less design). I don't like C++ much. Java is acceptable too. This is rather easier example of what I'm looking for. The emphasis should be more on design, there don't need to be complex algorithms but show rather putting some working system (e.g. information system with 3 layer architecture) together.


Commenting Code AS3 - Not being an API

How should I comment a method? What are the best practices on commenting code? Example:               /* Checks if a color is allowed in a given point     * of the bitmapdata of the current floor     * @param value - color to be checked     * @return boolean - if color is allowed returns true, else, return false     */          private function isAllowed(value:uint):Boolean {             //code...          }      Is that the best way to comment a method? I´ve heard there´s the use of the tag @see. What should be on this tag? I wonder if it could be something that has a relation to the method, is that right? Thanks.


Translating objects from one type to a another

I am working on a server-client app in c# and need to send an object from the client to the server via WCF. For simplicity I will call it WorkingClass as it is what does the work.                   public class WorkingClass          {             public WorkingClass (FileInfo uncompressedFile, FileInfo compressedFile)             {                 UncompressedFile = uncompressedFile;                 CompressedFile = compressedFile;             }                         public FileInfo UncompressedFile { get; private set; }             public FileInfo CompressedFile { get; private set; }                  public void ZipFile()             {                 //zip file             }         }      Now I need to send it to the server via WCF. I don't need the whole WorkingClass FileInfo properties serialized and sent, so I have a simple class which I will call MessageClass that has simple strings.               public class MessageClass         {             public MessageClass(string uncompressedFileName, string compressedFileName)             {                 UncompressedFileName = uncompressedFileName;                 CompressedFileName = compressedFileName;             }                  public string UncompressedFileName { get; private set; }             public string CompressedFileName { get; private set; }         }      I can add a ToMessage() instance method and a FromMessage static method to the WorkingClass. Or instead of the static FromMessage method, I could add a constructor to the WorkingClass that accepts a MessageClass as a parameter. To me these options seem to tie both classes tightly together and the WorkingClass should only have to worry about zipping a file, not converting itself for communication via WCF. Do I maybe create a converter class? The Server will then need to convert from the message to its own working class. Am I on the right path to handle this sort of thing? Is there a best practice or design pattern I can follow?


Is it not a good practice to handle runtime exceptions in the code?

I am working on a Java application, and I see that Run time exceptions are handled in many places. For example,                      try {                            //do something                  }catch(NullPointerException e){                      return null;                 }      My questions is, when is it a good practice to handle Runtime exceptions? When should exceptions be left unhandled?


Becoming a microsoft partner organisation

Does anyone know the process of becoming a microsoft partner for an organisation. What the requirements and process are?


How safe is it to cache a user ticket in SESSION

I'm working on a client library to interface with my company's api, and we generate a user ticket when the user logs in using the api. Obviously I don't want to send the user ticket to the client for resubmission on subsequent requests - is it (relatively) safe for me to cache this value in `$_SESSION` for later calls?


What does this point about first normal form mean?

I'm reading the Wikipedia page on first normal form, and am confused about the last bullet point: > 5) All columns are regular [i.e. rows have no hidden components such as row > IDs, object IDs, or hidden timestamps]. Does this mean "all information about a row is contained in its values" (my words)? * * * I understand the rest of the points about 1NF; it's only this one that I'm confused about.


What would be the best real example to explain the usefulness of Inheritance ?

When trying to explain the concept of Inheritance in OOP, the common example is often the mammals example. IMHO, this is really a bad example, because it will lead the newbies to use this concept the wrong way. And moreover, it is not a common design that they will face in their day-to-day design job. So, what will be a nice, simple and concrete problem that is solved using Inheritance ?


Map Library: Client-side or Server-side?

As I have already asked here, I have to implement a Multi-Platform Map application. Now I have Mapstraction as an option which uses Javascript to implement the desired functionality. My question is, "Is there any reason/benefit to implement such a library (let say, Adapters) in Server-side (in my case, PHP)?" As these maps are all based on Javascript, there is a big reason to use Javascript again to make the adapter also, so it would not be dependent to PHP, Java, or .NET for example. But is that all?


Are there security implications to using dynamically-assigned TCP port numbers?

I'm getting pushback from operations for having a server process listen on a dynamically-assigned port number (i.e. it binds a socket to a port number of 0, triggering a dynamic assignment by the OS, which it retrieves using getsocketname()). The argument was that is "creates all kinds of issues for firewalling, routing, ACL, and security purposes". I haven't run across anything about this. This is CentOS, our applications are in-house and restricted to a set of machines on a LAN that's heavily firewalled from the outer world. Can someone knowledgeable weigh in on the subject? **UPDATE 1** : FTP dynamically assigns a port number, too, although I don't know if it's from the same range of numbers that I've seen elsewhere (32768-61000?). How do firewalls etc. deal with this?


Run jQuery search on a URL's content

I'd like to create a program/application to iterate through all of a Tumblr user's posts and copy the content from each. In essence it'd be like Tumblripper, but download the text and video URLs in addition to the photos. I have the know how to strip the content, pictures, and video URLs from one Tumblr page using jQuery if I have access to it, but how can I have my javascript run using a different page's content that has no `<script>` referencing the js file? For example I have the code               var contentArray = []     var $content = $('.content');     for(var i = 0; i < $content.length; i++)     {         // Code to copy the content and put it in the array     }      But I can't just edit the HTML of the Tumblr page to add in a reference to my javascript page. What I am in need of is something like (in theory)               RUN getTumblrsContent.js ON exampleblog.tumblr.com      and have it make it's way through the HTML and find each div with class `content`. How might I accomplish this? How does Tumblripper and other applications like it get content from web pages? I'm open to using other languages and means to accomplish my goal


When deciding a Primary Key, can I use Date part of a DateTime field

I'm designing a payroll system I have designed a database with several tables and this question is related to following tables `EMPLOYEE (Employee_ID [pk], Name,... etc)` `LOCATION (Location_ID [pk], Name, Address, ...etc)` These two tables have many to many relationship as one employee can work in several locations and in a location, several employees are working. These two tables are related through `ATTENDANCE` table. `ATTENDANCE (Employee_ID, Location_ID, Shift_Type, In, Out)` Shift type would be either "Day" or "Night" and "In" / "Out" fields are `DateTime` fields. The shift type is decided based on the date in the field "In" . For example if an employee's `In` field is lets say -`06/22/2014 07:30:00 PM` then the shift type is `Night` and shift is belongs to 22/06/2014. (his `Out` time would be `23/06/2014 07:30AM`; that is on next day) THE CONDITION is that, an Employee can't work same shift on same date twice even in two locations. But an employee can work Day in a location and Night in another location. My initial primary key selection ATTENDANCE table was `(Employee_ID + In)` but that is wrong as an employee can work same shift in same day if the `In` time is slightly different in two occasions. So now I know the primary key should be some thing like `(Employee_ID + Shift_Type + Shift_Date)`. But the problem is I don't have a Date field in the ATTENDANCE table. But I have `In` field which is a `DateTime` field. Hopping that my understanding about the issue is correct..., My question is, with out adding another field to ATTENDANCE table as `Shift_Date`, is there a possibility to get the Date part of the field `In`, when creating a `PRIMARY KEY` for this table ?


Continuous Integration with Bamboo and Maven, Managing Version Numbers?

I am currently developing a product that is broken up into a few main parts: A Server, an Android client, a Desktop client, and a class library for providing common data structures. Currently my team is using Maven (with a private Nexus repo) and TeamCity to do continuous integration, but we're having a ton of problems with builds failing due to version numbering issues. Our current solution involves using the Auto-Increment Versions Plugin for Maven, but any time we make any changes to our pom files we have to manually update the version of the pom file since the version of the pom in Git is now out of date. My team and I have decided to look at Atlassian Bamboo, and since we are making changes to our workflow we would like to iron out these issues all at once. Here is what we are looking for:   1. We want to specify a major and a minor build number (such as 0.3) and have the resulting artifact deployed to our repository as major.minor.auto-incrementing-build-number (such as 0.3.2, 0.3.3, 0.4.0).   2. We want this to be as automatic as possible, since we have several developers and it only takes one person making a mistake to cause a disruption to everyone's workflow.   3. We would prefer for this functionality to happen in Bamboo if possible, as Bamboo's "clone project" feature would allow us to replicate this functionality across multiple applications quickly, as well as keeping all of our pom files from having a ton of additional code for managing versions. Has anyone had any experience doing something like this through Bamboo, or is there another approach that I should consider to make this easier?


Ajax - Responding business errors

This might sound like another of those questions with "best way" or "best practice" but I couldn't find anything related that could give me some light. The scenario... I have some ajax calls. Everything works alright. I make the calls, get the results back, change fields, values, colours. Nothing interesting here. But then, yesterday, I was writing another ajax method. Basically, two date fields to return number of days without holiday days. Again, nothing interesting here... until the point where I could pass invalid dates. Now, my question... in an ajax interaction, whenever I have a scenario where the data passed by an ajax call is invalid (understand invalid, the formatting is wrong or the data does not suit some sort of business), **should I respond any ajax call that contains data not suitable for my server side processes with a http status different of 200 or create a model with errors and messages and everything?** I've found people doing like AjaxRespond models and responding that. My point here is that if the data is not good, I could respond a http status 200 and deal with the ajax model to check if there are errors or not but I could also respond a 500 and be sure that there is an error. I can see two perspectives here. 1- the call was successful from javascript/ajax side and therefore 200 is the logical way to respond. This one sounds like "I have good news and bad news". 2- the call was successful but the data was busted and therefore 500 (or any other suitable status) was returned. This one is more doing business logic inside try/catches.


C++ Web Development: Wanting a minimalist start

I'm currently working on a Computer Science degree, and I want to build my own Web Server library. The problem? Every search I've done on interacting with web sites points to "Use this library that was built by someone else" - instead of explaining the basics of sending and receiving information. I'm not asking for a lot - I just want to enter a single alpha-numeric character on a web page, hit a button, and have that one byte of information sent to a C++ program, without the aid of a non-standard library.


Processing every leaf under a node in a tree efficiently

**Short version:** In a tree (non-binary) with many levels of children, where each node can have multiple leaves, what is the best way to tally leaves that meet a certain condition given a node? **Long, convoluted version:** Say you have Folders, which can contain more Folders. In production, my system has about 15 layers of folders at the deepest. Each folder may have documents. When a user navigates to a folder, they need to know how many documents are in that folder, total. They also need to know how many of those documents have been "flagged". Documents can be flagged if, after a certain time period, they have not been updated. This is determined based on history entries - take the last history entry for the folder, if it's bigger than X, then it's flagged. Right now I'm iterating over all folders > subfolders > etc > children to check the history entry and tally recursively. This is getting pretty slow now so I need a new approach. I've come up with two options but want to know if there's a better approach, or which one of these is best. **option 1** : Whenever adding a document or removing a document, iterate up the parent graph and increment / decrement a "DocumentCount" property that's stored in the Folder entity. This means that adding / removing take a minimal performance hit. But the problem here is that I actually need to count total number of documents, as well as total number of documents that are flagged (by checking history entries), so that means that I'll need another field and another process to call when this status changes. This introduces even more complexity as checking whether or not something is flagged is a method call, not a property. **option 2:** Have a timer job run through and update the "documentCount" and "unopenedDocumentCount" properties of each folder in the system, would be lots of CPU cycles and seems wasteful. **option 3** : Just thought of this - maybe iterating over every document and seeing if the document is a direct or distant child of the target node before evaluating would be better than iterating via recursion. I feel like this would be better for nodes high-up in the tree, but iterating over every child for a low-level node would be ridiculous. Hmmm... I'm tempted to implement option 1.. what other options are there?


Public-private key pair handling on a Windows ecosystem

I've been thinking about how to architect an infrastructure for one of our business applications with the following requirement:   * **Data written by some user can only be read by that user and his superior and a 3rd person yet to be defined** I'm thinking in using some sort of asymmetric algorithm, such as RSA for data encryption. We can generate a public-private key pair for each user and store the public key of each one openly on a database, but how should we handle the private key ? If we just let the users manage their private key one day we will have a big headache if one of them loses his key. If the private key becomes public somehow then the data would become public too, rendering the architecture invalid. Our infrastructure is heavily Microsoft-oriented: All applications are ASP.Net MVC3, our dabatase is SQL Server 2005 and we use Active Directory for user authentication and basic data, such as e-mail/phone number. How would you guys architect a solution to solve this problem ? Bottom-line: This is not a banking or financial application, it's some kind of 360-degree personal feedback system. EDIT: Adding more requirements, hoping to make it more clear:   * This database will be in production environment, where developers don't have access;   * When the database is restored, developers should not be able to recover the data;   * The DBA should not be able to view the data by SELECT'ing the rows on the tables; EDIT 2: Bounty info. Bounty went to the answer with more upvotes, although my personal feel is that none of the answers provided addressed the question correctly. For this reason, I'm granting the bounty but not marking the answer as correct.


How much help should I give during technical interviews?

I'm asked to perform or sit in during many technical interviews. We ask logic questions and simple programming problems that the interviewee is expected to be able to solve on paper. (I would rather they have access to a keyboard, but that is a problem for another time.) Sometimes I sense that people do know how to approach a problem, but they are hung up by nervousness or some second- guessing of the question (they aren't intended to be trick questions). I've never heard my boss give any help or hints. He just thanks the interviewee for the response (no matter how good or bad it is) and moves on to the next question or problem. But I know something about the rabbit hole that defeat and nerves can lead you down, and how it disables your mind, and I can't help wondering if providing a little help now and then would ultimately help us end up with more capable programmers instead of more failed interviews. Should I provide hints and assistance for befuddled interviewees (and if so, how far should I go while still being fair to the more prepared candidates)?


Combining Single Page Application and DDD with a REST API

I'm creating a web application which on the client side consists of a Single Page Application (with Durandal) and on the server side an ASP.NET MVC site with a Domain Driven Design. The two are connected with a REST Api (Web API). I have a relation between two entities, which on the database level is many- to-many. (Hotels <=> RoomTypes). Since in DDD a best practice is not to have many-to-many relationships I built it so that it can only be navigated from the roomtype to the hotel (since a hotel can exist without roomtypes, but a roomtype should always be associated with a hotel). The relation itself also has attributes (availability for example). My current issue is how to associate a hotel with a roomtype however. Following DDD practices I would add a method `AddHotel` to the RoomType-class. The problem is that in the SPA, you can edit all the attributes of a roomtype (pictures, description, ...) and associated hotels in a single view. After editing these attributes, an update is submitted via the rest api. This means that everything gets submitted in one call to the server. How would you structure the server and the rest based API so that:   * the domain stays in place and there's correct validation inside the RoomType-class   * you can post atomic updates from the single page application through the rest   * there's no code duplication on the server and the single page application


Commenting in code I believe is very important but recently I've been reviewing code that has left me wondering particular this one.                //due to lack of confidence with web programming leaving this note in for now      What is the right level of granularity for code commenting? EDIT: Obviously the above comment is shocking hence why I'm asking the question. I've recently noticed the inline comments in the code at my work place annoying. Instead of getting angry I want discovery the acceptable level of granularity for code commenting in the community.


What complexity do DI frameworks add?

The currently most upvoted answer to a very recent question states that > DI containers are an "enterprise software" pattern, used when the object > graph is very large and complex. I suspect that 95% of applications do not > require it. which is something I strongly disagree with. Maybe I've got the terminology wrong, but for me DI framework means just "something wiring my objects together". Am I missing something? I'm using Guice even for really tiny projects (like 10 classes) in order to _simplify_ them. Sure, it's a 400 kB JAR file, but this isn't what I'd care about. For a small project I hardly ever need any configuration and the only "overhead" is adding the `@Inject` annotation. So I really wonder, what added complexity do DI frameworks cause? ### Update addressing the answers In a 82 class project, I have   * 32 `@Inject` annotations   * 15 `@Singleton` and 1 `@ProvidedBy` annotations   * 4 Providers (all of which I'd need also without DI as they're my factories)   * 1 Module containing a single line   * 0 lines XML !!! That's all. Sure, it's small project, but exactly this was my point. The additional work was a few _words_ rather than _lines_. I'm using solely constructor injection in order to get immutable "easygoing" objects. Whenever a new dependency appears, I add a final field, let Lombok's RequiredArgsConstructor take care of the declaration, and let Guice take care of calling it properly.


REST API Structure

I have a REST API that looks something like the below where a person can belong to an organisation (but doesn't have to) and a person has many items. The items may also belong to the organisation instead of the person.               /people/:personId     /people/:personId/items     /organisations/:orgId/items     /organisations/:orgId/people/:personId/items      There is a scenario where we want to query the items for multiple people within an organisation, what's the correct URL structure to use? ### Option 1               /organisations/:orgId/people/items?personId=1&personId=2      ### Option 2               /organisations/:orgId/items?personId=1&personId=2      ### Option 3               /items?personId=1&personId=2


Why and for what reasons developers may not like "daily scrum"?

There are advantages in holding daily scrum, like:   1. Team get coordinated with each other   2. Everyone knows what amount of task has been done   3. Burndown chart gets more and more complete   4. Task board is updated    5. It doesn't last that much, 15 minutes won't kill anybody However, recently (after 6 months of implementing and using scrum), I feel like that our developers don't like scrum daily that much anymore. People just update the task board, without explaining enough and it seems that they're bored of it. I see that when for any reason, we don't hold it, they kind'of become extra-happy. I just don't know what could be wrong with this. Are there any reasons mentioned somewhere for disadvantages the "daily scrum" can have for a team? What could be the reasons for developers getting tired of daily scrum?


Version control management of large projects

I'm used to version control, in particular I currently use Mercurial. I have some doubts about how to make it work in large teams, where there is a good probability of having more people working on the same file. Let me make an example with Mercurial (but any decentralized system will be more or less the same). Say we have a central server and three developers Alice, Bob and Carl. The three decide to start working at the same moment and they all pull from the server. By chance it happens that they are working on the same file. Alice finishes first, and push her changes to the server. Then both Bob and Carl finish, more or less at the same time. Before pushing, they check whether there is something new, and find Alice's commit. So they pull it, and each one merges the changes locally. Then Bob pushes it and Carl pushes its changes. What happens here is that on the server there are two heads: one by Bob and one by Carl, and both include merges with Alice's work. Whoever now pulls from the server will find a little mess. Of course one can just merge Bob and Carl heads, but that may not be as simple. Bob and Carl may have had different ideas on how to merge with Alice's work. As soon as more people start working on the project, things can go even worse. So, while in theory I understand how merges are supposed to work, it is not clear to me how to make things manageable in a large project. > How do people manage to resolve conflicts when there are many people working > on the same file, possibly having done different merges in different orders?


Options other than C for embedded projects? I hate the preprocessor

C is an awesome simple language perfect for close-to-hardware programming, but the preprocessor sucks in comparison to modern languages. Is there an alternative/add-on to the c preprocessor that adds modern features to C pre-processing (eg import vs includes)? In particular, I'm looking for namespaces (or something close to that), a readable macro language, and a more powerful macro language (with reflection). Or do I need to look in to viable alternatives to C for doing embedded programming (my own projects, not contract work where I take on or pass off project) I am aware of D, but haven't really looked into using it for embedded. *edit I can't believe nobody pointed me to this! eLua


Many-to-many in OOP: Class A instantiates Class B, which instantiates Class A, which

I am mapping Field1 to Field2. The map object instantiates the field object and vice versa, creating an infinite loop. This is in PHP.               class field {       protected $maps; // mapCollection object. all the mappings of this field to others          }          class map {       protected $field1; // field object       protected $field2; // field object     }          class mapCollection {       protected $maps; // array of map objects     }      The mappings and fieldsets are stored in a database where they each have a unique ID. So I decided to allow fetching them using their ids in the constructors.               class field {       protected $maps; // map object       public __construct($id = 0 ) {         if(!empty($id) ) {           $this->maps = // get mapsCollection. data from db         }       }          }          class map {       protected $field1; // field object       protected $field2; // field object       public __construct($id = 0 ) {         if(!empty($id) ) {           $this->field1 = // get field1 data from db           $this->field2 = // get field2 data from db         }       }     }          class mapCollection {       protected $maps; // array of map objects       public __construct($field_id) {         // get maps from db by field id         foreach($dbdata as $map_id) {           $this->maps[] = new map($map_id); // instantiates new map, which instantiates new field, etc         }       }     }      How should I be doing this?


When one thread out of four is executing first line in run() then at the same time what will remaining three threads do?

I have four thread instances and they are executing `run()` code given below:               public void run (){        System.out.println("1st line :"+Thread.CurrentThread().getName());        System.out.println("2nd line :"+Thread.CurrentThread().getName());        System.out.println("3rd line :"+Thread.CurrentThread().getName());        System.out.println("4th line :"+Thread.CurrentThread().getName());        System.out.println("5th line :"+Thread.CurrentThread().getName());        System.out.println("6th line :"+Thread.CurrentThread().getName());     }      When one thread out of four is executing first line then at the same time what will remaining three threads do? Either they are waiting for executing first line or will they proceed other lines of code?


Using 2 Constructors: one that injects dependencies and one that instantiates them

I started using TDD for the first time on a project I started recently. I have a few objects with dependencies and structures that look something like this:               public class MyClass     {         private readonly IDependency1 _dependency1;         private readonly IDependency2 _dependency2;              public MyClass(IDependency1 d1, IDependency2 d2)         {             _dependency1 = d1;             _dependency2 = d2;         }              public MyClass()         {             _dependency1 = new Dependency1();             _dependency2 = new Dependency2();         }     }      For tests I use Mock objects for the dependencies but in the implementation I sometimes let the constructor new up a concrete object. It feels like I am cheating by doing this but I'm not sure why it is bad in practice. Is this considered bad practice? If so why?


Why do we must declare a public API when using semantic versionning?

from semver.org: > **Software using Semantic Versioning MUST declare a public API**. This API > could be declared in the code itself or exist strictly in documentation. > However it is done, it should be precise and comprehensive. Why are we forced to declare a public API? Why can't I use it for my own website that has no API? Perhaps I am wrong with the definition. For me it is a part of the site desigedn for other developers (i.e.: `api.example.com`) that allow them to query my website and get the result into structured data (json, xml...).


User uploaded images: limit file size on front end or reduce on back-end?

I was wondering what the standard/best practice is with regard to managing user-uploaded images. Obviously there needs to be a way to limit file sizes, but what's the best and most common practice here -- limit the size of the image that can be uploaded by the user, or reduce the size once it's uploaded on the back-end? Thanks for any guidance! Ken


Where should an object in CQRS+ES be fully initialized: in the constructor, or when applying the first event?

There appears to be widespread agreement in the OOP community that the class constructor should not leave an object partly or even fully uninitialized. > **What do I mean by "initialization"?** Roughly speaking, the _atomic_ > process that brings a newly created object into a state where all of its > class invariants hold. It should be the first thing that happens to an > object, (it should only run once per object,) and nothing should be > permitted to get hold of an un-initialized object. (Thus the frequent advice > to perform object initialization right in the class constructor. For the > same reason, `Initialize` methods are often frowned upon, as these break > apart the atomicity and make it possible to get hold of, and use, an object > that is not yet in a well-defined state.) **Problem:** When CQRS is combined with event sourcing (CQRS+ES), where all state changes of an object are caught in an ordered series of events (event stream), I am left wondering when an object actually reaches a fully- initialized state: At the end of the class constructor, or after the very first event has been applied to the object? > **Note:** I'm refraining from using the term "aggregate root". If you > prefer, substitute it whenever you read "object". **Example for discussion:** Assume that each object is uniquely identified by some opaque `Id` value (think GUID). An event stream representing that object's state changes can be identified in the event store by the same `Id` value: (Let's not worry about correct event order.)               interface IEventStore     {         IEnumerable<IEvent> GetEventsOfObject(Id objectId);      }      Assume further that there are two object types `Customer` and `ShoppingCart`. Let's focus on `ShoppingCart`: When created, shopping carts are empty and must be associated with exactly one customer. That last bit is a class invariant: A `ShoppingCart` object that is not associated to a `Customer` is in an invalid state. In traditional OOP, one might model this in the constructor:               partial class ShoppingCart     {         public Id Id { get; private set; }         public Customer Customer { get; private set; }              public ShoppingCart(Id id, Customer customer)         {             this.Id = id;             this.Customer = customer;         }     }      I am however at a loss how to model this in CQRS+ES without ending up with deferred initialization. Since this simple bit of initialization is effectively a state change, wouldn't it have to be modelled as an event?:               partial class CreatedEmptyShoppingCart     {         public ShoppingCartId { get; private set; }         public CustomerId { get; private set; }     }     // Note: `ShoppingCartId` is not actually required, since that Id must be     // known in advance in order to fetch the event stream from the event store.      This would obviously have to be the very first event in any `ShoppingCart` object's event stream, and that object would only be initialized once the event were applied to it. So if initialization becomes part of the event stream "playback" (which is a very generic process that would likely work the same, whether for a `Customer` object or a `ShoppingCart` object or any other object type for that matter)…   * Should the constructor be parameter-less and do nothing, leaving all work to some `void Apply(CreatedEmptyShoppingCart)` method (which is much the same as the frowned-upon `Initialize()`)?   * Or should the constructor receive an event stream and play it back (which makes initialization atomic again, but means that each class' constructor contains the same generic "play back & apply" logic, i.e. unwanted code duplication)?   * Or should there be both a traditional OOP constructor (as shown above) that properly initializes the object, and _then_ all events but the first are `void Apply(…)`-ied to it? I do not expect of answer to provide a fully working demo implementation; I'd already be very happy if someone could explain where my reasoning is flawed, or whether object initialization really _is_ a "pain point" in most CQRS+ES implementations.


Do any object-oriented programming languages support "collective constructors"?

I was recently considering that sometimes several objects depend on each other (e.g. if they contain cyclic references) and therefore it would be useful to create them as part of one atomic operation that makes sure that, after construction, the new objects fulfil some collective constraint. In order to do this one could have constructors that can create more than one object. The programmer would then put in a single constructor all the code ensuring that, once objects o1, ..., on have been created, they satisfy all required constraints (e.g. all links between the new objects are already in place). I have made up the term **collective constructors** myself because I have never heard of such a feature, but there might well exist an accepted name for this concept. So, is there any programming language supporting this kind of constructors? If not, has the idea been tried out already?


Tools and/or methods for regular Code review of Remote development team

We are outsourcing a development to a small team of offshore developers. Our in house process for code review is manual, paper based, based on a waterfall model requiring "big bang" delivery. It cannot be changed. Past experience is these devs are proficient and reliable, however come time to deliver, the overhead of reviews becomes a difficult burden for everyone involved and issues are being found too late. We use CVS for our source repository. They take a copy of the CVS repo, receiving regular updates to the most recent code base, and use GIT locally to manage their changes. When ready to deliver, send us a tarball of an upto date CVS clone with their work merged into it. We then code review and check it in. We are looking for a tool chain to support a code review process where we can do regular, light weight reviews outside our inhouse process, so that when the inhouse process kicks in, we can do it "go fast" mode as we have already reviewed most of the code. Limitations are that there systems and ours are disconnected. We use sneaker net to transfer files between us. The best we can do is have one machine in house that VPN's into their system. The source is commercial code and cannot be placed anywhere where it is exposed to the internet. One option they have suggested is Gerrit - which they plan to use on their site. Is there a way to share and synchronise the gerrit database between sites, given the limitation of the sneaker net? Does anyone else have a solution to tis kind of problem?


Naming UI components in web based editor

I'm developing a web-based source code editor. I'm developing everything(tabs, context menu etc) out of HTML elements. How do I come up with names for UI controls? Is there a book or guide or project from which I can learn how to name things?


How to choose a development method?

There are many academic/industrial researchs about various development methods (Scrum, XP, waterfall, ect.), telling us how to do it right and stuff. But I never saw something that suggest how to choose a method, what will be better for a given project. I know that what the developers are used to is an very important aspect. But lets say that I am assembling a new group from scratch, and that every programmer in the world is willing to work with me. :) What aspects of the project should I consider to decide between Scrum, XP, TDD, ect.? Or is that an entirely human thing, regardless of what is being developed?   * I said that all programmers are available, but you may comment they're knowledge about the domain, or other characteristics in the answers. E.g. "If you chose to hire people with no domain knowledge, `MethodX` is better than `MathodY`, beacause ...." is a completely welcomed answer.


How useful is command prompt?

As a beginner into programming, I wanted to know if there's any use or good in learning how write commands in a command prompt? If yes how useful is a command line interface and where is it used? P.S Also do suggest me some good resources to learn it if applicable.


Trouble understanding the COCOMO model

In the basic COCOMO Model which is used to estimate the development time of software Effort : a * KLOC^b = X person months Development time : c * Effort^d = Y months where a , b , c , d are constants derived from the table below depending on the type of your software project ![enter image description here](http://i.stack.imgur.com/jr2lO.png) > Question 1 Assuming X = 10 , Effort will be equal to 10 person months. Does 10 person months mean that the effort required to complete this project will be 1 month if we have 10 people working on it **OR** Does 10 person month mean that the effort required to complete the project will be 10 months if we have 10 people working on it. > Question 2 Do the constants have any SI units like the SI unit of Effort is person months I am confused by the terminology


Enterprise Architecture Certification

I want to make the step up from developer to enterprise architect. I have 13 years experience in various environments, from SME line of business apps to investment banking enterprise systems. I'm certified in a number of technologies, including Java/.NET/SQL. What should I focus on over the next 12 months that will hold some weight with potential employers and lend credibility to my application for an Enterprise Architecture role, absent experience? I am currently looking at TOGAF 9.1. Are there other competing or supplemental methodologies I should research?


Difference between USP and IEEE rounding

I am trying to understand the difference between different rounding methods: Our application offers two different types of rounding:   * IEEE    * USP (GMP) rounding. http://www.usp.org/sites/default/files/usp_pdf/EN/USPNF/USP34-NF29General%20Notices.pdf In our unit tests, they seem to do the same thing for the cases being tested. However, I haven't found anyone in the office who can explain what is meant when selecting rounding mode of IEEE


Why do VMs need to be "stack machines" or "register machines" etc.?

(This is an extremely newbie-ish question). I've been studying a little about Virtual Machines. Turns out a lot of them are designed very similarly to physical or theoretical computers. I read that the JVM for example, is a 'stack machine'. What that means (and correct me if I'm wrong) is that it stores all of it's 'temporary memory' on a stack, and makes operations on this stack for all of it's opcodes. For example, the source code `2 + 3` will be translated to bytecode similar to:               push 2     push 3     add      My question is this: JVMs are probably written using C/C++ and such. If so, why doesn't the JVM execute the following C code: `2 + 3`..? I mean, why does it need a stack, or in other VMs 'registers' - like in a physical computer? The underlying physical CPU takes care of all of this. Why don't VM writers simply execute the interpreted bytecode with 'usual' instructions in the language the VM is programmed with? Why do VMs need to emulate hardware, when the actual hardware already does this for us? Again, very newbie-ish questions. Thanks for your help


quick prototyping in project design & development

i'm currently working on a project in my spare time (mostly 3-4 hours from monday to friday, and up to 6 hours on sundays) and i've found redmine very useful to hold a record of development tasks. However, there are some stuff, specially when you are trying to prototype or brainstorm a redesign of a set of related classes, that the best tool that i've found for this still is **a sheet of paper and a pen**. I want to understand if maybe i'm just short of getting to work properly with existing tools. Do you find the use of a notebook or a journal an unavoidable part of software design? are there better alternatives? how do you organize pen-and-paper work and other software management tools like redmine?


What is the best way to divide work among developers

My team and I are rebuilding a site we developed around ten years ago, and we want to do it in Agile. So after I spent a lot of time reading (probably not enough) I am having trouble with the question how to divide work between developers. I'll be more specific and say that the site is divided to separate modules that doesn't have much integration between one another. What is the best / Most accepted way to divide the work between the developers?   * Giving each person a different module to work on.   * Assign all developers to the same module, and split the work by different parts of the module (UnitTesting, DAL and Mapping, Logics, UI)   * Assign all developers to the same module, and split the work by different logics (For example each developer is in-charge of a specific logic(probably a method in the BL) and It's UnitTesting, DAL and Mapping and UI... Or maybe something entirely different?


Are there still any companies/academic centers that use mainframes from 60s-70s?

As a young software engineer, I often hear other colleagues talk about the days of punch cards and "computers as big as the room." The earliest memories of computers that I have involve MS DOS and Windows 3.1. My question is, are there still any companies, academic centers, or government agencies that still use mainframes from the 1960s-70s in their daily operations? If so, can you think of a place that would allow visitors to observe such a machine at work? I know that there are several museums out there that possess such pieces, but I cannot think of a functioning one.


How to fix bad fundamentals?

I am a native PHP developer, and have been for about a year or so. I love PHP and it was very easy for me to learn, but I have developed some bad habits along the way due to never having a formal education in programming. It's pretty easy to get the job done in PHP without writing the best code. I am looking to work more with another language; not because I don't like PHP but because I want a clean slate to learn programming fundamentals. I am looking to stay with web development, so Ruby or Python seem to be where I'm leaning, though I am open to other suggestions. The more important question is, how do I approach learning this new language to really become a good programmer rather than a guy that can "get the job done"?


How do I let customers run arbitrary code as securely as possible?

I'd like to offer a service where customers can write arbitrary java code, send it to me, and I'll run it for them on Amazon EC2. My question is: how can I do this without exposing one customer's data to another customer? Right now I'm thinking that each customer can be sandboxed as their own OS- level user with restricted permissions. Is that good enough? I understand that this is a tricky issue, but it seems to be one that many people, such as the designers of multi-user OS's and Amazon themselves are solving, so I am optimistic that there might be a good approach.


How do purely functional programming languages deal with fast changing data?

What data structures can you use so you can get O(1) removal and replacement? Or how can you avoid situations when you need said structures?


Optimistic & Pessimistic Programming - Ensuring multiple tasks are called only once for specific record

Let's say you have 10 database records which you need to process in the following way:   1. Start   2. Pull 2 records from the database with the 'Processed' flag set to 'false'   3. Call the external web service with the custom data from this 2 records.   4. Update those 2 records in the database and set them as 'Processed' = 'true'   5. Goto 1 **Now, what can happen in this scenario?**   1. -   2. An error can occur while pulling the records from the database      * that's fine, as in the next round we will try to get them again.   3. An error can occur while calling an external web service      * that's also fine, as in the next round we will try to send those 2 records again   4. An error can occur while calling the database for the processed record update      * **what to do now?** Are you optimistic that this will never happen?      * keep in mind that you already sent those 2 records via web service and you must not send them again at any cost     * one option is to call a database update in a loop until it runs successfully !?   5. - **The question is, how (would) you handle this situation?** _**_**UPDATE**** Code illustration:               loop     {         db = database         ws = webservice              trans = db.open_transaction              recs = trans.query_for_two_records_and_update_processed_to_true              ws_response = ws.send_text_messages(recs)              if (ws_response == success)         {             trans.commit() // what would you do if this fails?         }         else         {             trans.rollback()         }     }


Breaking into database administration

I am brand new on this site and look forward to interacting with each of you. I am graduating in June with my Bachelors Degree in Computer Information Systems with hopes of become a DBA in the future. I am currently taking a Database class now and studying SQL Server/T-SQL on the side. My experience in IT is limited to managing an Access database at my last employer for two years. What are the chances of landing a junior DBA position after I graduate?


AngularJS Directive vs Service vs Controller

I am about to start implementing a change request on my companies internal website, that will check a bunch of fields and highlight them if they match certain guidelines. For example, if the date of birth is today, that field will be outlined and the tooltip will say "Wish them a happy birthday!". The specs ask for this to be loaded after the rest of the page is done rendering, so it won't increase the load time. Since I am new to angularJS, I'm not sure of the 'proper' ways this should be done. Issues: Since this includes adding borders and images and title attributes (DOM manipulation), it seems I should be using a directive. However, this won't be reusable or 'short' like most directives seem to be. Half of the data I need to check will be returned in the original call on page load, so I would like to save that and not waste another call getting it again, which makes me think a service would be nice for storing all that data. I do know how to do this all in the controller, but that is bad bad code :P Any ideas on the best way this could be done? Basically, I will need an http call to check all the data, which will return an object with bool values for each type of 'Call Out' I need to do. Then I'll run through this list and if the value is true, add a border, image, and tooltip text. I'm not sure if this question is clear enough, so if you want me to add some details, please ask. Thank you!


How independent is Clojure from Java?

I am quite new to the Clojure world. I appreciate the fact that one has easy access to all Java libraries via Clojure interop features, but I was wondering how much Clojure stands on its own legs. Of course there are some platforms, like Android, where interoperability with Java will always be required, because the core libraries are written or exposed in Java. Moreover, since Clojure strings are Java strings, I expect string manipulation libraries to be a wrapper on the Java String methods. But for other tasks I see no reason why native Clojure libraries couldn't be developed. Think of Http, date manipulation, XML parsing, templating, JSON serialization and deserialization, OAuth, math libraries and so on. So my question is: How far has Clojure come to become independent of the Java ecosystem? Does it have its own idiomatic libraries for most of these and other tasks?


Can we live without constructors?

Let's say in some reason all objects are created this way $obj = CLASS::getInstance(). Then we inject dependencies using setters and perform starting initialization using $obj->initInstance(); Are there any real troubles or situations, which can't be solved, if we won't use constructors at all? P.s. the reason to create object this way, is that we can replace class inside getInstance() according to some rules. I'm working in PHP, if that matter


Is there a specific term for an accessor method that returns a boolean value?

I seem to recall that there is a specific term for an accessor method that returns a Boolean value but it escapes me. For example: typical methods such as:               class Example {         bool isDirty();         bool hasChildren();         bool isValid(SomeType obj);     };      I will also settle for such a term as applied to a non-member functions.


Removing the "integration test scam" - Understanding collaboration and contract tests

I've recently watched Integration Tests are a Scam by J. B. Rainsberger and am now looking for more material on the subject. I have to say, I'm shocked by how much we're doing wrong, (i.e. integration testing when we should unit test), intrigued by the concepts described by Rainsberger but also confused about how to apply them. I would like to have more of the described **collaboration tests and contract tests** but I don't know where to start. The only things that got stuck in my mind are the 4 questions the tests need to ask: **Side A:**               Do I ask the right question?     Can I deal with the answer?      **Side B:**               Can I answer a question?     Do I answer correctly?      But how do I apply this to some random method in my application stack? Is there a book or a tutorial or example out there that takes a real world example and applies these ideas of isolated micro tests? Ideally the example uses **Java, Spring + PowerMock / Mockito / EasyMoock** Any literature that deals with these concepts in general and helps me understand them better would be appreciated. Also if there are forums out there where I can ask more detailed questions about how to go about correctly unit testing and maybe even refactoring existing code and post examples would be nice. Thanks! * * * **Edit - some additional thoughts:** Is there a general rule, when to use a mock and when a stub to isolate a class under test from it's collaborators? Can it be applied to the 4 questions? The best mocking frameworks seems to be PowerMock, allowing me to precicely define for each test what class I want to have mocked and what it should return or is there anything better that you have used to ask the above questions? Are there good tutorials out there that use PowerMock to apply some or all of the given principles to some part of a real world application stack, say a DAO or a GUI? * * * **Edit 2 - an example** Just some example of the kind of methods I want to test and my thoughts.. I have a web service that saves orders. At this stage we're not too worried about the best security, so to have some, the service will also take a username and password to authenticate the save request. Once authenticated, the `OrderManager` is called to save the `Order`. Internally the manager decides if its a new order so it has to be created or an existing one that has to be updated. (That shouldn't matter to the WebSerice, right?)               @WebService     public class OrderService {         @Inject         private AuthenticationManager authenticationManager;              @Inject         private OrderManager orderManager;              public void save(String username, String password, Order order) {             authenticationManager.authenticate(username, password);             try {                 orderManager.save(orde);             } finally {                 authenticationManager.logout();             }         }      Now I am wondering: What exactly am I testing here? I'm thinking there should be tests for authentication success and failure and for order saving success and failure. But how can I split that up into the 4 questions? My class under Test is obviously `OrderService` (OS) and the collaborators are `OrderManager` (OM) and `AuthenticationManager`. (AM) So I have the following tests, please correct me here, I am just thinking aloud: **OS <\--> OM**   * OS asks OM to save an order (what kind of different parameters do I test here? `null` and `Order`? Does it matter if `Order` is correctly initialized?)   * OM answers a save call by calling some other internal method, I I test if that method gets invoked?!   * OS should not fail if OM does not fail   * OS should fail if OM fails ... What else? And then of course **OS <\--> AM**:   * OS asks AM to authenticate - I guess I test how the AM reacts to different kinds of username / password?   * ... Now my **first conclusion** : As far as the WebSerice is concerned I can only test 2 out of 4 questions: Side A. Now I have to look at the `OrderManager` and `AuthenticationManager` and see if they can answer the questions of side B. Right? Secondly - database access: Authentication and Order persisting obviously requires some data in the database in a production environment. For my unit tests however I won't need them so I'll just mock the calls to return the desired result, right? But how do I mock this? I need the `AuthenticationManager.authenticate` to pretty much do nothing, as in case of a failed authentication it will throw an `Exception`, else it has the return type `void`. How do I tell my `OrderService.save()` to use my mocked `AuthenticationManager.authenticate()`? And how do I set the `AuthenticationManager` up to either do nothing or throw an exception? Can I tell Spring to **inject** a mocked `AuthenticationManager` that will do nothing / throw an `Exception` into my `OrderService` under test?


How can you effectively use web services in an enterprise environment if you can't use transactions?

The place I'm working at is trying to establish some ground rules, and the debate we're having now is local libraries vs web services for code reuse. Web services seem to be the popular pick in most companies, and that's what most of the developers here are leaning toward. I just can't see how you can effectively use web services for any serious work. How can I safely execute multiple service calls if I can't use a transaction? Let's say I have a cron job that grabs customers from our database who meet a certain condition that they need to be notified of. They are sent a fax, an email, and a ticket is created to track the issue internally. That is 3 different service calls that would happen for each customer in a for loop. If an error occurs anywhere in there, it's possible that, for example, a fax and email is sent to the customer, but a ticket is not created. Or worse, this cron job could contain a bug on that causes it to fail at the same point every time, and it repeatedly emails the same customer. If the libraries were all local, everything could just be wrapped in a transaction, and none of that would happen. But we're using web services in this example. Note that the email and fax methods actually insert the data into database- backed queue tables, which in turn are handled by a separate cron job process. So the calls to the "send email" and "send fax" service methods could be aborted side-effect free if needed. An option is to put this entire chunk of code in the web service itself, so the web service itself would call the email, fax, and ticket creating methods in a transaction. But then we're creating a web service method just for the use of a transaction; there is no valid reason we would ever actually need to call this method from anywhere except this one cron script. How would you generally handle this method?


How do I use PowerMock / Mockito / EasyMock to use a mocked object for dependency injection?

I have an `AuthenticationManager.authenticate(username,password)` method that gets called in someMethod of a SomeService under test. The AuthenticationManager is injected into SomeService:               @Component     public class SomeService {         @Inject         private AuthenticationManager authenticationManager;              public void someMethod() {             authenticationManager.authenticate(username, password);             // do more stuff that I want to test         }     }      Now for the unit test I need the authenticate method to just pretend it worked correctly, in my case do nothing, so I can test if the method itself does the expected work (Authentication is tested elsewhere according to the unit testing principles, however authenticate needs to be called inside that method) So I am thinking, I need `SomeService` to use a mocked `AuthenticationManager` that will just return and do nothing else when `authenticate()` gets called by `someMethod()`. How do I do that with PowerMock (or EasyMock / Mockito, which are part of PowerMock)? Or is there another way to tell Spring to use some Mock instead of the real deal, when injeeting the `AuthenticationManager` into `SomeService`? Or is my design wrong? Thanks! * * * **Edit - found a solution, would like to hear comments** So I found a nice way to inject a mock without having to use a setter or package level:               @RunWith(PowerMockRunner.class)     public class TestOrderService {              @Mock         private AuthenticationManager authenticationManager;              @InjectMocks          private OrderService orderService = new OrderService();              @Before         public void setup() {             MockitoAnnotations.initMocks(this);             Mockito.doNothing().when(this.authenticationManager).authenticate(null, null);         }              @Test         public void testOrderService() {             orderService.save(null, null, null);         }     }      with OrderService like this:               public void save(String username, Order order) {         authenticationManager.authenticate(username, password);         // do something with the order...     }      Now the save method will call authenticate on the mock and the mock does nothing leaving me free to test the actual work inside my service method (which actually is calling a manager method but that was not the point ;) )


n-layers architecture design, really worth the effort?

I was building an application in .Net for almost a year (almost alone), I took the decision to build it with a 3-layer design. Recently when finished the project, I analyzed if the effort of creating this application with layer design in mind really compensate for the "benefits" obtained implementing such design. Out of port the desktop application to web without any major code rewrite and to be almost database-agnostic; I don't see any further benefits of this. Any experiences, and thoughts?


Search for object in loop or query? Who has better performance?

I have a DB that stores some complex objects of my app. When my app starts I load the objects into list and store them on the RAM. But sometimes I would like to search for an objects that fulfills conditions (filtering), even the conditions are complexes. I was always wrote a for loop (sometimes a very complex one) for this thing, that runs on these objects. But I heard recently that DB and SQL queries have a lot optimization mechanisms (dependent the DB company), and its works faster then regular search. If I understand it correctly, it's better to write a SQL query that search these objects and returns objects IDs. And then by them IDs, get the relevant objects. Its look like the ultimate solution for searching objects. But I'm a little bit doubtful about this idea, because all the time we learned that DB is slow, and it's better to load the objects to RAM and work on them... So I have two questions:   1) Are the queries actually more faster then regular search (for complex searches)?   2) Maybe its true for many many objects (thousands), but is it true for few objects (tens)?


What architecture to use for AJAX calls?

I am working on a website with PHP as backend. There are things from the front-end which I'd like to accomplish using AJAX calls. Which of these methods should I use to design them and why?   * Call to different PHP files for different uses ![enter image description here](http://i.stack.imgur.com/3EURr.jpg)   * Call to the same PHP file, with instructions on what to do ![enter image description here](http://i.stack.imgur.com/KUIKq.jpg)   * A RESTful API   * Any other better way?


Potential issues with code reviews

for clarity, **code review** = a team meeting and reviewing/sharing code What are the potentially negative aspects of the code review process in a development environment? What comes to mind for me   * Strong criticism can lead to negative interactions and feelings of animosity between colleagues.    * Laziness to read and understand new code can lead to apathetic and very general feedback.   * Considerable Time investment is required to organize and execute the review process. There must be more than this though, What negative things have you guys noticed or experienced?


I want to sell a simple calculator. What is the simplest way to implement registration keys?

I want to sell a simple calculator that will help a certain industry. This calculator would be installed on the computer (as opposed to a web service). How is a registration key mechanism implemented?


Is there a design pattern that describes the separation of a Form from a Model

I am working on a web application implemented in C#, that follows MVC conventions. This application contains a page that allows me to create or update a Wingding. The view passes a complete Wingding Model back to the controller for me to create or update. The problem is that the page also has a checkbox that allows me to create identical Wingdings for _all_ users. The current code adds a variable to the _Winding Model_ to capture that data, so it can be passed back from the view. It seems obvious to me that the page should have a _Wingding Page Form_ object that is passed back from the view to the controller, instead of adding extra variables to the Model that won't get saved to the DB. I know that this counts as separation of concerns, but is there a more specific design pattern that describes the separation of a From from a Model?


Managing resource paths in source code

I suspect this is something that many of you guys have dealt with, and I'm certain there's articles on how to do it, but I cant seem to find them. My problem is that my various constant classes in Java (read: classes containg lists of static constant values) are too many and too big, and some of them have some annoying complex static initializers. We've got a file paths class, a file name class, a constants class, a strings class, a colors class (for the swing components) and a bunch of css for the JavaFX components... it goes on and on. The CSS is manageable, the rest of it is quickly becoming not-so. having classes like this               public class Constants {         public static final String something = "Something";         public static final Path someResourcePath = staticMethodCall(RootString, dirTraversal);         public static final Image spinner = iconFindingStaticMethod(dirTraversal)         //and on and on for hundreds (not yet thousands thankfully) of lines              //and then often we have         static{             //code that determines our environment and fudges some paths as appropriate             //sometimes we ask the class loader to find some things for us             //nothing too scary, but still, static initializers are never friendly.         }     }      is good for one very powerful reason: Every java programmer out there knows exactly what this class does and how it works. The ones with static initializers might be a little confusing, but for the most part, the above is PO-Static-JO. I like that. but it also introduces a number of problems. I'll try to enumerate the ones I know of here:   1. the most obvious code smell of all: these classes are multiplying and they're all annoyingly large. We've got one for file extensions thats got a couple dozen entries, including things like `public static final String XMLFileExtension = "xml"`. That might be a bit much, but I'm not really willing to fault the dev who wrote it. It wouldn't be hard to replace references to that with the string value, but I'd like to encourage this kind of code, so I'd feel stupid doing it. But these classes are getting large and annoying.   2. use of static constants is not testable. This in itself isn't too often a problem since the values in those classes are supposed to be simple, but it does turn into a problem when you do something like `Constants.someFilePath.exists() ? a() : b()` (since there's _no way to intercept that exists() call_ , from any environment we're going to ask the actual file system if that path exists, which is a problem for testing.) We're on guice, so I'd really like to inject these values like everything else, so they can be modified by our fixtures with fake/stub/mock values.   3. It also introduces a dependency problem. Right now we have a couple of IntelliJ & Guice Modules (semi-separate code bases) under the same git repo. They all use our original module's constant files, which means all modules have a dependency with that module, but with static constants whats the solution? Copy-paste?  Some solutions I've thought of:   * we could leverage guice and simply inject every single needed constant with an `@Named` parameter. This addresses problems 2 & 3, but compounds problem 1 since the binding logic would have to either be incredibly long and contain a huge swath of duplicate registration, or employ some pretty complex composition.    * we could go the auto-generate-source-java-from-XML-or-JSON route, which I've used with Android and I believe some C# component I worked on briefly. The extra step in the build process adds a level of complexity in an area (that is: devops) that not a lot of developers are familiar with. It was nice to have just a big table in eclipse containing all my values, but the added complexity to the build process is unwanted. Furthermore the static initializer logic couldn't fit into this model.    * stay the course with Java, maybe extract a package near the route called "Environment" or "constants", and then give that package a number of constant classes that can inherit other classes with shared fields. Regarding testability, we run into java inlining final fields. We could replace each field with a simple getter, but that makes an already overly verbose problem more verbose.  I really don't know how I want to tackle this. I've been telling myself to let it become a problem for a few months now, thinking that some kind of solution would emerge. It hasn't, and know we have a kind've gnarly dependency graph, hacks around testing code with file paths, and large constant classes. What kind of solutions have you guys employed for managing these files? Am I being overly concerned and what we've got now is the best solution? Thanks guys, -Geoff


How can an developer working alone respond to a spike in server demands?

Imagine this scenario: You've created a multiplayer game app for a mobile platform such as Android. You successfully set it up with one server, you figured out how to do that. It works quite well. To your surprise, the game TAKES OFF. Server demands explode. You need to scale, but you have hardly any experience with running a single server, let alone running multiple servers in tandem. What do you do? Is there a service (Heroku-style) to help with such a thing? Anything? Or do you need to hire someone with a certain skill set and the necessary experience?


C++ returning references

Looking at making a GUI library for a game engine. I generally avoid pointers if I don't need them and in my below example I find that I don't and it works, but just curious if this design is generally considered good practice or if anyone has comments on it.               int main()     {         // all widgets are positioned and sized according to the window size         Window wndOptions("wndOptions");              Button cmdExit("cmdExit");              // the window doesn't own the widgets nor does it create the widgets so it's not responsible for deleting the widgets         wndOptions.AddWidget(&cmdExit);              // this is how you can find a control and get it casted also. make your variable a reference         Button& test = wndOptions.FindWidget<Button>("cmdExit");              test.SetPosition(50, 25);              return 0;     }      As you can see the idea is that you create your controls (button in this case) and pass a pointer to them to the Window. Then you can find the control by name returning a reference to that control in which you can manipulate the control. It's a bit pointless to use FindWidget() in this example since I have the cmdExit variable, but if I was to pass the window around this would be a way to find and use controls. The biggest issue I have is that FindWidget() might not find a widget. Right now I throw an exception as not finding a control I would deem as a true exception and not something that should happen much if at all. Any comments about the usage being done this way?


What's next after learning the basics of the C programming language?

After having learning the basics of C programming from several books (variables, arrays, linked lists, etc.), what comes next? Any suggestions of areas to extend my C programming skills to, and any helpful sources? Because I was wondering what experienced programmers did after learning the basics.


Injecting dependencies (DI) in c++ applications

I am playing with dependency injection, but i am not sure I am doing it right. Especially, I am not sure what should be the correct way to build classes with injected dependencies. Say I have a class A that creates class B. Class B depends on class C and class C depends on class D. Who should be responsible for creating class D?   1. It could be class A. However, in a large system, class A might end up creating and assembling a very large number of objects.   2. A separate builder class that will create D, C and B. A will use this builder class.   3. Some other option. In addition, I read a lot about DI containers. However, it seems that there are no major frameworks for C++. Also, if I understand correctly, DI can be performed well even without containers. Am I correct?


Architecture guidelines for a "single page web-app"

I'm going to start a side project to build a "single page" web application. The application needs to be real-time, sending updates to the clients as changes happen. Are there any good resources for best-practice approaches wrt the architecture for these kinds of applications. The best resource I've found so far is the trello architecture article here: http://blog.fogcreek.com/the-trello-tech- stack/ To me, this architecture, although very sexy, is probably over-engineered for my specific needs - although I do have similar requirements. I'm wondering if I need to bother with a sub/pub at the server side, could I not just push updates from the server when something happens (e.g. when the client sends an update to the server, write the update to the db, and then send an update to the clients). Tech-wise, I'm probably looking to build this out in Node.JS or maybe Ruby, although the architecture guidelines should to some extent apply to any underlying server technologies.


Radix exchange sort implementation?

I need a little help understanding the implementation of radix exchange sort algorithm. Radix exchange (I don't know if it's the exact name in english based literature) is a lot similar to quicksort, but uses binary representation of numbers. Firts we look the highest digit in binary representation, and then using two indexes (from the beginning of the array and from the end, we increment the first if the given digit is 0, and decrement the other if the given digit is 1). Then we swap two numbers, and then continue the work until i = j (the indexes are equal). Then we have two separate partitions and sort them using the second most important digit and so on... Mainly, I have a few questions:   1. Is this algorithm really called radix exchange or does it have some other, more commonly used name?   2. What are the advantages of this algorithm? It seems like a lot of work, and not very effective?   3. Where can I see an example of implementation of the algorithm? Maybe it will be a little more clearer on what it really is, because it's really confusing for me at the moment.


How much to test in TDD?

I am newbie to TDD (writing first project following TDD practices). I have fairly basic interface `IProfiler` and an implementation `Profiler`.               interface IProfiler     {       bool IsBusy {get;}       long Elapsed {get;}     }      A Simple Test                   IProfiler profiler = default(Profiler);         [TestInitialize]         public void Initialize()         {             profiler = new Profiler();         }              [TestMethod]         public void ProfilerInitializationTest()         {             Assert.AreEqual(false, profiler.IsBusy);             Assert.AreEqual(true, profiler.ElapsedMilliSeconds == default(long));         }      The question is : As I will have more state, Number of asserts will increase. Should I keep separate Assert to test each field or should i include all here, or should I group into 3-4 similar asserts?


Drawing Flowchart for function calculate a number in the Fibonacci Series

I'm trying make Flowchart for function calculate a number in the Fibonacci Series. But It looks like not right. I don't how draw the recursive function. Please help me how to fix it. My flowchart: DIA ![PNG](http://ubuntuone.com/7SrSmJWoTpuQekGY43Hcqa) This is my code:               #include <iostream>     using namespace std;          long long Fibonacci(int input);          int main()     {         cout << "Input Fibonacci Index number: ";         int Index = 0;         cin >> Index;         cout << Fibonacci(i) << endl;         return 0;          }     long long Fibonacci(int input)     {         if (input < 2)             return input;         else         {             return Fibonacci(input - 1) + Fibonacci(input - 2);         }     }


Using streams as method parameters and/or return types

So let's say I have a 'Transformer' interface that can transform one file-type to another. Let's say I also wish to use streams to provide the data to the Transformer. Which is the approach that is considered 'best practise';               public InputStream transform(InputStream data);      OR               public void transform(InputStream originalData, OutputStream newData);      Although the first method seems to be slightly more concise to me (ie, you get an inputstream that you can consume immediately) it seems to violate the whole 'creator of a stream should be the one who closes it' principle. The second method, whilst needing a bit more work on the part of the client to handle the outputstream, seems like it might be more useful in some cases (ie, passing a ServletOutputStream as the 'newData' argument) and the client code will handle all opening/closing of streams. I am leaning towards the second method but I have seen both used in various APIs I have come across and am wondering if there are situations where one would be preferred over the other?


Are "Stocks" a TDD/Unit testing anti pattern?

From Martin Fowler's Mocks Aren't Stubs he states that **Stubs** provide canned answers to calls made during the test while **Mocks** objects pre- programmed with expectations which form a specification of the calls they are expected to receive.   In addition several sources state that Stubs **shouldn't** fail tests, but Mock **could**. So what about this:               $validator= $this->getMock('ValidatorService');                  // Set up the expectation for the isValid() method             // to be called only once and with the string 'textToBeValidated'             // as its parameter and returns true or false.             $validator->expects($this->once())                      ->method('isValid')                      ->with($this->equalTo('textToBeValidated'))                      ->will($this->returnValue(true));      This came up in a code review in a project I'm working on and we called it a **Stock** ( **St** ub - M **ock** ). Why you ask?!   1. It set an expectation for `isValid()` to be called only once and with certain input like a Mock.   2. It returns a canned answer like a Stub. I get a feeling that this is wrong, but what if we used a pure Stub only:                $validator->expects($this->any())  //<-- can't fail the test now                          ->method('isValid')                          ->will($this->returnValue(true));   //<-- canned answer        * I can't verify that the method `isValid` was called only once with the right parameters.   * If the test passed I'm not sure that it passed for the right reason. Maybe `isValid()` was called twice and that caused it to pass. So let's use a pure Mock instead:               $validator->expects($this->once())                          ->method('isValid')                          ->with($this->equalTo('textToBeValidated'))        * I can't verify that my function works correctly, because I only verified that call to `isValid()` was successful. Maybe there is a bug in the rest of my code using the `ValidatorService`. I know some people will talk about state vs behavior verification, but the way I see it the only way to be sure that the test passes for the correct reason is to to use a Stock (i.e. verify the behavior and final state). Of course the other option is to write 2 test for every test criteria. One using a Mock and an identical test using a Stub. However, that will result in a TestOverflow (a huge number of nearly identical tests). What is the correct way to have a concrete test of a function using a dependency?


Securing web services

How to approach securing webservices? I can think of using one of the two approaches below   1. sending a user name password in every request for validation   2. Sending a time based token (GUID or some similar long string) In the first approach I have to query a database every time in most cases an RDBMS to authenticate a user. In the second I now make a user name password authentication only once and then return to the user a time based token. All future business requests are authenticated via this token. On expiry this token will need to be recreated by the calling client. Both approaches seem to have their own pros and cons. Which one would you recommend in which circumstances and what would be your reasons for the same? Perhaps a specific condition where one favors the other.


MVC + 3 tier; where ViewModels come into play?

I'm designing a 3-tiered application using ASP.NET MVC 4. I used the following resources as a reference.   * CodeProject: MVC + N-tier + Entity Framework   * Separating data access in ASP.NET MVC I have the following desingn so far. **Presentation Layer (PL)** (main MVC project, where **M** of **MVC** was moved to Data Access Layer):               MyProjectName.Main         Views/         Controllers/         ...      **Business Logic Layer (BLL)** :               MyProjectName.BLL         ViewModels/         ProjectServices/         ...      **Data Access Layer (DAL)** :               MyProjectName.DAL         Models/         Repositories.EF/         Repositories.Dapper/         ...      Now, PL references BLL and BLL references DAL. This way lower layer does not depend on the one above it. In this design PL invokes a service of the BLL. PL can pass a View Model to BLL and BLL can pass a View Model back to PL. Also, BLL invokes DAL layer and DAL layer can return a Model back to BLL. BLL can in turn build a View Model and return it to PL. Up to now this pattern was working for me. However, I've ran into a problem where some of my ViewModels require joins on several entities. In the plain MVC approach, in the controller I used a LINQ query to do `join`s and then `select new MyViewModel(){ ... }`. But now, in the DAL I do not have access to where ViewModels are defined (in the BLL). This means I cannot do joins in DAL and return it to BLL. It seems I have to do separate queries in DAL (instead of joins in one query) and BLL would then use the result of these to build a ViewModel. This is very inconvenient, but I don't think I should be exposing DAL to ViewModels. Any ideas how I can solve this dilemma? Thanks.


Web design pattern

I am building a small website, in PHP and I am using MVC design pattern for the UI.   In the future I will need to add mobile support for my website. It will be in the sub domain "m" like everyone. All the web is new for me, and I am new with MVC too. I did for each page View, Model and Controller. The Views and the Models are in some internal directory, and the controller is in the public directory of the server (the servers root directory). **My Questions:**   1. Do I need to create a new MVC design for the mobile pages, or can I use the Model of the regular website?   2. Most of sites have "m" sub-domain for mobile web pages. But the only thing that need to change is the View part. If the public page is the Controller, why not to create only Views for the mobile pages, and the Controller will decide which View will present? Like:              if ($isMobile) {           include 'mobiles\main.php';       } else {           include 'web\main.php';       }      With the "m" sub-domain, you must have different Controller. Not so?


How to protect my php code running on a client server?

I'd like to ask how to protect my code that is running on a client server from being altered and/or copied.   It's running on Ubuntu Server with the standard Apache Php Mysql stack.   Any software needed would preferably be open-source. I'd also like to terminate the application when there is a license problem.   Doing this using my code is possible but since it's php the client could alter the code to prevent this from happening. Thanks in advance.


Is byte stuffing required when using a packet field length

I'm involved in a project which involves implementing a binary protocol that will be transmitted over TCP. During our early discussions we have hit a brief snag on deciding whether byte stuffing is required if we decide to include the packet length in the field header. For example. If our packet structure was like so:               [STX] [PACKET LENGTH] [PACKET ID] ..... [ETX]      Do we need to byte stuff? One of my colleagues seems to say that given we know the packet length then even if a special character i.e. STX, ETX appears in the bytes it will not matter as we are reading [Packet length] amount of bytes anyway. Seems to make sense but I'm not 100% sure if that reasoning is quite right. Please note that we are not using existing protocol handler type modules such as proto-buf but designing this protocol ourselves for our own use. To confirm what I think I'm meaning when referring to byte stuffing: > Byte stuffing is a process that transforms a sequence of data bytes that may > contain 'illegal' or 'reserved' values into a potentially longer sequence > that contains no occurrences of those value Taken from Wiki - Consistent Overhead Byte Stuffing