PHP to Java career change

> **Possible Duplicate:**   >  Going from PHP to Java I have been working at my current job for about 4 years. I have been doing PHP for twice as long. I am completely self taught (with lots of internet and friends help). I recently found a job posting for a Java developer and I am wondering what I need to know about Java to prepare. I took 2 college course on Java so I am looking a little beyond Hello World stuff (actually just installed Eclipsed and wrote it again). I hear they also do Flex so anything on how Java and Flex work together would be great as well. My first step is going to be to remake a project I built in PHP using Java. This is similar but the answers aren't very specific. Going from PHP to Java Thank you and I apologizes if this should be community wiki.


What should one consider in choosing a language for web application development?

To begin with, this isn't a question about which language one should choose :) We're considering a language switch as our general direction is changing from content-driven web sites to data/action-driven web applications. What sort of factors should one think about in order to successfully evaluate the various languages out there. A few factors I've thought of so far, along with a supposed importance level:   * Level of knowledge of language X within the company [medium/high]   * Tooling available [medium]   * Community size & activity [medium]   * Availability of developers [medium]   * Cost of developers [medium] Frameworks are also an important consideration, however I'm just trying to focus on the language-selection question first :)


Standardization across an organization: Good or Bad?

Currently I work for an java shop that places a high value on standardization. This includes common things(styles, javadocs, formatting, etc.) on to what I consider slightly more draconian measures(IDE, development OS, toolsets, etc. ). It is common to hear phrases from more old hands like "it helps when we are all working with the same tools/looking at familiar code". Sometimes I agree and sometimes I feel like there may be a better way. Also sometimes I encounter older organizational standardization practices that are in direct conflict with more state of the art community practices(most notably accursed bad exception handling practices). I also encounter cases where folks would prefer that code be written in a manner that looks and feels like what has been written there for years (sometimes decades)rather than code that takes advantage of the industry lessons that have been learned in the interim. I understand there are cost and schedule benefits to be realized through standardization. So the question is how can technology managers realize them without stifling innovation and/or turning off developers onboarding from college or other jobs with affinities for toolsets and techniques that are not the "standard"?


Is there such a thing as a .NET developer curriculum?

One of the constructs I miss from academia is a curriculum for what must be covered in order to get a degree in computer science. I started with a .NET shop almost three years ago without having any .NET training. Given my experience with the field and trying to stay up on things via conferences, blogs, podcasts, etc., I feel I'm drowning in a sea of infinite depth. Having some structure works really well for me, so I thought the closest thing would be certification. It appears the Microsoft Certified Professional Developer (MCPD) would be the closest fit; however, others have said the Microsoft certs aren't really geared for the "get a book, study, pass the test" model -- you need to have actual experience. What if my experience is flawed or doesn't exercise techniques that others consider important? The other attractive part of certification is that it is standardized, meaning that both myself and employers know that I have demonstrated knowledge over certain topics. I do C#/WPF development for my job and would love to get my hands on a list of things every .NET/C#/WPF developer should know. Yeah, I get the most common stuff like object-oriented design, events, syntax, etc. But the language (and the framework) has many subtleties -- extension methods, lambda expressions, delegates/events, data binding, threading, operator overloading, weak vs. strong events. Microsoft doesn't seem to offer a language-specific or framework-specific exam, so I'm left to books/blogs/wikis to fill in the gaps. I'm committed to improving my craft through learning and experience. How do you as developers handle this situation? Thanks in advance!


Who should be the architect in an agile project?

We are developing the agile way for a few months now and I have some troubles understanding the agile manifesto as interpreted by my colleagues. The project we are developing is a framework for future projects and will be reused many times in the next years. Code is only written to fulfill the needs of the current user story. The product owner tells us what to do, but not how to do it. What would be right, in my opinion, because he is not implicitly a programmer. The project advanced and in my eyes it messed up a little bit. After I recognized an assembly that was responsible for 3 concerns (IoC-Container, communication layer and project internal things), I tried to address this to my colleagues. They answered that this would be the result of applying YAGNI, because know one told them to respect that functionalities have to be split up in different assemblies for further use. In my opinion no one has to tell us that we should respect the Separation of Concerns principle. On the other side, they mentioned to prefer YAGNI over SoC because it is less effort to implement and therefore faster and cheaper. We had changing requirements a lot at the beginning of the project and ended up in endless refactoring sessions, because to much has to be adapted. Is it better to make such rather simple design decisions up front, even there is no need in the current situation, or do we have to change a lot in the later progress of the project?


Where to put common shared methods

I have a bunch of methods that are commonly used everywhere. Right now the codefile is named globals, to represent the fact that they are... in fact... global. However, I do not like this. I want to group these into a class and pass an interface around. I'll make only one instance, but I'm not falling into the singleton trap here. First of all, what should I name the class. I want to avoid the globals name because I'm afraid maintainers would get the wrong idea. Also, how should I consider splitting up such a set of methods so that behavior can change and adapt? The set of methods contains stuff like:   * Conversion tables   * Clipboard interaction   * Managing built fonts   * Common drawing methods   * Providing an interface with access to often used resources


My boss decided to add a "person to blame" field to every bug report. How can I convince him that it's a bad idea?

In one of the latest "WTF" moves, my boss decided that adding a "Person To Blame" field to our bug tracking template will increase accountability (although we already have a way of tying bugs to features/stories). My arguments that this will decrease morale, increase finger-pointing and would not account for missing/misunderstood features reported as bug have gone unheard. What are some other strong arguments against this practice that I can use? Is there any writing on this topic that I can share with the team and the boss? I find this sort of culture unacceptable to work in but want to try and change it before jumping ship. Any input is appreciated.


Is is reasonable to be asked to record defect culpability?

I fear this question is going to send shivers down the spine, and/or instinctive anathema of the very thought... Basically: **has anyone ever been asked to diagnose and assign individual culpability to defects?** In other words: to be asked to work back through the code, to try and establish who was responsible for the line/function/module that introduced it in some way, and then record that persons name in the ticket so that a report can breakdown defects not only by severity, component, estimate, etc - but also by team member. I’m asking this because - like me - you might want to just try and get inside the mindset of a manager who might propose it, and in so doing, understand why they might think this is extremely useful. Surely, you might ask, this time would be better spent actually fixing the defect?


Bounty points for fixing bugs?

Ever heard of a company awarding bounty points for bugfixes? Making team members work to do the most, as some bonus money will be dependent on it? Having them split, or pay bounties to others to test, so they don't 'lose' points when it reaches a UAT environment? I heard this from management for the first time today. To me, it sounds like a pretty ridiculous approach to software development. It sounds as if the team members will be competing with each other in a non-productive way, essentially slashing the productivity they've got going now. Any thoughts? Have you ever seen something like this actually work? Did it help or hurt the team? _**UPDATE 4/6/11:_** This approach was cancelled due to feedback from the whole team! I'm happy to learn that it wasn't just me thinking it wasn't a great idea.


Is it good practice to analyse who introduced each bug?

I used to analyse performance of programmers in my team by looking at the issues they have closed. Many of the issues are of course bugs. And here another important performance aspect comes - who introduced the bugs. I am wondering, if creating a custom field in the issue tracking system "Blamed" for reporting the person who generated the problem, is a good practice. One one hand it seems ok to me to promote personal responsibility for quality and this could reduce the additional work we have due to careless programming. On the other hand this is negative, things are sometimes vague and sometimes there is a reason such us "this thing had to be done very quickly due to a client's...". What to you think?


Assigning Blame for Bugs versus Giving Rewards for Fixes

In a team that I used to work for, there was a policy that if you introduced a memory or other resource leak, you got a 'dummy of shame' hung on your door until you found the next resource leak. While it was effective at finding resource leaks, I felt like it placed more emphasis on blaming others rather than working together to solve problems as a team. Am I being unreasonable in thinking that this policy contributed to a lower sense of team cohesion? Am I also being unreasonable in thinking that we should have rewarded those people who found and fixed the issue?


Multiple long polling requests: bad idea?

I am designing a web server that handles multiple things such as a user-to- user chat, a user-to-group chat, friends request, forum etc. The chats have to be real-time chats, the friends requests should be notified in real-time to the user, and the users should be instantly notified about the new topics on the forum. I use Spring and I implemented long polling to lower the latency and the number of requests. In theory long polling works well for one thing (a chat for example). The problem here is that the client has to be notified for multiple reasons: new message on chat, new message on forum, new friend request etc. The naive solution would be to use long polling requests for each action, but it leads to having all the clients opening four or five requests at the same time. Can the server easily handle this or should I manage to create a system so that every notification is returned through only one request? Is there another solution?


Special feautures of each of these languages that make them special

I interested about C++, C#, Java, Python, Ruby and Perl. All this languages are very popular and I believe that each one have something that make people to choose them. What is that special thing that each of this language have that makes people to choose them? I want the answer to be in this form e.g: C# have _this_ and _this_. C# is the best option if you want to do _this_. Note: I don't asking which language is the best, i just want to know the power of each of these languages.


How to choose a code style for C++

When starting to learn one new language, we have to choose perfect code style such as types or file name's first letter should be uppercase or lowercase, etc. But when I started to learn C++, I did not find any official common code style as I did for Java. A popular one is Google's, yet someone told me, we should keep the style of our company. But I think that no one will work in one company for a whole life, so it could be better for him to choose a popular common code style if some company's code style is ugly. How should I choose a code style for C++? Is there any official, common, popular code style that is generally used? Can I write C++ code with the style I use for Java? I think Java's code style is perfect.


Do I continue developing an alternative existing solution, or am I wasting of time?

Almost 2 years ago I had need for a monitoring system, that monitored servers ping times, databases and various other metrics, but also things things like my email inboxes (for unread email), my game servers, webservers, and lots various other stuff. Nagios was the only system I'd used seriously, I liked it's architecture a lot (add a check with a python, bash, ruby, perl script, etc), but hated many things like the interface, the lack of decent remote check support and one of the biggest things was having to restart the service after any configuration change. I Googled around a _bit_ for other solutions, but as a developer, I didn't spend enough time Googling and found it easy to open up my IDE and start writing code for a new solution. After a few hours I had something I thought was promising, had something functional in a few days and after a week or two I released The Upsilon Project (http://upsilon-project.co.uk). I've invested a few evenings and weekends over the last 2 years, but I've got a system that is totally perfect for me. It turned out better than I could have ever expected and I'm mostly happy with the technical functionality (respectable web interface, online configuration reloads, far better scheduler). Now the next stage is pretty simple, it has been open source since the beginning (naturally), so I posted it around a few sites, once including reddit, and got some interesting feedback.   * "Yet another monitoring _solution_ "   * "Ugh, it's Java and XML"   * $X already does that (in particular, Sensu - http://sensuapp.org/ is eerily similar in architecture and objective) So, I guess the last point is what bugged me the most, but it should not have come as a surprise, I didn't do my research I suppose because writing code is more fun! Now, I'm suppposed to be asking a question, so here it comes; The Upsilon Project _hasn't_ been a waste of time for me, because of this;   * I've learnt a _lot_ , mostly about the process of open sourcing a project (news, how difficult it can be to get interest, a community)   * Stable, effective build pipelines are _ seriously hard_.    * Effective, comprehensive documentation _sucks_ to write.    * Negative feedback really hurts, but it seems a good motivator to improve.    * I've got a perfect system that works for me.  But it now _could_ be a waste of time if I invest more into it;   * Nobody is using my project, and many other solutions (Sensu in particular) are further along and have a community.    * Any features now are surplus to my personal immediate requirements.   * My contributions into other projects could help more, rather than further developing another tool.  My question to you is, **do I continue with the Upsilon Project?**


Best practices for using HTTP sessions(Java)

My Question is not about how to use HTTP session or how values are being used in session. Question is more oriented about approach. In my current application there are few values being stored in the Session and we require those values every now and than, here are few values we fetching from session   1. Store   2. Language   3. Customer   4. few others I can fetch these values from session like               request.getSession().getAttribute( "name" )      I need those values not directly in my Controller, but in other layer (say Facade) so I have 2 options   1. Pass each required values to Facade method by `request.getSession().getAttribute( "name" )`.   2. Create a method in each Facade Class like. Method in Facade                private Object getSessionValue(final String key) {         ServletRequestAttributes reqAttr = (ServletRequestAttributes) RequestContextHolder                                 .currentRequestAttributes();                 return reqAttr.getRequest().getAttribute(key);     }      Though both are working find in my case, but with one exception, I need to have this method on each Facade Class or need to fetch each object in Controller. Is there any other way or approach which might be more clean or my current approach is fine


What is an example of a computationally impossible business problem?

I have coworker who refuses to accept the reality that Turing machines (and Von Neuman machines by extension) cannot solve their own halting problem stating: > You can do anything with enough time and money. He also dislikes theoretical problems arguing that: > In our field, we'll never run into those questions. We're application > developers, not theoretical scientists. Is there a good example of a business problem that is computationally impossible that I could use to help convince him of this?


Question regarding LinkedList in Java

When I was reading a book for SCJP, I came across the following paragraph. > A LinkedList is ordered by index position, like ArrayList, except that the > elements are doubly-linked to one another. This linkage gives you new > methods (beyond what you get from the List interface) for adding and > removing from the beginning or end, which makes it an easy choice for > implementing a stack or queue. Keep in mind that a LinkedList may iterate > more slowly than an ArrayList, but it's a good choice when you need fast > insertion and deletion.. What makes a LinkedList to iterate more slowly than an ArrayList ?


Does a web application framework require an application level plugin system?

Does using a web application framework, Spring, CakePHP, Django, etc., mean I do not need a plugin system for my main application, as in I don't have to build, essentially, a framework on framework? Does the framework serve as the entry points for my application, so I can use things like Dependency Injection for better testing? Does a framework provide the environment for me to do this for what I need in my application, or does the application need to build a additional plugin system? EDIT: Is this better for Stackoverflow?


What are the alternatives to resx file

I am developing a Windows application and I want to store all the text for labels, radio buttons, buttons, check boxes and column headers of grids at one place. I have tried using a class file, an xml file, a database table and a resource file. I found that a class file is the best way to store all these texts, but I want to know is there any alternative way? If I am using a class file then I will have to recompile the project if any text changes. Will a resource file work properly for large amounts data? What about a dictionary or storing data in variables?


Querying types in a co- or contravariant way

I posted a c# feature request here; however, I do not get a lot of attention there. Therefore I am asking you here, what you think of it. * * * The `in` and `out` keywords in generic type declarations are useful; however, due to their nature, their application is limited to a small number of types. What I am suggesting here, is to be able to use them in declarations of variables, fields, parameters and possibly properties in order to restrict the set of possible operations on any generic type in a dynamic and temporary way. This would considerably increase the cases where co- and contravariance could be used. Examples               // A List of a more derived type can be passed     public void ReadList(IList<out MyType> list)     {         MyType item = list[0];  // OK         list[0] = new MyType(); // DISALLOWED because of "out" keyword!         list.Add(new MyType()); // DISALLOWED because of "out" keyword!     }          // A List of a less derived type can be passed     public void WriteList(List<in MyType> list)     {         MyType item = list[0];  // DISALLOWED because of "in" keyword!         list[0] = new MyType(); // OK         list.Add(new MyType()); // OK     }      \-- **UPDATE** Taken these declarations               class LessDerived { }          class MyType : LessDerived { }          class MoreDerived : MyType { }      You could use the methods shown above like this               var listOfLessDerived = new List<LessDerived>();     var listOfMyType = new List<MyType >();     var listOfMoreDerived = new List<MoreDerived>();          ReadList(listOfMyType);     ReadList(listOfMoreDerived);          WriteList(listOfMyType);     WriteList(listOfLessDerived);


How can I approach creating an efficient algorithm for maximizing value with these specific constraints?

I'm having trouble coming up with an approach that isn't n^2 for this problem. Here's a contrived, simplified version I've come up with: Let's say you're a company that needs 4 employees to launch in a new city, a manager, two salespeople, and a customer support rep, and you magically know how much impact every candidate will have and how much salary they require to take the job. Your table of potential employees looks something like this:               Name           Position       Salary     Impact     Adam Smith     Manager        60,000     11     Allison Brown  Salesperson    40,000     9     Brad Stewart   Manager        55,000     9     ...etc (thousands of records)      What algorithmic approach can be taken to find the maximum "impact" while still filling all the positions and remaining under, say, a 200,000 budget? Thanks!


Giving team members more decision-making power led to very long arguments, blocking progress since there is no one with the final say

Currently we use Scrum with the exception that our Scrum Masters sometimes act as project managers rather than facilitators of the Scrum process. About half of the time team members pull tasks on their own, but half of the time the Scrum Master assigns the tasks to team members. I would like us to fully adopt self-organizing teams. However when we tried giving team members more decision-making power, it led to very long arguments between team members, and since there would be no one with the final say, these arguments would block progress. Do you think there is a way to minimize arguments with self-organizing Scrum teams?


Gathering IP address and workstation information; does it belong in a state class?

I'm writing an _enterprisey_ utility that collects exception information and writes to the Windows Event Log, sends an email, etc. This utility class will be used by all applications in the corporation: web, BizTalk, Windows Services, etc. Currently this class:   * holds state given to it via public properties   * calls out to .NET Framework methods to gather information about runtime details. Included are call to various properties and methods from `System.Environment`, `Reflection` details, etc. This implementation has the benefit of allowing all those callers not to have to make these same calls themselves. This means less code for the caller to forget, screw up, etc. **Should this state class (please what's the phrase I'm looking for [like DTO]?) know how to resolve/determine runtime details (like the IP address and machine name that it's running on)?** It seems to me on second thought that it's meant to be a class that should hold state, and not know how to call out to the .NET Framework to find information.               var myEx = new AppProblem{MachineName="Riker"};          //Will get "Riker 10.0.0.1" from property MachineLongDesc     Console.WriteLine("full machine details: " + myEx.MachineLongDesc);          public class AppProblem     {         public string MachineName{get;set;}         public string MachineLongDesc{             get{                 if(string.IsNullOrEmpty(this.MachineName)                 {                     this.MachineName = Environment.MachineName;                 }                 return this.MachineName + " " + GetCurrentIP();             }         }              private string GetCurrentIP()         {             return System.Net.Dns.GetHostEntry(this.MachineName)                          .AddressList.First().ToString();         }     }      This code was written by hand from memory, and presented for simplicity, trying to illustrate the concept.


Testing interaction with large CRM database

In our company we have two large systems, basically they are scoring and CRM. Both have large SQL Server databases running on Windows servers on the intranet. These two databases are managed by other department, which we have a direct contact with. Neither of those systems have any external APIs except for some stored procedures (hereinafter "SPs"), which we use to input all the data from our (web-dev team) two applications, which are a public web site and a web-based CRM. **There are problems** which make this kind of integration a nightmare:   1. There are no proper copies of databases for testing. There are some occasional copies which may or may not be up-to-date and being synced manually, which make them practically useless in "ASAP-situations" (all the time).   2. All sorts of modifications in stored procedures code are being made straight on the production databases (!!!), which obviously cause us a lot of problems.   3. Stored procedures code is not documented, poorly commented and mostly not well-written. Just to say that I've spent last two days "decrypting" two SPs, one of which is ~2400 SLOC long and has many magic numbers and vars like `@str1`. **To make it easier and safer** :   1. We made kind of "API-server", which is basically a SOAP server which does queries to SPs and gives back whatever queries return together with some nice status messages. This helps us decouple our apps from the chaos, but it barely simplifies our task when it comes to writing and tesing new functionality.   2. We store some IDs and other constants from these databases in our databases to prevent using magic numbers in our code whenever possible, but still we have to collect and fill in all the data manually with sqlcmd (which is very uncomfortable because of the Windows `cmd` disability to handle copying, pasting and displaying text). I wish we could have some proper process of testing interaction with those databases, but what we have today is just another copy of CRM database which we have to sync manually somehow. **My questions are** :   1. How can we make all the changes made on production databases automatically propagate into testing copies? I can think of something like `.bat`-script, but maybe there are better tools. I doubt (because of previous experience) we can ask other department to do some replication, so I'm asking for something we can make ourselves and convince that other department to use.   2. How can we easily sync some data without copying all the data? For example, we need to have an up-to-date copy of all dictionaries/taxonomies, but not the data about clients (which is a lot of data and will take significant time to copy). Again, I'm thinking of some script, but may there be something with just a bunch of checkboxes to select.   3. What is the best approach for testing the interactions through our "API-server"? I mean, suppose I made a request via SOAP with some fake data and no errors occured - how can I be sure the data is there in that external DB and it is consistent? It is sort of black/grey box testing and I don't know how to deal with it.


Google review microformats, microdata, RDFa, oh my!

I'm developing a website which includes a section for reviews. I want to include Google's microformat for review information so that details of the review show up in Google's snippet thingy, like this: ![Review snippet](http://i.stack.imgur.com/Q8RIa.png) However, according this page, Google supports three different formats for the review data, "microformat", "microdata" and RDFa. They all seem to do exactly the same thing, though, and I have no idea which one to choose... RDFa looks nice - in that the data is fairly separate from the actual content (which makes my life a bit easier). Except it's based on XML namespaces, which isn't going to play well with HTML5 (the site isn't HTML5 yet, but I imagine it will be ported eventually). The "hReview microformat" seems to use special CSS classes to denote the various sections of the review, which seems like a bad mix of concerns to me... So I'm kind of leaning towards the "microdata" format, which looks like it's closer to the HTML5 way of doing things (i.e. no special namespaces). An example of that would be (from the page I linked above):

         L’Amourita Pizza         Reviewed by Ulysses Grant on         <time itemprop="dtreviewed" datetime="2009-01-06">Jan 6</time>.         Delicious, tasty pizza in Eastlake!         L'Amourita serves up traditional           wood-fired Neapolitan-style pizza, brought to your table promptly           and without fuss. An ideal neighborhood pizza joint.         Rating: 4.5

      But as I said, all the formats are basically the same, just slightly different... which one should I choose?


Copyright statements in source code

Ever since I started programming I've seen a header at the top of most code files indicating some sort of copyright: e.g.               /* Copyright (c) 1998 Innotech */      or               /* Copyright (c) 1998-2008 Innotech */      Conceptually I get the idea... depending on your wants/needs it _roughly_ translates somewhere between: > Hey check it out! I made this! I'm awesome! to > Don't copy/redistribute this! Our lawyers will come after you if you do! On the one hand I find the whole thing somewhat humorous as often this is a file that no one outside of in-house developers will ever see, but **_presuming_** this line may actually one day "mean something" I'm curious about the date part.   1. Does a single date imply that the author claims copyright of the file from that date until eternity?   2. If a date range is used, and not kept up to date has the developer invalidated his/her own copyright beyond the date range?   3. Without some additional legal filing of some kind - does the copyright header provide any real legal strength of any kind? or are we all just fooling ourselves.


Queries about commercial products about using freewares libraries

I'm looking at developing some commercial product (sell for money, only binaries, no sourcecodes). I have read up on open source licensing, but I just could not understand if what I want to achieve is possible. Will need some bros to walk me through. Like I mentioned, I looking forward to create a simple commercial product, I might be looking at using json for communication. I saw quite a number of favorable comments for Jackson JSON. Is it legally advisable for me to use it's library, but do not distribute my own source code? Or is there any other condition that I have to adhere to before I can sell my product without distributing my own source code? I won't be modifying the Jackson library at all, only calling its method. I definitely have no intention of paying to obtain a separate license to allow me not to distribute my source code. If this is not feasible, any other json library that I can look at? ps:I hope that there will not be answers directing me to read up on the license, as I have read, but do not understand the advise legally.


What would a piecework-based payment system for software development look like?

In software development, a developer is usually paid either annually (by fixed salary) or by the hour. For the most part, it seems like this works. However, I've seen industries where professionals are paid for the task. For instance, in agriculture a worker is paid per bushel. In sales, a worker is paid by commission most commonly. Would it be possible to pay a developer by delivered item? How could we calculate what a single "item" of software would be? Would this incentivize more efficient development? Would it be more/less fair to the developer, or the employer? Would this be similar/different from a "results-only-work- environment"?


How to ensure that a member variable is initialized before calling a class method

There's a class with a parametrized constructor that initializes a member variable. All public methods of the class then use this member variable to do something. I want to ensure that the caller always creates an object using the parametrized constructor (there is also a setter for this member variable) and then call that object's methods. In essence, it should be impossible for the caller to call any method without setting a value to the member variable (either by using the parametrized constructor or the setter). Here's the catch - there is just one method that itself generates a value to be initialized in the member variable (and returns it) - and to call that function, one would need a default constructor. Currently, a caller can simply make an object using the default constructor and then call that object's method - I want to avoid checking whether or not the member variable is set in each and every one of the 20-odd methods of the class (and throw an exception if it is not) - except for the one method mentioned above. Though a runtime solution is acceptable (better than the one I mentioned above); a compile-time solution is preferable so that any developer will not be allowed to make that mistake and then waste hours debuggging it! Update: Here's an artist's impression of the current implementation in code:               class MyClass     {     private:     string m_strProperty;          void InternalNonStaticMethod(int iSomeParam);          public:     MyClass(string strValue)     {     m_strProperty = strValue;     }          MyClass() {}          void setProperty(string strValue)     {         m_strProperty = strValue;     }          string MethodOddManOut()     {         /* Do some computations to generate a value for the property */         string strGeneratedValue("");         InternalNonStaticMethod(4);         /* ... */         return strGeneratedValue;  // The value has to be returned and this method cannot simply update the member due to design issues that are beyond the realm of this question     }          void MethodLikeEveryoneElse()     {         /* Do some computation based on the property */         string strTemp = m_strProperty + "EXTEND";              /* If strProperty is empty/garbage then this is going to fail miserably            Trying to avoid the following snippet at 20 other similar methods:            if (!strProperty.empty()) {                strTemp = m_strProperty + "EXTEND";            } else {                throw exception            }         */     }          void MethodLikeEveryoneElse2()     {         /* Similar to the above method */     }          }      The caller would be a function in some other class using it like this:               void MethodThatUsesThis()     {         MyClass objA;         m_strHandle = objA.MethodOddManOut();  // Save the handle as a member of this object              /* Some other lines of code */              objA.setProperty(strHandle);         objA.MethodLikeEveryoneElse();     }          void AnotherMethodThatUsesThisLater(string strHandle)     {         MyClass objA(strHandle);  // The handle that the above method received was passed to this method since they are in different classes         objA.MethodLikeEveryoneElse2();     }      This code snippet is bound to raise tons of allegations on the horrendous design that is being implemented - but my only defense is, this is legacy code (ha! you saw this coming) and I only have the right to change anything in class A (it's more of an API and a library module) but the caller is not in my jurisdiction.


How do you balance between "do it right" and "do it ASAP" in your daily work?

I find myself pondering over this question from time to time, again and again. I want to do things the right way: to write clean, understandable and correct code that is easy to maintain. However, what I end up doing is writing patch upon a patch; just because there is no time, clients are waiting, a bug should be fixed overnight, the company is losing money on this problem, a manager is pressing hard etc., etc. I know perfectly well that in the long term I am wasting more time on these patches, but as this time spans months of work, nobody cares. Also, as one of my managers used to say: "we don't know if there will be a long term if we don't fix it now." I am sure I am not the only one entrapped in these endless real/ideal choice cycles. So how do you, my fellow programmers, cope with this? UPDATE: Thank you all for this interesting discussion. It is sad that so many people have to choose daily between a quantity and a quality of their code. Still, surprisingly many, people think it is possible to win this battle, so I am going into the trenches too.


Does craftsmanship pay off?

> **Possible Duplicates:**   >  Prototyping vs. Clean Code at the early stages   >  Frankly, do you prefer Cowboy coding? After working in a number of companies, I am starting to realize that my commitment to writing high quality, well tested software, does not necessarily lead to career advancement, especially when managers with non-technical backgrounds do not see the benefits of maintainable code, and prefer developers who have a semblance of high productivity, while racking up mountains of technical debt. That said I tend to stick to well written code to because I find it intrinsically rewarding - that feeling you get when you know you have done a job well, even though you know you won't get credited for it. In part I can close the productivity gap by adopting different technologies and approaches while still writing clean code - solutions include dynamic languages, polyglot programming, and convention over configuration. But my dilemma remains - does craftsmanship pay off?


Good design: How much hackyness is acceptable?

> **Possible Duplicate:**   >  Prototyping vs. Clean Code at the early stages I'm right in front of a difficult decision. I have a problem in my codebase (it's in C++), which I could solve in two ways:   * A) Add one line of code   * B) Rewrite ~7500 lines of code, adding roughly 1000 for an additional messaging switchboard class Now, at that point any sane person would probably tell me to chose A, **but** : Solution A would be **hacky**. In my case what I mean by this is that it would:   * Involve adding coupling between two classes that normally shouldn't know of each other, and shouldn't interact except over an external manager class   * Lower flexibility   * Cause future classes in the same league to have the same problem, thus creating more hackyness if the solution isn't changed **I'm sorry for the lack of concrete information, but explaining my situation probably would take 1,5 A4 pages of paper - and the decision is really a general one.** So, what do you think:   * Should I choose solution A or B?   * How hacky are things allowed to get in a project where clean and logical code plays a great role?   * Are there any general guidelines on avoiding the phenomenom of "hacky code"?


Is it sometimes reasonable to cut corners and expect to re-write software in a couple of years?

I work for an organization with one developer (me) and one DBA. When I started, the previous developer had developed applications that had bad architectural practices and it was getting and more time consuming after a couple of years to add features, fix bugs as the story usually goes. I came in and started re-writing a couple of apps from scratch. Now being the only developer, it's taking me quite a while to stick with TDD, do good UX, good architectural principles, create common libraries for business logic as it's used by many applications, etc. I'm wondering if in an environment like this it'd be more feasible to cut corners and churn out web applications (I'm not sure about desktop applications) with the intent of re-writing them every 2-3 years. I mean cutting corners in things like unit tests and architecture. I'd expect such applications to be hard to maintain over a long term, and that'd be ok, because we'd just rewrite from scratch and copy and paste any business logic we needed to carry forward - as long as the requirements, documentation, and the data modeling is solid. Anybody see any pitfalls to this? I guess it wouldn't be good for my career in the long term, but from the organizational perspective, I think it makes sense. The pay is kind of low because they're constrained by budget (govt. job) and I think the developer wouldn't last more than 2 years. I'd really appreciate any insights.


Why write clean, refactored code?

This is a question I've been asking myself for a long time. Thought of throwing out it to you. From my experience of working on several Java based projects, I've seen tons of codes which we call 'dirty'. The unconventional class/method/field naming, wrong way of handling of exceptions, unnecessarily heavy loops and recursion etc. But the code gives the intended results. Though I hate to see dirty code, it's time taking to clean them up and eventually comes the question of "is it worth? it's giving the desired results so what's the point of cleaning?" In team projects, should there be someone specifically to refactor and check for clean code? Or are there situations where the 'dirty' codes fail to give intended results or make the customers unhappy? Do feel free to comment and reply. And tell me if I'm missing something here. EDIT: **I like to emphasize - What I meant by WHY is not the technical reasons, I'm asking about the motive.** We all are familiar with why we should write clean code in technical point of view. But, imagine in college if I write bad code, I get bad marks (see @TofuBeer 's comment). So in your industrial environment what motivates you and your team to write clean code? And what de-motivates you and team from writing bad code. It's so easy to write a method in a class to get the information you need without looking around and checking if there's a similar method!! result-a 5000 + lines of code with few methods doing almost similar tasks. :-( Do feel free to add comments if you have seen or worked with same code.


Developer thinks they do not have to follow standard development process

How do you deal with a senior developer who does not think that the company standard way of developing software applies to them ? For instance:   1. Will ask other developers to do work by email, rather than assign bugs to them.   2. Will keep copies of documentation and code in their own local area, rather than keeping them in the common area under source control. (and overwrite others changes with theirs) NOTE: This has been flagged to QA people before.


Is cowboy programming a senior approach?

> **Possible Duplicate:**   >  Frankly, do you prefer Cowboy coding? By cowboy programming, I mean a programmer just typing the code very fast without a semi-formal process. I have a programmer that codes fast by dismissing revision control, documentation, patterns, tests, and methodologies. We talked about that and she tells me that all the approaches like agile are too academic and disregards them completely. I feel very reluctant to believe that is the consensus among senior programmers. I used to bring samples of big-name-guys like Kent Beck and Alan Kay, but she tells me that those are just authors trying to sell books or professors with no real experience. Yes, it is fast at first, but the time saved by the cowboy approach is paid in debugging. I'm not planning to change her opinion, but if those are bad practices, I don't want to adopt them. See, as a junior level, it is hard to filter good and bad practices because your knowledge is mostly based on books or on people with more experience than you and they might be wrong as well. So to senior programmers, is this a common approach at your league?


Coding style (do more, then simplify)

I'm a CS student and I have been coding for a few months shy of a year now, and I seem to have developed what I think may be a "bad" habit and I'm wondering if anyone does the same (or whether it's a bad habit at all). When I'm coding / solving a problem with code, I find that my initial implementation is lengthy and overly-complicated; in other words, there is a lot of extraneous code (variables, checks) that is simply not needed. When I finish the initial "draft," and make sure the code actually works, I simplify it and make it easier to understand/less verbose. I think the reason I do this is that I have trouble foreseeing what I will need to complete a task and end up over-compensating and creating complexities that should not or need not exist. Anyone have any tips or advice on how to improve this facet of my coding style, or any input as to whether the habit is actually a bad one?


How to deal with team members writing bad code

Our team consits of junior and senior developers. Problem I am facing is with the code written by seniors. They are not following MINIMUM coding standards. I am also still learning but I wouldn't declare the inline style or give improper names for variables and controls. I tried to mention it indirectly but they were like we can take it up later and since its agile, we should move on. But my problem is when I start working on my task, it makes me feel bad and I would focus more on refactor rather than on my task. I am not sure how to deal with this situation. PS: I am sure this question has been asked many times. But any advise is much appreciated.


Follow the deadlines vs Do it right

I have been given a huge task of migrating few functionalities from jQuery to AngularJS. I have been pretty good at Angular by now. But I want to dive deep and create futuristic, sound architecture. BAs are seating on my neck, wanting to get my tasks as quickly as possible. I prefer doing something once and right vs keeping on patching existing functionalities. And with this attitude, I always keep working more than necessary. Am I missing something? Am I having right approach or am just not convincing enough BAs my point. What's the best approach, in your opinion Thank You :)


What should be the minimal quantity of code production per week?

I'll try to further explain what I mean. Imagine you are the boss of a company. You have to deal with the tradeoff between the quality of the code and the speed of producing it. Let's assume to measure the coding speed according to Agile Methodologies in Story Points Let's consider the two extremes:   1. Our developers spend a lot of time in formation without writing any line of code. They are getting certified. They know about every technology and pattern, they spend hour in thinking how to better implement something but the productivity goes to 0.   2. Our developers go straightforward to the solution of the problems. They produce a lot of code, they respect the deadlines. But it's really poor quality. A lot of code smells and other problems which will slow down the code in a few time. It' objective that both the two extremes are not optimal. So what's your suggestion and consideration for finding the optimal tradeoff?


Prototyping vs. Clean Code at the early stages

I'm planning to work/start on a few personal projects that could end up as my daily job. It made me think, which way should I start?   * Just prototype—write just working basic code that could cost me tons of time optimizing and refactoring for easy expansion.   * Write clean, optimized and documented code from the very beginning, keeping in mind that if after some time it won't be cost-effective, it will be dropped. **Update:** Combining YAGNI with sunpech and M.Sameer answers makes perfect sense to me :) thank you everyone for help.


When to refactor

I've read through most of Fowler's Refactoring book and have refactored many applications in my past big and small. One of the harder things I find to teach is "when" to refactor. I tend to do this based on a gut feel which has served me remarkably well in the past. However, when getting into discussions with people about whether a piece of code should be left alone or refactored right now it is hard to stand by the "gut check". I feel like there should be more rigorous approaches to this, but am not sure what they are. I understand "code-smells", red-green-refactor and other thoughts, but often I feel that the best time to refactor is not the first time you write the code, but the second or third time you are using the code and realize that it is actually a problem and is in actual use.


Designing new application from scratch, TDD, MVC, OOD based

I'm about to improve my skills in all that is related to designing applications from scratch using proper OOD principles, involving MVC pattern and using TDD approach to do it. I have a project for that. I also finished reading a book by Matt Zandstra: PHP Objects, Patterns and Practice And my question is still left unanswered... How do I start designing from scratch? Should I start using TDD immediately? It doesn't feels comfortable when u have nothing implemented yet. Should I use code spaghetti just to build working prototype first, understand the scope and needs and only then rewrite all using proper OOD and TDD? I'd love to get any advice, how to work towards something considered "RIGHT TO DO", or any book that will actually lay down things of how to build the applications form scratch, or design an architecture and dependencies, rather than just throwing lifeless implementation sample codes of Design patterns like Zandstra did. Thanks! **UPD:** Basically, my question is: Is it a good idea to immediately start new project from using TDD and proper OOD, or first write something that works using the most horrible and fastest ways and then refactor everything or rewrite from scratch after you got some idea of how you want your application to look like?


Should I let my "beginnerishness" hold me back? (not rhetorical)

My situation is that I've been programming for about three years and have learned a lot but still have a long long way to go. I have an idea for an app that I believe would take off, but I'm afraid to build it because it involves architecting a back-end with databases and authenticated payment transactions and user accounts and _I've never done any of that._ I'm afraid that if I hacked it together, people would use it and things would go wrong-- security flaws, data loss, somehow I accidentally drop_table and lose everyone's payment history, etc, because I'm not sufficiently experienced with industry practices in terms of data management, versioning, hosting transitions, and plain old coding. But I really want to build this. Has anyone every been in a similar situation, and do you have any advice?


Lean Startup MVP: Quality Code or Quick and Dirty

Hello some programmers might know about the lean philosophy, building a minimal viable product Lean Startup MVP. I ask myself (when building Webapps): > "Should I put effort into writing good reusable code, testing etc." or > "Write quick and dirty code. It just works. The customer does not care what > kind of programming pattern you used etc. He/she just wants to use it." So reading the article about a MVP is a bit paradox to me. On the one hand it says: > "version of a new product which allows a team to collect the maximum amount > of validated learning about customers" on the other: > ...begin the learning process as quickly as possible So which actually has a higher priority? To me this is a trade-off between time and quality. Correct me if I did not understand it. Thanks.


How do you disarm a cowboy coder?

I found a question (code cowboy on the team), but it was more related to "Ninja Coder" then the problem that I have. I have a team member who is a pure living example of " **Cowboy Coder** ". I do understand that one can't change people, but is a way to make him stop behaving like a "Cowboy Coder"? He refuses to listen to the team, and he recently stopped code reviews, unit testing, sharing the implementation details, etc. Yes, he "codes" fast, but his code is just a bug generator. Other team members and I are in a "bug fixing phase" and 80% of bugs comes from his code. I don't want to fix his bugs. And management is blind, or doesn't want to see this, or maybe they like his "speed". Is there any way that I (as his younger colleague by age, not his boss) can do something about it? **How can I disarm this cowboy coder?** I feel like I'm the last one who really cares about the project at all.


Develop fast and buggy, then correct errors or be slow, careful for each line of code?

> **Possible Duplicates:**   >  Frankly, do you prefer Cowboy coding?   >  Prototyping vs. Clean Code at the early stages   >  Good design: How much hackyness is acceptable?   >  Does craftsmanship pay off? Which is better:   1. Coding fast, not caring about possible errors and limits, maybe forgetting to check the input, NULL returns etc, just to complete the task or to get to the milestone, and then correct all possible errors.   2. Coding slow, checking every line you write many times, writing tests, and checking every possible input to make a code as bug free as you can but taking weeks to write a working program. Actually I'm using the 2nd way but it's frustrating to work, work, work and see only small improvements every day...


Should I be commiting code quickly and testing later?

I am a web and software developer involved in the creation of mobile apps. I am currently working on a project with a looming deadline. I am wondering if I should be committing code rapidly and large and testing later, or doing tiny commits and testing each one. Thank you!


Does "write quality code" advice apply to companies of any scale?

I carefully followed the "always write quality code, unless you're writing a prototype" advice during my career as freelancer and software developer. I was convinced pretty early that avoiding to do code reviews, testing, QA or refactoring doesn't make the project faster, but only slower. Books like The Mythical Man Month by Fred Brooks or Rapid Development by Steve McConnell confirmed my thoughts. Professional experience in medium-scale companies also showed me how much money and time is wasted by not even trying to do quality work. At the same time, I often heard my colleagues complaining that constantly maintaining good code quality or simply achieving good code quality at all is too complicated for small scale companies and small teams:   * It's just too expensive to get the people able to write and maintain quality code. If the company can hire either two persons for $3 000 per month or one person for $6 000 per month, most managers would consider that two persons will be more productive than one: maybe not by a factor of two, but still. Or the small company can hire one person for $3 000 per month and spend the remaining 3 000 for something else.   * There are too many aspects to take in account in order to be able to do it within a small team. A single person can hardly take care of the style of code, readability, architecture, design, ease of testing, testing itself, reliability, security, ease of use, performance, etc.   * And it doesn't worth it. It's not like a piece of code will remain in the code base for the next fifteen years and will be read thousands of times by hundreds of developers. Chances are, the same person will maintain this piece of software for the next five years, then just throw it away and write a better one from scratch. I usually reply that one should remember the productivity factor of 1:10 among developers and that most of the time is spent not writing code, but maintaining it. This means that low quality code is still ways more expensive. But is it so? Should every company, no matter its scale, try to hire the best possible developers they can afford, and encourage them to write quality code, or there is scale above which code quality becomes just a burden, a waste of time and money?


How far to go when standardizing code

My small team and I have created a decent sized web application (~50k lines), with a fully featured API, all in Perl. As us perl hackers know.. it is easy to get sloppy. We had to port over a lot of legacy code.. thus perl whale guts code ensued. Long story short, we were under a fairly tight time constraint which now has been pushed back, so we have some time to go back in and standardize code. We quickly found out how nonstandard our code was as our contractor was developing an iOS app where we have account numbers of length 10 some places, 12 in others with prepended data, etc. As I'm going through fixing date formats and data formatting, I'm noticing a ton of really non descriptive variable and hash key naming which came from legacy code - not nice down the road maintaining it. Basically, my question is - given the scenario above or your own experience, how far do you go when cleaning up and standardizing? Is it worth going in and replacing hash key names with longer camel cased ones, and variable names, the way data is handled in results - etc. I know lot more pain can come from breaking working code, and it may not be worth it.. but how do you know how far to go? Get it over with now and then it pays off later, or just live with a bit of "code debt"?


Frankly, do you prefer Cowboy coding?

Most programmers defending methodologies politically correct like Agile, Waterfall, RUP, etc. Some of them follow the methodology but not all of them. Frankly, if you can choose the methodology, you certainly would go to mainstream "correct" methodologies or you would prefer the "easier" methodology like cowboy programming? Why? I know it depends. Please, explain when you would use one or another. Please, say what advantages do you see on Cowboy coding. See about Cowboy coding on Wikipedia


Is method overriding always a violation of Liskov Substitution Principle?

Overriding a method originally defined in the super class, by definition means this method will do different things when invoked on an object of the base class or an object of the subclass. So does this mean that overriding methods _always_ means violating LSP? Or are there cases when it doesn't?


Why use Android Fragments?

I have read the documentation and some other questions' threads about this topic and I don't really feel convinced; I don't see clearly the limits of use of this technique. Fragments are now seen as a _Best Practice_ ; **every Activity should be basically a support for one or more Fragments** and not call a layout directly. Fragments are created in order to:   1. allow the `Activity` to use many fragments, to change between them, to reuse these units... ==> the `Fragment` is totally dependent to the `Context` of an activity , so if I need something generic that I can reuse and handle in many Activities, I can create my own custom layouts or Views ... I will not care about this additional Complexity Developing Layer that fragments would add.    2. a better handling to different resolution ==> OK for tablets/phones in case of long process that we can show two (or more) fragments in the same Activity in Tablets, and one by one in phones. But why would I use fragments **always** ?   3. handling callbacks to navigate between Fragments (i.e: if the user is Logged-in I show a fragment else I show another fragment). ===> Just try to see how many bugs facebook SDK Log-in have because of this, to understand that it is really (?) ...   4. considering that an Android Application is based on Activities... Adding another life cycles in the Activity would be better to design an Application... I mean the modules, the scenarios, the data management and the connectivity would be better designed, in that way. ===> This is an answer of someone who's used to see the Android SDK and Android Framework with a Fragments vision. I don't think it's wrong, but I am not sure it will give good results... And it is really abstract... **====> Why would I complicate my life, coding more, in using them always? else, why is it a best practice if it's just a tool for some cases? what are these cases?**


NHibernate and complex domain model against a legacy database

I'm trying to refactor (actually, rewrite) an application which currently uses only stored procedures to access the database (hundreds of SPs). My goal is to use Nhibernate and follow a good design as much as possible. But since the database (and the SPs) are used by dozens of other apps, I can't really change the db design. And off course, it's awful. I'm facing a design problem and I can't really find a good solution. I have a table called movies which contains movies, but these movies can be different "things". For example, this table contains movies as well as episodes of tv shows and the only way to know the difference is a field named "episode" which is set to 0 for movies and 1 for episodes. My objective is to expose the following class hierarchy :               public abstract class Program {}     public class Episode : Program {}     public class Movie : Program {}      Currently, I have mapped the whole movies table to a model class MoviesModel and then I build my Episode/Movie class through AutoMapper and a factory method in the Program class :               public static Program Load(MoviesModel movieModel)         {             if (movieModel.Episode > 0)                 return Mapper.Map<Episode>(movieModel);             return Mapper.Map<Movie>(movieModel);         }      This seems really wrong on many levels : I have an anemic data model since my MoviesModel is totally empty of any business logic, the automapper stuff becomes really hard to maintain when I add many other entities with relations to Movies, and I break the lazy loading with AutoMapper. I heard about the any mapping of nhibernate but it doesn't really solve my issue, it just creates sub components of a class. So my questions are :   * Ideally, where should be my business logic ? I guess in the MoviesModel class but I don't really like the idea to expose my database fields.   * Is there a way with nhibernate to map the same table in different classes based on a field value ?   * Is there a point to wrap the nhibernate objects if I want to provide a "clean" public API ? My goal is to build a base library which will be used (hopefully) on other legacy apps so I want to provide a clean API with logical methods and without exposing the database mess even if I still have to deal with it. Thanks for any help to put me in the right direction.


What is meant by change the main routine? The C Programming Language

In exercise 1-16 in The C Programming Language (K & R) it asks for us to: revise the _main routine_ of the longest-line program so it will correctly print the length of arbitrary long input lines, and as much as possible of the text. From what I read here, I get the notion that the main routine is everything inside of `main`, is this correct? I posted the code for the longest-line program below for more context, but I am confused my what I am being asked to do not the code. Thanks!               #include <stdio.h>          #define MAXLINE 1000                /* maximum input line length */          int getline( char line[], int maxline );     void copy( char to[], char from[] );          /* print the longest input line */          main()     {          int len;                /* current line length */     int max;                /* maximum length seen so far */     char line[MAXLINE];     /* current input line */     char longest[MAXLINE];  /* longest line saved here */          max = 0;     while (( len = getline( line, MAXLINE )) > 0)         if ( len > max ) {             max = len;             copy( longest, line );         }            if ( max > 0 )         printf( "%s", longest );             return 0;     }          /* getline: read a line into s, return length */      int getline( char s[], int lim )           {         int c, i;              for ( i = 0; i <  lim - 1 && ( c = getchar() ) != EOF && c != '\n'; ++i )             s[i] = c;                if ( c == '\n' ){             s[i] = c;             ++ i;         }            s[i] = '\0';             return i;         }          /* copy: copy 'from' into 'to'; assume to is big enough */     void copy( char to[], char from[] )      {         int i;              i = 0;         while ( (to[i] = from[i] ) != '\0' )             ++i;     }


How deeply the interviewer goes in these skillls asked in job posting

I have seen many job posting with normal technical skills required but there are few thing mentioned in them , which i have no idea actually how can i go about improving them or how should i prove them that i know this   1. Software development lifecycle quality control   2. Setting up version control in a traditional dev/test/stage/production environment with firewalls between stage and production.Note: setting up not just using version control.   3. Automating and optimising software release processes   4. Simultaneous database updates and code revisions   5. Releases to distributed server farms in multiple locations   6. Setting up error checking, error reporting processes and alert systems   7. Knowledge of search technologies is highly desirable.   8. Agile Programming Methodology and Unit testing Experience Now i want to know from experienced programmers or job interviewers how much deeply they ask for these things. The reason i am asking this is that if someone can guide how can i learn those so that at least i can have those thing in resume so that i can get an edge over those who have not written anything about it. I don't want to tell lie but what i want to do is apply those small to some websites so that at least i can tell them i covered this here. I have 6 months free time before i go to my country to start applying for jobs, so i am just searching for jobs requirements so that i am capable of write them in my resume.


What kind of design pattern for an "investment" system?

I'm developing a browser game with nodejs. I'm trying to make a "invest" function with letting users invest according to their balance. The problem is, lets say:               A user came and invested 20 dollar    %40 of bankroll         B user came and invested 30 dollar    %60 of bankroll      Then:               C user played and lose 10 dollar      Worked good so far, now :               A user has 24 dollar    %40 of bankroll   (+4 dollar)     B user has 36 dollar    %60 of bankroll   (+6 dollar)      But, then if a **D** user come and invest some dollars, site profit is dividing to 3 according to my function. **D** user is came last and he **mustn't** get any profit. How can I set up a working and flawless investment system?


Is binary recursion a type of exponential recursion?

People in this thread state that fibonacci runs in exponential time. This professor on the other hand states that fibonacci sequence is binary recursion. I don't think either of them are wrong, which leads me to conclude that binary recursion is a form of exponential recursion.


SPA Applications: AJAX to fetch templates or build from strings

I'm working on a large angular application and I'm currently using a factory class that builds HTML templates from strings. We don't have to worry about mobile support for the application and I'm wondering from an architectural standpoint, which method would you rather implement and why: static HTML files that are fetched on request, or a class that builds the templates as strings?


How does Facebook manage to allow a user unlimited sessions?

I could login through the website, android app, iOS app, the browsers on mobile, and when I log out from one, it doesn't log me out of all of them. Traditionally, you would log out of all the services at once because your auth_token would be set to null in the DB. That being said, I don't see a way to do this through Rails and Devise. I only have two solutions so far. The first one is to have separate session tokens, and figure out which to use based on a header. However, if you want unlimited number of sessions, you need some unique ID to follow through on. I'm not sure how you'd achieve this. The second solution is to have a counter in the DB named sessions. It keeps track of how many sessions you currently have logged in. If I'm logged in through the website, Android app and iOS app, it would be 3. Whenever you have more than 1 session open and log-out, the number of sessions would be decremented. If the number of sessions becomes 0, we set the auth_token to null in the DB (nil in Ruby). The only loop-hole I could see in this is that if someone logs out, is still logged in on some other platform, and is code savvy, they could find the auth_token via previous requests on their browser. Then, they could send it in and continue to use it even though they have technically logged out. I don't necessarily see a problem with this, but I don't know if this is a good way to do it. Does anyone else have a good suggestion? Is there a better place to post this?


Converting mysql and SQLServer tables quickly in an update utility

The requirements are to take an existing list of identical tables (AAA0001 - AAA9999) which generally don't meed our current requirements and need to be swapped out with three tables (XXX0001-XXX999, YYY0001-YYY999 and ZZZ0001-ZZZ999). Currently, the guy who is programming this update which is supposed to take place on our clients machines who run both mysql and microsoft SQL Server is running select and insert queries which is bound to make the next update the slowest and most painful in the history of our product. I'd think we could so something faster by dumping the tables to a database, doing some string manipulation and undumping the database. However, we've never used any database connectors besides ODBC for our program and don't necessarily have the faculties to do both a mysql and a SQLServer dump (unless it's easy). So, what's the speediest way to dump and undump rows over ODBC? If there is no speedy way what's the safest and easiest to implement alternative? * * * We use Delphi XE2 Enterprise, if anyone has any 3rd party DB tools or knows any shortcuts. We've never used datasnap, as we didn't have the "good version" of Delphi until we updated to XE2, so I'm clueless as to whether it's got this functionality.


Which are the significant algorithms for humankind in past decades?

Which world most important algorithms have contributed most to humankind in past decades? I thought this is a good general knowledge for a developer to know about. **Update:**   If possible, please keep the answer to a **specific programming algorithm**.   I would like to get a list of the most important ones, only one algorithm per answer.   Please consider to state why the algorithm is significant and important...


BackgroundWorker vs. Async/Await

I am new to C# development and wish to create a more responsive UI. In my preliminary research, I have seen two methods for achieving this:   1. Multi-threading in conjunction with the BackgroundWorker class.   2. The newer Async/Await modifiers.  Does newer mean better? What's the difference between the two methods? If I wish to create a new project, how do I choose which method to go with? EDIT: Maybe I should specify. I am creating a Windows Forms application, where all necessary data will be saved/loaded on the local disk. I will also be communicating with several USB devices.


Fast set indexing data structure for superset retrieval

I am given a set of sets:               {{a,b}, {a,b,c}, {a,c}, {a,c,f}}      I would like to have a data structure to index those sets such that the following "lookup" is executed fast: find all supersets of a given set. For example, given the set {a,c} the structure would return               {{a,b,c}, {a,c,f}, {a,c}}      but not {a,b}. Any suggestions? Could this be done with a smart trie-like data structure storing sets after a proper sorting? This data structures is going to be queried a lot. Thus, I'm searching for a structure that might be expensive in build but rather fast to query. UPDATE: I have finally used a prefix Trie as described in the paper "A New Method to Index and Query Sets", by Jorg Hoffmann and Jana Koehler.


What should I do when I can't reach my deadline?

I've founded a startup with my friends a few months ago, and—due to some personal issues like starting college and moving to a new town—I've found that I'm likely going to miss an important deadline for the project we're working on. I'm stressing out about this, and I'm not sure what I should do. How can I handle this stress and communicate the delay to my team?


How to say effectively to a manager that you missed the 'deadline'

> **Possible Duplicate:**   >  I cannot reach my deadline. What to do? My manager is a very deadline specific person. Even though I am a trainee, he insists on a deadline for every small assignment that he gives. Now it so happens that I miss the deadline. And boy, he doesn’t like that at all! So how do I say that i missed the deadline without inviting his wrath? How to stop getting into his bad books? P.S. I am not being lazy. Just that the assignments that he gives are not easy stuff, plus I am doing it in Delphi, which is new to me.


Is it better to build HTML Code string on the server or on the client side?

The result of the following process should be a html form. This form's structure varies from one to user. For example there might be a different number of rows or there may be the need for `rowspan` and `colspan`. When the user chooses to see this table an ajax call is made to the server where the structure of the table is decided from the database. Then I have to create the html code for the table structure which will be inserted in the DOM via JavaScript. The following problem comes to my mind: Where should I build the HTML code which will be inserted in the DOM? On the server side or should I send some parameters in the ajax call method and process the structure there? Therefore the main question involves good practice when it comes to decide between Server side processing or client side processing. Thank you!


How can I test PHP skills in a interview?

My company needs to hire a PHP developer, but nobody has PHP knowledge in my company and we find difficult to test for PHP skills. If it were a C/Java developer I would ask him to write a quick implementation of the Game of Life, but PHP is a completely different language. I saw this test with interest: http://vladalexa.com/scripts/php/test/test_php_skill.html Anyone else has more suggestions?


How do you limit whitespace differences for developers using different IDEs/environments?

I've used UltraEdit for years and never had a problem with sharing code with fellow developers whether they worked on Windows, Mac, Linux, Eclipse, Visual Studio -- what have you... But now I am in an office where some developers are using emacs and they complain profusely about the white space differences my code "introduces". I have UltraEdit set to write to files as UNIX-style (no Windows returns), but it seems the whitespace renders differently for the emacs developers. Since I don't use emacs (or vi), its a pain for me to try to figure out why this is impacting them, but I more so just want them to shuttup! lol This is even causing problems in SVN/Diff! Any thoughts on how to fix this? Forget about everyone using Emacs because thats not gonna happen lol.


while(true) and loop-breaking - anti-pattern?

Consider the following code:               public void doSomething(int input)     {        while(true)        {           TransformInSomeWay(input);                if(ProcessingComplete(input))              break;                DoSomethingElseTo(input);        }     }      Assume that this process involves a finite but input-dependent number of steps; the loop is designed to terminate on its own as a result of the algorithm, and is not designed to run indefinitely (until cancelled by an outside event). Because the test to see if the loop should end is in the middle of a logical set of steps, the while loop itself currently doesn't check anything meaningful; the check is instead performed at the "proper" place within the conceptual algorithm. I was told that this is bad code, because it is more bug-prone due to the ending condition not being checked by the loop structure. It's more difficult to figure out how you'd exit the loop, and could invite bugs as the breaking condition might be bypassed or omitted accidentally given future changes. Now, the code could be structured as follows:               public void doSomething(int input)     {        TransformInSomeWay(input);             while(!ProcessingComplete(input))        {           DoSomethingElseTo(input);           TransformInSomeWay(input);        }     }      However, this duplicates a call to a method in code, violating DRY; if `TransformInSomeWay` were later replaced with some other method, both calls would have to be found and changed (and the fact that there are two may be less obvious in a more complex piece of code). You could also write it like:               public void doSomething(int input)     {        var complete = false;        while(!complete)        {           TransformInSomeWay(input);                complete = ProcessingComplete(input);                if(!complete)            {              DoSomethingElseTo(input);                     }        }     }      ... but you now have a variable whose only purpose is to shift the condition- checking to the loop structure, and also has to be checked multiple times to provide the same behavior as the original logic. For my part, I say that given the algorithm this code implements in the real world, the original code is the most readable. If you were going through it yourself, this is the way you'd think about it, and so it would be intuitive to people familiar with the algorithm. So, which is "better"? is it better to give the responsibility of condition checking to the while loop by structuring the logic around the loop? Or is it better to structure the logic in a "natural" way as indicated by requirements or a conceptual description of the algorithm, even though that may mean bypassing the loop's built-in capabilities?


Separating validation from persistence in models?

Models in an MVC application gets kind of hard to test when validation of data and persistence of data is baked together in the model. I would like to test those separately to prevent doing integration testing instead of actual unit testing. What patterns are available to keep validation and persistence separated?


Organizing single page code well with Notepad++

I've a c# file that will contain, most likely 10,000+ lines of code. I'd like to break this file into tabbed segments, so I can organize each method into a certain tab and label the tab something like : initial setup, helper functions,execution logic,list structures,global variables, etc. If I were using PHP I would have separate files and use include(); to include the separate files. What can be done, following the same style, with c#?


What's the best way to modularize a User schema so it's generic

I have a database design question. Basically I want to be able to create a schema for a User model, then use this User model in other models that extend User but I want to design it in such a way that it's generic enough to be used in every application. For example a Profile or Account model might extend User, and in both cases they will be different based on the web application you are designing but the core credentials of User should never be different across any web application. What fields do you think should be in the User model? I think the bare minimum to successfully handle authentication would be:   * email (the login unique identifier)   * salt (obviously!)   * password (duh)   * lostToken (a hash to verify lost password functionality)   * role (member, admin, editor, etc.. IMO this list of roles would differ between sites however it's too important to the User model not to have here?) Now we get into other interesting fields that are still very very useful:   * createdAt (when the account was created)   * ipAddress (track the ip when the account was created)   * refererUrl (which site it came from)   * lastLoggedIn (the last time the user logged in)   * isOnline (is the user currently online) And even more fields that are still pretty useful:   * username (might not be used on every site)   * number of consecutive logins (similar to the stack network) I think anything else like social data (likes, votes, profile views), badges/achievements, the last time they updated their profile/account/whatever, and other info like their name belong in the per- site Profile model. What do you think? Edit: I fully understand that this question is partly subjective but I do think there's definitely room for discussion.


Is it OK to use sample code from blogs, GitHub, etc... in commercial applications?

When searching the web for a solution to a particular problem, I often find a perfect solution posted on someone's blog, or in a public repository (GitHub, Google Code). Most of the time, the code has no copyright information, nor does the author mention any sort of attribution rules. I'm pretty sure short snippets are fine, but what if I copy a handful of classes verbatim (again, no copyright notices, TOS, attribution requests, etc...)? Am I under any legal obligation to the original author?


Is there a performance benefit to using immutable objects in a scripting language?

As I understand it, writing your objects in an immutable style can help the performance of your program for compiled languages, as the compiler tends to rewrite your code in single static assignment form under the hood anyway. Is there a performance benefit to using immutable objects in an interpreted language like Python or PHP? I understand there may be readability or code quality benefits from immutability, but I am asking specifically about performance.


Is it OK to mix C and C++ in an interview?

If I am asked in an interview to write down some code, should I completely stick with C++ or is it acceptable to "mix" the two to write easy code as it comes to my mind? I'll explain it: if I'm asked to create a "stack" data type, a C++ class is perfectly suited, while if I need to parse some strings a strtok/sscanf is far easier than STL. On the other hand, if I need a generic container STL and templates are the way to go. Everything can be done in C or in C++, but in an interview I can't code everything or remember every standard/STL function. What is an acceptable tradeoff?


Using "Google Guava" in coding interviews

I attended a in-person interview recently and performed well. But surprisingly I got rejected. When I asked the HR for reason, he contacted the technical interviewer and told me that I was syntactically wrong while coding. I used Google Guava for coding. So my code looked like this: `List<String> items = Lists.newArrayList()` instead of `List<String> items =new ArrayList<String>();` I know that the code will compile and work as expected.Is it ok to use third party libraries like Google Guava in interviews?


Architecture for Social Graph data that has a Time Frame Associated?

I am adding some "social" type features to an existing application. There are a limited # of node & edge types. Overall the data itself is relatively small (50,000 - 70,000 for each type of node) there will be a number of edges (relationships) between them (almost all directional). This, I know, is relatively easy to represent with an SDF store (such as BrightstarDB) or something like Microsoft's Trinity (or really many of the noSQL options). The thing that, I think, makes this a unique use case is that each relationship will have a timeframe associated with it (start and end dates). Right now, I'm thinking of just storing this in a relational structure and dealing with the headaches of "traversing the graph", but I'm looking for suggestions on a better approach (both in terms of data structure and server):               Column     ================     From_Node_ID       Relationship     To_Node_ID     StartDate     EndDate      Any suggestions or thoughts are welcomed.


How can I teach Java theoretically from distance?

I will be in the position of teaching Java theoretically, (it will not contain a screen and typing, all things that I will have is a paper and a camera so they can watch my hands while I am writing). Any ideas of what topics I should cover if I'm teaching this way?


Best way for an external (remote) graphics designer to style ASP.NET MVC 4 app?

My customer has his own graphics designer he wants to use to style his web application we're building in ASP.NET MVC 4. Our solution is in Bitbucket, but if he can't run it what choices do we have? I doubt he uses Visual Studio 2012. One idea is for us to publish to our solution to a file system, send it to him, have him create a local IIS website on his machine (assuming he isn't using a Mac). Mocking data or pointing to a test SQL in Azure isn't a problem. Then he can make changes to .css and .cshtml files. Will this even work? The point is that he needs to be able to test his changes. I know he can modify the views and just check-in. But he needs to deliver a working design. So it seems inefficient. The graphics designer will have access to our test site so he can see how it works, what data we have and fields. Another idea is for him to build a static mock site using just HTML/CSS. Later I'd integrate his styles into customer's solution, split his html into partial views which we use and add Razor syntax. Again, we'd like to leverage graphics designer for all of this. Is there a best practice documented around this subject? How do other teams deal with this situation?


Desktop application, dependency injection

I am thinking of applying a real dependency injection library to my toy C#/GTK# desktop application. I chose NInject, but I think this is irrelevant to my question. There is a database object, a main window and several utility window classes. It's clear that I can inject the database into every window object, so here DI is useful. But does it make sense to inject utility window classes into other window classes? Example: I have classes such as:               class MainWindow {…}     class AddItemWindow {…}     class AddAttachmentWindow {…}     class BrowseItemsWindow {…}     class QueryBuilderWindow {…}     class QueryBrowserWindow {…}     class PreferencesWindow {…}     …      Each of the utility classes can be opened from MainWindow. Some utility windows can also be opened from other utility windows. Generally, there might be a really complex graph of who can open whom. So each of those classes might need quite a lot of other window classes injected. I'm worried that such usage will go against the suggestion not to inject too many classes at once and become a code smell. Should I use some kind of a service locator object here?


How does std::string in c++ allocate memory?

I've noticed that the string library doesn't require one to allocate space before writing the input/output. How does the string library allocate that memory dynamically, i know of the 'new' keyword in c++ and 'malloc' in c but when i try something like this, my program stops working.               char* str = new char[strlen(str) + 1];     cin>>str;      i can't get it to work that way, how does the string library work? I also know of vectors in C++ but not a big fan of using them, i would like to know if there's a way to dynamically allocate memory without having to allocate a size before, something close but not as sophisticated as the string.h library. How does the string library get unlimited input from user without the programmer specifying buffer size?


Change management's mind?

As a programmer working in an insurance office, I have a nasty little management hierarchy which is making programming much harder. At current, our IT department rates a three on The Joel Test, which worries me. I'd like to fix this, but management enforces an insanely aggressive release schedule. Basically every project is due "yesterday". As a result basic planning is nearly impossible. Best practices like planning, documentation, and testing are all overlooked on every project we attempt. So far, I've tried a myriad of methods. Everything from trying to frighten them with worst case scenarios, to referring to industry standards for advice on how to proceed on a subject. I'm at the end of my rope. So the question is, what methods have worked for other programmers to change how management views programming. My biggest fear is that it is simply impossible to make them see the light, and the solution is "work somewhere else".


Learning to program by immersion?

I've long realized that the best way to go about learning another (natural) language is by immersion - you can learn Spanish in a classroom, but you'll never be as fluent as someone living in Spain (over an extended period of time who is interested in actually learning Spanish). I was curious if the same was true for people who are new to programming. Now, I know that not all of these are specific to programming, but the general public at least generally associates these things with "computer geeky". Would switching to Linux be a good choice? Would using Git (or some other type of VCS) be a good choice? What about joining online forums and IRC? What about writing unit tests or working on larger projects? I know that in the past programming and computer science was introduced in a very sterile environment. You started in a university classroom with a well known curriculum and book (say, _Structure and Interpretation of Computer Programs_ ), say for a few "hackers" who started young (and often with BASIC or the like). I've noticed that the actual experience of a software developer is more complicated than just knowing a language (and how to use it), there's a whole lot in between, and a whole lot to learn. Do you think it's better to start programming by immersion? Not necessarily all at once, but rapidly introducing new "concepts" that professionals make use of? Or is it better to start slowly and academically?


Can I advance my career in the USA if I lack local networking?

I'm a web developer with 10 years of experience in the Microsoft stack. I was brought to the US by my company, but my contract has ended. I want to continue pursuing a career in the US, but it seems there's a focus on networking while still in college. Due to my foreign education, my networking occurred elsewhere. However, because of this network effect, it seems most developers in the US only have to apply to one or two jobs throughout their career. Am I handicapped by not having a professional network in the US?


Reading and conditionally updating N rows, where N > 100,000 for DNA Sequence processing

I have a proof of concept application that uses Azure tables to associate DNA sequences to "something". Table 1 is the master table. It uniquely lists every DNA sequence. The PK is a load balanced hash of the RK. The RK is the unique encoded value of the DNA sequence. Additional tables are created per subject. The PK is a load balanced hash, and the RK is the unique value of the DNA sequence. Assume that the quantity of RKs here is many order of magnitudes smaller than the Master table. Each subject has a list of N DNA sequences that have one reference in the Master table, where N is > 100,000. It is possible for many tables to reference the same DNA sequence, but in this case only one entry will be present in the Master table. **My Azure dilemma:** I need to lock the reference in the Master table as I work with the data. I need to handle timeouts, and prevent other threads from overwriting my data as one C# thread is working with the information. Other threads need to realise that this is locked, and move onto other unlocked records and do the work. Ideally I'd like to get some progress report of how my computation is going, and have the option to cancel the process (and unwind the locks). **Question** What is the best approach for this? I'm looking at these code snippets for inspiration: http://blogs.msdn.com/b/jimoneil/archive/2010/10/05/azure-home- part-7-asynchronous-table-storage-pagination.aspx http://stackoverflow.com/q/4535740/328397


Critique of the IO monad being viewed as a state monad operating on the world

The `IO` monad in Haskell is often explained as a state monad where the state is the world. So a value of type `IO a` monad is viewed as something like `worldState -> (a, worldState)`. Some time ago I read an article (or a blog/mailing list post) that criticized this view and gave several reasons why it's not correct. But I cannot remember neither the article nor the reasons. Anybody knows? **_Edit:_ The article seems lost, so let's start gathering various arguments here.** I'm starting a bounty to make things more interesting. _Edit:_ The article I was looking for is Tackling the awkward squad: monadic input/output, concurrency, exceptions, and foreign-language calls in Haskell by Simon Peyton Jones. (Thanks to TacTics's answer.)


Hard declarations in Haskell (á la C)

http://susam.in/blog/clumsy-pointers/ How can be solved different declarations puzzles with Haskell? `void x1(int *)` A function which has int * argument and return type void. `void (*x2)(int *)` Pointer to a function which has int * argument and return type void. `void (*x3())(int *)` A function that returns a pointer to a function which has int * argument and return type void. `void (*x4(void (*)(int *)))(int *)` A function which has a pointer to a function that has int * argument and return type void as argument, and returns a pointer to a function which has int * argument and return type void. `void (*x5(void (*[10])(int *)))(int *)` A function which has an array of 10 pointers to functions that has int * argument and return type void as argument, and returns a pointer to a function which has int * argument and return type void. `void (*(*x6)(void (*[10])(int *)))(int *)` A pointer to a function which has an array of 10 pointers to functions that has int * argument and return type void as argument, and returns a pointer to a function which has int * argument and return type void. `char (*(*x7())[])()` Function returning pointer to array[] of pointer to function returning char. `char (*(*x8[3])())[5]` Array[3] of pointer to function returning pointer to array[5] of char.


iOS - Unit tests for KVO/delegate codes

I am going to design a MVC pattern. It could be either designed as a delegate pattern, or a Key-Value-Observing(KVO), to notify the controller about changing models. The project requires certain quality control procedures to conform to those verification documents. My questions:   1. Does delegate pattern fit better for unit testing than KVO?   2. If KVO fits better, would you please suggest some sample codes?


How to you "sell" support as an career option

We find it relatively easy to hire developers to work on various projects. The problem arises when the project is finished but still needs to be supported. We really battle to get people to join the support team. It's seen as dead- end, career-limiting, boring, second-class etc. Currently, we get round this by getting the project team to assign some of their team to the support team for a while. Part of the assignment is to do a "brain dump" of the project so that the support team understands it. This works as long as the assignment is only for a fixed period. Trying to hire people to work in support full-time is a problem. There are few applications and the calibre is not particularly high. (The financial reality though is that support can be very lucrative for a company and once you get a reputation, you get approached by other companies to do their support even though you weren't involved in the original development.)


C++ job interview questions?

I am expecting a job interview for a C++, what kind of questions should I expect? I have been programming with C for 5 years. I know what OOP is and I have been reading about it for some time. But it is most likely I can miss important details because I do not do anything real on C++. Best Regards,


Is Java much harder to "tweak" for performance compared with C/C++?

Does the "magic" of the JVM hinder the influence a programmer has over micro- optimisations in Java? I recently read in C++ sometimes the ordering of the data members can provide optimizations (granted, in the microsecond environment) and I presumed a programmer's hands are tied when it comes to squeezing performance from Java? I appreciate a decent algorithm provides greater speed-gains, but once you have the correct algorithm is Java harder to tweak due to the JVM control? If not, could people give examples of what tricks you can use in Java (besides simple compiler flags).


When does "proper" programming no longer matter?

I've been building an android game in my spare time. It's using the libgdx library so quite a bit of the heavy lifting is done for me. While developing, I carelessly selected datatypes for some procedures. I used a hashtable because I wanted something close to an associative array. Human readable key values. In other places to achieve similar things, I use a vector. I know libgdx has vector2 and vector3 classes, but I've never used them. When I come across weird problems and search Stack Overflow for help, I see a lot of people just reaming the questions that use a certain datatype when another one is technically "proper." Like using an ArrayList because it does not require defined bounds versus re-defining an int[] with new known boundaries. Or even something trivial like this:               for(int i = 0; i < items.length; i ++)     {         // do something     }      I know it evaluates item.length on every iteration. However, I also know items will never be more than 15 to 20 items. So should I care if I evaluate items.length on every iteration? I ran some tests to see how the app performs using the method I just described versus the proper, follow the tutorial and use the exact data types suggested by the community. The results: Same thing. Average 45 fps. I opened every app on the phone and galaxy tab. No difference. So I guess my question to you is this: Is there a threshold when it no longer matters to be proper? Is it ok to say - "so long as it gets the job done, I don't care?"