How would you feel if your code editor formatted your code for you as you typed, without tabs/spaces?

As with most things, I'm sure this concept has been tried before - I just haven't come across editors that use what I've termed 'Virtual Formatting'. The principle is that there's a floating left-margin that simulates the effect of the padding space/tab characters that are conventionally inserted by the developer or the editor itself to format the code. The editor continously parses code (even when commented-out) as you type and calculates the required indent based on the context where each line-feed is found I'm developing this idea working specifically with an XML editor as XML has some peculiar problems with formatting characters and it tends to be heavily nested, however I believe many of the principles still hold for conventional code. Have you experience coding with such a tool or do you have a view on whether it would help or hinder? Would it cause problems with version-control systems? (it detects and strips out all existing padding characters) Unless you've tried it, the behavior of such a tool is hard to describe, it looks conventional until you actually start editing. I've put up a screencast video showing a prototype in action which demonstrates editing XML, changing it's hierarchy and doing drag/drop and copy and paste operations, and then how formatting is broken/fixed when invalid characters are typed. **Edit** All answers/comments have so far been negative - so to attempt to redress balance, some benefits of virtual-formatting to think about:   * No more debates on formatting standards, just place line-feeds where that conforms to your chosen/mandated convention   * Where space is at a premium (in a book/blog/documentation) you can word-wrap but still getting perfect indentation   * Each code-block can have a 'mouse-handle' immediately adjacent to where it starts, not squeezed into the screen edge - click this to select the whole block or inner-block   * Drag, drop and forget - becomes viable for the first time   * No time spent reformatting other peoples code   * No incorrectly formatted code (in the sense that there is none - just the rendering)   * Using Backspace instead of Ctrl+Backspace keeps your fingers on the keyboard guide-keys   * Flexible rendering - adapt rendered formatting to your environment, anyone tried reading code on a mobile phone/small-screen tablet?   * Consider that there are roughly 25% fewer editable characters (in a sample XSLT), doesn't that have efficiency benefits? **Edit - Conclusions so far**   1. Developers have established tools and working methods that efficiently overcome most of the disadvantages inherent in the use of padding characters used for indentation.   2. There is concern that removal of formatting characters will detrimentally affect some differencing tools.   3. Developers want the flexibility to 'fine-tune' formatting in such a way that automated rendering could not handle.   4. The removal of leading spaces/tabs means that a 'code-aware' tool capable of code-formatting is needed to review such code efficiently - a plain-text editor would show no formatting.   5. Those that feel there may be some hypothetical benefits (to virtual-indentation), have a view that the disadvantages outweigh those potential benefits - _conclusively_. **Edit - Verdict** The perception of the obstacles and few (if any) benefits is such that it would be unwise for me, as a sole-developer, to pursue this space-free editing concept for general languages. For XML/XSLT, however (because of its special treatment of whitespace), there seems to be some agreement of potential at least. **Edit - Product Shipped** In spite of the generally negative sentiment found here, I went ahead and shipped the editor. I made a free version in the hope it would bring criticism in the form of more concrete issues, based on real experience. Somewhat frustratingly, there have been no complaints so far (in fact barely any feedback considering download volume). I'd like to think this was because users adjusted to the idea so well that they see this as a 'so what?' kind of feature - but there's no way of telling...


What's the rationale of not simply disclosing the license fees for a commercial libary or tool?

Some companies selling software or libraries simply put their licensing model on their web page and be done with it. (Many also contain a disclaimer that there are volume discounts and special arrangements possible.) Other companies (most notably those placing themselves in the "enterprise" market) don't disclose their fees, some don't even disclose their licensing model! When you are interested in their product and contact sales, you then discover that their price calculation is simply a per site / per developer / per core / per whatever thing and they could just as well have put that info on their webpage. Can fellow programmers give me an insight as to why I have to exchange 3 emails and 2 phone calls with a sales representative to find out if a product even remotely fits into our development price tag? I have found that me (and some of my co-workers) are extremely reluctant to even evaluate a product that doesn't disclose it's costs up front, so I cannot understand why anyone would do that for "simple" products - that is for libraries and software that really doesn't have negotiated license fees. Note again: I'm talking about single-installation software or libraries that are licensed per-site or per-developer and not about stuff that requires complicated licensing agreements.


How to move to Java enterprise development after Python and Ruby?

I used to develop in Django/Python and Rails/Ruby (and before that C/C++ and C#), and I'm now at a job where we do enterprise Java development (Spring, Hibernate, RESTEasy, Maven, etc.) for web applications and web services. Coming from the Convention over Configuration world, what's the best way to get up to speed doing enterprise Java web services development? I know Java (the language) well, and I've written GUIs in Swing and basic JSP before, but nothing of the kind I'm doing now. Are there any recommended tutorials to get up to speed on popular Java enterprise development tutorials?


Should I achieve validation by handling errors in classic ASP?

I came across this while modifying an old ASP application:               ON ERROR RESUME NEXT          ivalue = CDATE(ivalue)          IF err.number > 0 THEN       ivalue = CDATE(date)     END IF     err.clear      This doesn't look like good practice. What is the purpose of doing it this way, and is there a better way to go about it? For example, I would've just used `ISDATE()`: is there something I'm missing?


Best books on Managing a Software Development Team?

The canonical books on software development is fairly well established. However, after reading through a dreadful book full of bad advice on managing programming teams this weekend I am looking for recommendations for really good books that focus on the management side of programming (recruiting, performance measurement/management, motivation, best practices, organizational structure, etc.) and not as much on the construction of software itself. Any suggestions?


Implement Generic DataSet Builder with C#

I want to create a data access library that can build a DataSets with relations which can easily be written to XML with `dataset.WriteXML()`. This is a get to know C# endeavor that will hopefully gain me some productivity as well (lots of converting relational tables to XML from different data sources for document generation) So far the only difference I see between the Data Access technologies (SQL, OLEDB, ODBC) with regards to how I will use them for this is that they require a type specified Connection and Adapter (SqlAdapter, OleDbAdapter, OdbcAdapter, etc). So in my mind I envision classes with two methods and a public data set that will be filled.               public DataSet DataSet { get; set; }          public void InsertTables(string ConnectionString, string[] TableNames, string[] Commands)          public void AddRelations(string[] PrimaryTables, string[] PrimaryKeys, string[] ChildTables, string[] ForeignKeys, bool[] NestingRules)      I already started with an OleDb Implementation that works well, and I want to set up something similar for other Data Access technologies. However, I want to be as efficient as possible with the code so am looking for advice on how to accomplish. I was thinking that the Template Method Design pattern could be a solid approach, but then I also thought that a single class that utilizes generics might work as well (I am new to C# and not that familiar with them). I am looking for a general example of how I could accomplish this with a good design pattern and/or generics. Here is what I have for the OleDbDesign. Any advice is greatly appreciated.                public class OleDbDataSetBuilder     {         private DataSet _DataSet;              public DataSet DataSet { get { return _DataSet; } }              public OleDbDataSetBuilder(string DataSetName)         {             this._DataSet = new DataSet(DataSetName);         }              public void InsertTables(string ConnectionString, string[] TableNames, string[] Commands)         {                  if (TableNames.Length != Commands.Length)             {                 throw new Exception("Error: Must provide a table name for each command.");             }                  OleDbConnection cn = new OleDbConnection(ConnectionString);                  OleDbDataAdapter adapter = new OleDbDataAdapter("", cn);                  adapter.SelectCommand = new OleDbCommand("", cn);                  for (int i = 0; i < TableNames.Length; i++)             {                 adapter.SelectCommand.CommandText = Commands[i];                      adapter.Fill(_DataSet, TableNames[i]);             }                  cn.Close();              }              public void AddRelations(string[] PrimaryTables, string[] PrimaryKeys, string[] ChildTables, string[] ForeignKeys, bool[] NestingRules)         {                  for (int i = 0; i < PrimaryTables.Length; i++)             {                 DataColumn pk = _DataSet.Tables[PrimaryTables[i]].Columns[PrimaryKeys[i]];                      DataColumn fk = _DataSet.Tables[ChildTables[i]].Columns[ForeignKeys[i]];                      DataRelation relation = _DataSet.Relations.Add(pk, fk);                      relation.Nested = NestingRules[i];             }         }     }


GWT vs JSF vs ZK vs Restful+JS

I'm planning to develop a web based ERP, which should be full-ajax and with desktop-like UI. It will be a data-entry & data-report application. For developing it I'm considering all technologies. GWT: I saw that with GWT Designer you could create cool UIs, but databinding seems to be too complex JSF: Netbeans no longer supports the visual web editor ZK: supports databinding in a relatively easy way, and has got an Eclipse- based visual editor Some people talk about REST + javascript as a winning choice I'd like to have your opinion about what could be the right choice. Thank you very much in advance!


Is it a good idea to provide different function signatures that do the same thing?

Here is a C++ class that gets constructed with three values.               class Foo{              //Constructor         Foo(std::string, int, char);          private:         std::string foo;         char bar;         int baz;     };      * * * All of the parameter types are different.   I could overload the constructor so that order doesn't matter.               class Foo{              //Constructors         Foo(std::string, char, int);         Foo(std::string, int, char);         Foo(char, int, std::string);         Foo(char, std::string, int);         Foo(int, std::string, char);         Foo(int, char, std::string);               private:         std::string foo;         char bar;         int baz;     };      But is that a good idea?   I started doing it because I knew what things a class/function needed;   I didn't always remember what order it took them in. * * * I've been assuming that the compiler optimizes this as if I called the same constructor.               //compiler will implement this with the same code?      //maybe not.. I could call a function to get a parameter,      //and that function could change the state of the program, before calling     //a function to get another parameter and the compiler would have to     //implement both     Foo foo1("hello",1,'a');     Foo foo2('z',0,"world");      What are your opinions on overloading a function so that the order doesn't matter? * * * Also, If I'm writing some utility functions,   Is it a good idea to provide different function names that do the same thing? eg.               void Do_Foo();     void DoFoo();     void do_foo();     //etc..      * * * I don't often see these two but similar conventions.   Should I break or embrace the habit?


What is the proper way to use an IDE to work on remote code?

One of the code bases I work on has a development environment that is running on a dev server and cannot be copied over to my PC to locally test and develop. I am wondering what is the proper way to work with this code base? It is object oriented and I have found it to be very tedious and time consuming to do my work using Vim when working on such a codebase. I have another project which I have running locally and I like to use Eclipse and sometimes Sublime text to make changes to the codebase. Is there a way to utilize such tools that I use locally with a remote project, and if so what is the proper way to set this up? Should I remotely mount my system? We do have git/hg setup with these environments however I like to test and debug things in very small changes and this would produce a lot of commits that are un-needed. As well it is also time consuming. Ideally it would be great to just be able to work like it is a local environment and when I save and refresh a page the change is there. Is my best solution mounting?


Are there any tools for remote coding interview?

Firstly, I'm not exactly sure if this question is a better fit over here, or on workplace.SE. So forgive me if it is in the wrong place. We are interviewing some candidates for a development position, and currently they are not in our city. We would like to give them simple coding tests to see how they will perform on the typical issues that we face in our daily work. Are there any specific tools geared towards this? Right now we are using Skype and I feel this tends to decrease the performance of a lot of developers since they tend to be shy, and often can't work when someone is directly staring at them. The problem with sending them the test questions by email are as follows:   1. It is not possible to know what their thought process is, sine we just see the end result. There is no discussion, or clarification of the question, which is an Important step.   2. There is no guarantee that the problems were solved by the candidates themselves. They could send it to a smarter friend, and we wouldn't be able to know. How are these problems usually solved?


Guid collisions

I have a product that lets game developers create games. Inside of their games they are required to give all the elements of their games GUIDs. I've told them that they need to generate their guids using a specific mechanism, but they seem to think that it won't cause any issues. What I'm concerned about is GUID collisions between games. Some developers just sequentially increment the last digit of their GUID, others zero out the last block and increment other parts, well others just pull together a random armada of numbers and letters for each one. My argument is that by doing this it dramatically increases the risk of colliding with other games that are both following the standard, and those that don't. Just as a heads up there are potentially hundreds of thousands of GUIDs involved here. Am I right in thinking this, or is it really improbable that this will really happen?


Just in time prize winning algorithm

I'm building a contest where you can win prizes by opening boxes. Whatever the box is open, i just send a request to the server to test if the user won something. Since this contest is not a "Register and we'll draw a winner after some time" type of contest, i'm a bit puzzled at what algorithm i should be taking to calculate chances to win. I've devised in an excel spreadsheet what i call a progressive winning algorithm in the form of:               ([Number of prizes left] / [Prizes i should have left at this time of contest]) / 4      Which gives me a rough percentage change of winning an item off the pool of remaining items around 25%. If there are many winners within a close timespan, the algorithm should automatically lower the chances of winning while going in the opposite direction if the scenario is different. What i'm afraid of is that not all my items will be drawn by the end of the contest because it's a linear calculation of expected gifts left or i'm afraid that, by chance, most of my prizes will be won after only half of the contest (and by chance i mean that lots of player get truly great random odds and keep winning) So my question is, how should i tackle this kind of scenario, what are already known methods for this and please keep it simple, i'm no mathematician nor statistician. * * * **Variables to take into account**   * 100 prizes to give out total   * Contest lasts five whole days   * Unknown number of participants   * Unknown participation rule but will probably be once per day based on a unique credential such as an e-mail address.   * It's an online contest where a user opens a virtual box, nothing physical


Practice programming guidance

I am a recent graduate so I understand a lot of the theory, object-oriented languages, and various data structures. I am competent in languages such as C++, Java, PHP, just to name the ones I'm strong at. Since graduation I bite the bullet and accepted a job outside of my field for now. So obviously I don't want to lose my edge and want to stay current. Most of my programming has been for academic reasons and a 3-month web programming (back-end) internship. I really want to program something to use my skills I've learned. I always hear program a game is great practice. However one problem with the Internet is it's robust volume of information and find myself reading one site then jumping to another & on & on. Where would you suggest is a good foothold to begin? It's always harder to start from scratch and that is where I am. I figure start with some 2D game and go from there, but then comes the question of which SDK to use, if any. I'm currently using Linux but I wouldn't mind developing in Windows either. I'm always thinking maybe I should try to develop a simple app for an Android phone as well. As you can tell I'm all over and just need a little direction. Any advice/website is greatly appreciated!


What are the difference between an edge case, a corner case, a base case and a boundary case?

I'm not a native English speaker. In my native language I'm aware of some terms used to refer to the condition checked to stop a recursion, and to the condition checked for extreme, unlikely or super-simple cases. In English, I've encountered the terms "edge case", "corner case", "boundary case" and "base case", but I can't quite figure out the differences and which is used to refer to what; I'd love to get some summary of the differences between them. In particular, I would be very happy if someone could provide annotations for the lines in the following code sample:                   int transmogrify(int n) {     1.      assert(n <= 1000000);     2.      if (n < 0) return -1;     3.      if (n == 1000000) return PRE_CALC;     4.      if (n == 0) return n+1;            // For stopping the recursion     5.      if (n == 1251) return 3077;             return transmogrify(n-1);         }      I _think_ it's:   1. Sanity check   2. Input check   3. Boundary case? Edge case? Corner case?   4. Base case? Boundary case?   5. Corner case? Edge case?


Using Scrum/agile with multiple customers

I am a big believer in agile development. I just changed jobs, and I am now working for a company that coordinates big development projects for (rather large) groups of customer organizations. My job is to find the right contractors for the projects, and make sure that the customer organizations are as happy as possible, and control the process. There is nothing in the world that would make me happier, than if I could introduce Scrum or a similar agile method into this situation, making my company's main role the product owner. It would make sense on so many levels. There are some issues though: Since Scrum is a rapid-response method, I wonder if Scrum is the right method for a place like this, where not one customer but a big group of customers have to be involved in prioritizing of the backlog from sprint to sprint. It takes place in a quite political environment. What pitfalls and possibilities do you see in a situation like this? Can this situation simply be handled by longer sprints? There is a general understanding and empathy for the agile agenda in the company, but the issue I describe here seems to be a major obstacle. I would really appreciate your input. I need good ammo for my agile preaching :o)


Making internal search engine return results that adhere to local permissions on an internal web application

I have an ElasticSearch search engine and an internal web application. Prior to applying the security model, search results were very fast. The security model restricts some users from accessing certain pages. We have 7 "types" of pages. Our process is currently this:   1. Search engine queries all records   2. For each type of result, I get all recordIds of that type from the database that the user is allowed to access. This ensures I only call the database a max of 7 times (once per type)   3. I do an intersect between the records the user can access and the records search is returning The above approach isn't fast enough. I have an autosuggest search and each query takes up to 2 seconds now. What is a typical way to make a search engine return results that adhere to security? Another developer has recommended I store the security permissions directly in ElasticSearch itself(essentially mirroring what our sql server has). Edit: Each record has a page. We can assume 200-500 users and 25000+ records.


Using two versions of a class in the same code

At my job, in our core project, we have a Validation class that has been evolving with the years. And ee have an old project with an User class that uses an old version of the Valdiation class. And we have to update some functionality that requires new validation methods. All those methods are implemented in our latest Validation class. But the new Validation class isn't backwards compatible, so we can't just put the new one in place. I thought that a good solution would be to upgrade all the code that references the Validation Class or making it backwards compatible but, obviously, both of them would take a lot of time. Finally, it was decided that adding the latest version and calling it Validation2 works just fine, some methods use Valdiation and others Validation2. I think that will bring a lot of problems later, because you don't know when to use one or another as the names stop being meaningful. What could be a better option to deal with this? Also, the Validation class was the best example, but we have the same problem with a lot of bigger and more complicated classes and now we have a lot of "duplicated" classes. The language is PHP, but could happen in other languages too.


Degree after BSc in Computer Science: Marketing, MBA, Techno-MBA, HCI?

Since a year I am a graduated Computer Engineer, and am now working in named field since 2 years. However, I'd like to get a Masters in a "softer" field and was thinking over the following choices:   * **MBA** : Master of Business Administration, to bridge the business world with the world of computer science. Would give me an interesting job, travel potential, high salary etc.   * **Techno-MBA** : Sort of an MBA, but aimed at people who already have a degree in Computer Science.   * **HCI** : Human Computer Interaction degree, something I have been **very** interested in, but feel like it doesn't have the growth potential of MBA/Techno-MBA   * **Marketing** : My most recent brainchild is a degree in Marketing, is this at all a good idea given my background? Growth potential? Main priority: Gaining a skill, and gaining a job allowing me to use my social skills. Which path has the best "career potential"? (Controversial I know) Any thoughts? Any feedback welcome. Edit: DOH. Realized that the first sentence makes no sense. Was running my own semi-successful business during last year of school.


When would you choose *not* to update a third-party library to a newer version?

Using third party libraries for productivity gains in software development is common. Unfortunately, along with the library's functionality we also import its bugs. Some of them get fixed in subsequent releases. So, to upgrade or not to upgrade, this is the question. I am interested in learning from experiences when upgrading to a newer version of the library was desirable, but after a cost/benefit analysis the conclusion was that upgrading was not a good solution "in the grand scheme of things". I am interested in finding out what _forces_ influence the decision towards _not_ upgrading.


Python vs. Java for embedded wireless module

We are developing a product at work which interfaces with basic I/O and sends data to a webserver over a GPRS connection. What i need to know before we commit to a product, is which language is more suited for this task: Java or Python? (or any language to be honest) As i said, it will run on a wireless module and open serial connections, read values, send data through GPRS connections to a webserver...


Should PHP view files be called something other than '.php'?

By default, any file that PHP touches is usually suffixed with `.php`. It's universally understood by Apache / Nginx as the default for PHP files and most setups expect PHP files to end in this extension. In short, `.php` is the standard for everything PHP. However, I'm wondering if perhaps view files should have a different extension to help differentiate them from other PHP files. First, when it comes to views I have found that almost all MVC frameworks using a matching view file named after the controller or method. In addition, you generally also have a matching model named the same thing. This causes a problem with most IDE's and editors. For example, you might have a "user" controller, a "user" view, and a "user" model. The results in having three files open called "user.php" which makes it a bother when you are moving around and clicking on the wrong tabs. Second, separating views as a fundamentally different kind of PHP file (the presentation type) is another argument for changing the extension of the view files to something other than `.php`. Something that immediately tells your brain what type of content belongs in it. Third, some applications expose parts (or all) of the PHP files in the webroot and it's directories. Rather than adding something like `<?php if(!defined(ABC)) die('not allowed');` it would be nice to have an easy way to forbid access to views while allowing other files like the customary `index.php`. **Are there any other good/bad reasons to think it's a good idea to change the file extension of view files?**


Lua-type Java integration with C++

So I'm curious: I've implemented Lua within C++ a few times before, and while it was relatively simple, it still didn't harness the power that I would have liked. I love how eclipse works, including javadoc locations, etc. and I was wondering if there was a way to integrate Java into a native application (that is cross-platform, of course) to do what Lua does, but with Java. This means I'd be able to build my own base classes and stuff, etc. Just an interesting thought! Any insight? EDIT: Also, what about MonoDevelop? Is it relatively easy to integrate? Is it compiled? Is it cross-platform-able?


Using function points as a metric for the velocity of a Scrum team?

I came across the idea of using function points as a metric for the velocity of a Scrum team. I saw it in a team and I found two articles mentioning a link between estimates and function points (http://www.ifpug.org/ISMA5-2010/Amol%20Keote-FunctionPointsAndAgile-Hand-in- Hand.pdf and http://www.cosmicon.com/portal/public/FromStoryPointsToCOSMIC.pdf). I am not sure how this can work, because if I understand it correctly, function points measure the _value_ of a feature (e.g. from the users perspective) whereas the velocity measures the _effort_ of finished features. And in my view there's no direct connection between these two. To put it another way: If you have (let's say) a stable Scrum Team which works 2 week Sprints, the number of functions points they deliver per Sprint should vary (possible wildly), which would render a velocity based on function points quite meaningless (e.g. for planning purposes)... Am I missing something here?


Have You Ever Had To Code "Badly" For Your Team?

I've been on the constant road of learning new concepts in OOP, Software Design, Architecture, etc. But there are times when you are in a team where those concepts are foreign to them and they don't have the time or the same eagerness to learn as you. The problem is if you design your code the "right" way, the people who code with 2kLOC classes won't understand it. Would you sacrifice good coding principles to support your team? What about a scenario where this will be a long term arrangement?


Does usage of advanced language features decrease maintainability?

On a code review, I've stumbled on an interesting idea, which I can't properly judge alone. Is it OK to improve readability of code by means of not widely known language syntax? When the original writer didn't use a special syntax designated for solving a specific coding problem, and solved it by simulating with workarounds — is it worth to refactor it for clarity and conciseness? What if even the code reviewer didn't know about the language feature? To be specific, I'll bring the exact issue I've met on the code review — but keep in mind that this is just an example. So the original code was a little web service in Python. At some point, there arised a requirement for several request handlers to be protected with an authentication mechanism. Somebody solved it with inheritance:               class AuthOnlyAccess:         def GET(self, *args):             if not hasattr(self, 'PROTECTED_GET'):                 raise web.Nomethod()                  if check_auth():                 return self.PROTECTED_GET(*args)             else:                 raise web.Unauthorised()              def POST(self, *args):             if not hasattr(self, 'PROTECTED_POST'):                 raise web.Nomethod()                  if check_auth():                 return self.PROTECTED_POST(*args)             else:                 raise web.Unauthorised()          ...          class FooHandler(AuthOnlyAccess):         def PROTECTED_GET(self, a, b, c):             handle_foo_get(a, b, c)              def PROTECTED_POST(self, x, y, z):             handle_spam_eggs()          ...     <more handlers deriving AuthOnlyAccess>      The refactorer found this code ugly and introduced a decorator:               from functools import wraps     ...          def requires_auth(wrapped_func):         """ (a little doc telling that this is a decorator and how to use it) """         @wraps(wrapped_func)         def decorator(*args):             if check_auth():                 return wrapped_func(*args)             else                  raise web.Unauthorized()              return decorator          ...          class FooHandler:         @requires_auth         def GET(self, a, b, c):             handle_foo_get(a, b, c)              @requires_auth         def POST(self, x, y, z):             handle_spam_eggs()          ...     <more refactored handlers>      The reviewer argues that this change actually **decreases** maintainability, because most of the team doesn't know decorator syntax. So the next person visiting the refactored code could be puzzled by the construct — but not with the previous version. There's also a convincing argument that **most of the codebase isn't in Python** , (the language is there only for that little web service), and hence team members aren't required to have even shallow knowledge of Python. However, to work with code, one's going to need to know its language, right? And if you have the temptation to say that python decorators aren't _that_ advanced syntax — please remember that this is only an example. Every language has its dark corners. (But to learn those corners means to become better.) So the question is... Can you read unknown syntax? Is the elegance worth the surprise? At least, what are the tradeoffs and/or guidelines you can name? I do really need some opinions from the community of programming professionals.


How do I initialize a Scala map with more than 4 initial elements in Java?

For 4 or fewer elements, something like this works (or at least compiles):               import scala.collection.immutable.Map;          Map<String,String> HAI_MAP = new Map4<>("Hello", "World",                                             "Happy", "Birthday",                                             "Merry", "XMas",                                             "Bye", "For Now");      For a 5th element I _could_ do this:               Map<String,String> b = HAI_MAP.$plus(new Tuple2<>("Later", "Aligator"));      But I want to know how to initialize an immutable map with 5 or more elements and I'm flailing in Type-hell. # Partial Solution I thought I'd figure this out quickly by compiling what I wanted in Scala, then decompiling the resultant class files. Here's the scala:               object JavaMapTest {       def main(args: Array[String]) = {         val HAI_MAP = Map(("Hello", "World"),                           ("Happy", "Birthday"),                           ("Merry", "XMas"),                           ("Bye", "For Now"),                           ("Later", "Aligator"))         println("My map is: " + HAI_MAP)       }     }      But the decompiler gave me something that has two periods in a row and thus won't compile (I don't think this is valid Java):               scala.collection.immutable.Map HAI_MAP =             (scala.collection.immutable.Map)              scala.Predef..MODULE$.Map().apply(scala.Predef..MODULE$.wrapRefArray(                     scala.Predef.wrapRefArray(                             (Object[])new Tuple2[] {                                     new Tuple2("Hello", "World"),                                     new Tuple2("Happy", "Birthday"),                                     new Tuple2("Merry", "XMas"),                                     new Tuple2("Bye", "For Now"),                                     new Tuple2("Later", "Aligator") }));      I'm really baffled by the two periods in this:               scala.Predef..MODULE$      I asked about it on `#java` on Freenode and they said the `..` looked like a decompiler bug. It doesn't seem to want to compile, so I think they are probably right. I'm running into it when I try to browse interfaces in IntelliJ and am just generally lost. Based on my experimentation, the following is valid:               Tuple2[] x = new Tuple2[] { new Tuple2<String,String>("Hello", "World"),                                 new Tuple2<String,String>("Happy", "Birthday"),                                 new Tuple2<String,String>("Merry", "XMas"),                                 new Tuple2<String,String>("Bye", "For Now"),                                 new Tuple2<String,String>("Later", "Aligator") };          scala.collection.mutable.WrappedArray<Tuple2> y = scala.Predef.wrapRefArray(x);      There is even a `WrappedArray.toMap()` method but the types of the signature are complicated and I'm running into the double-period problem there too when I try to research the interfaces from Java.


unit testing variable state explicit tests in dynamically typed languages

I have heard that a desirable quality of unit tests is that they test for each scenario independently. I realised whilst writing tests today that when you compare a variable with another value in a statement like:               assertEquals("foo", otherObject.stringFoo);      You are really testing three things:   1. The variable you are testing exists and is within scope.   2. The variable you are testing is the expected type.   3. The variable you are testing's value is what you expect it to be. Which to me raises the question of whether you should test for each of these implicitly so that a test fail would occur on the specific line that tests for that problem:               assertTrue(stringFoo);     assertTrue(stringFoo.typeOf() == "String");     assertEquals("foo", otherObject.stringFoo);      For example if the variable was an integer instead of a string the test case failure would be on line 2 which would give you more feedback on what went wrong. Should you test for this kind of thing explicitly or am i overthinking this?


A design pattern for data binding an object (with subclasses) to asp.net user control

I have an abstract class called Address and I am deriving three classes ; HomeAddress, Work Address, NextOfKin address. My idea is to bind this to a usercontrol and based on the type of Address it should bind properly to the ASP.NET user control. My idea is the user control doesn't know which address it is going to present and based on the type it will parse accordingly. How can I design such a setup, based on the fact that, the user control can take any type of address and bind accordingly. _I know of one method like :-_ Declare class objects for all the three types (Home,Work,NextOfKin). Declare an enum to hold these types and based on the type of this enum passed to user control, instantiate the appropriate object based on setter injection. As a part of my generic design, I just created a class structure like this :- ![Sample UML](http://i.stack.imgur.com/DyML8.png) I know I am missing a lot of pieces in design. Can anybody give me an idea of how to approach this in proper way.


Which operating system book do you recommend?

I want to read a good book about operating systems. More specifically, I want to read about how common problems - such as managing virtual memory, handling traps, doing context switches, managing processes and threads, etc. - are usually solved. To wit, I'm not looking for a book about how to program _towards_ an operating system; I'm looking for a book about how to _write_ an operating system. I hope this makes the question clear. Please only write **one book per answer** , for voting purposes.


What is a "powerful" language?

I have often seen people fighting over that their favorite language is more "powerful" than others. When it comes to describing a programming language, I can understand what an object oriented language is or what a dynamic language is, but I still can't figure out what exactly a "powerful" language is. What are your thoughts?


Is it a good idea for JS objects to draw themselves when the page loads?

So normally I would only use JS to modify the dom after the user interacts with something or some event goes off. This seems right for some reason. But I'm developing a widget based app where widgets need the capability to draw (print) themselves and it feels redundant to send the widget's html via the initial http request when I can just print them with the js method when the page loads. Should I be trying to avoid printing html elements with JS on the page load as a rule or is it just an optimization thing?


Graduated transition from Green - Yellow - Red

I have am having algorithm mental block in designing a way to transition from Green to Red, as smoothly as possible with a, potentially, unknown length of time to transition. For testing purposes, i will be using 300 as my model timespan but the methodology algorithm design needs to be flexible enough to account for larger or even smaller timespans. Figured using RGB would probably be the best to transition with, but open to other color creation types, assuming its native to .Net (VB/C#). Currently i have:               t = 300     x = t/2     z = 0     low = Green (0, 255, 0)     mid = Yellow (255, 255, 0)     high = Red (255, 0, 0)      Lastly, sort of an optional piece, is to account for the possibility of the `low`, `mid`, and `high` color's to be flexible as well. I assume that there would need to be a check to make sure that someone isnt putting in `low = (255,0,0)`, `mid=(254,0,0)`, and `high=(253,0,0)`. Outside of this anomaly, which i will handle myself based on the best approach to evaluate a color. ### Question:   * What would be the best approach to do the transition from `low` to `mid` and then from `mid` to `high`?   * What would be some potential pitfalls of implementing this type of design, if any?


What is an appropriate language for expressing initial stages of algorithm refinement?

First, this is not a homework assignment, but you can treat it as such ;). I found the following question in the published paper The Camel Has Two Humps. I was not a CS major going to college (I majored in MIS/Management), but I have a job where I find myself coding quite often. > For a non-trivial programming problem, which one of the following is an > appropriate language for expressing the initial stages of algorithm > refinement? > > (a) A high-level programming language. > > (b) English. > > (c) Byte code. > > (d) The native machine code for the processor on which the program will run. > > (e) Structured English (pseudocode). What I do know is that you _usually_ want to start your design implementation by writing down pseuducode and then moving/writing in the desired technology (because we all do that, right?) But I never thought about it in terms of **refinement**. I mean, if you were the original designer, then you might have access to the original pseudocode. But realisticly, when I have to maintain/refactor/ **refine** somebody elses code, I just keep trucking with the language it currently resides in. **Anybody have a definitive answer to this?** As a side note, I did a quick scan of the paper as I havn't read every single detail. It presents various score statistics, can't find where the answers are with the paper.


Should interfaces extend (and in doing so inherit methods of) other interfaces

Although this is a general question it is also specific to a problem I am currently experiencing. I currently have an interface specified in my solution called               public interface IContextProvider     {        IDataContext { get; set; }        IAreaContext { get; set; }     }      This interface is often used throughout the program and hence I have easy access to the objects I need. However at a fairly low level of a part of my program I need access to another class that will use _IAreaContext_ and perform some operations off it. So I have created another factory interface to do this creation called:               public interface IEventContextFactory      {        IEventContext CreateEventContext(int eventId);     }      I have a class that implements the _IContextProvider_ and is injected using NinJect. The problem I have is that the area where I need to use this _IEventContextFactory_ has access to the _IContextProvider_ only and itself uses another class which will need this new interface. I don't want to have to **instantiate** this implementation of _IEventContextFactory_ at the low level and would rather work with the _IEventContextFactory_ interface throughout. However I also don't want to have to inject another parameter through the constructors just to have it passed through to the class that needs it i.e.               // example of problem     public class MyClass     {         public MyClass(IContextProvider context, IEventContextFactory event)         {            _context = context;            _event = event;         }              public void DoSomething()          {            // the only place _event is used in the class is to pass it through            var myClass = new MyChildClass(_event);            myClass.PerformCalculation();               }     }      So my main question is, would this be acceptable or is it even common or good practice to do something like this (interface extend another an interface):               public interface IContextProvider : IEventContextFactory      or should I consider better alternatives to achieving what I need. If I have not provided enough information to give suggestions let me know and I can provide more.


Returning results of method on batch list?

The title is a bit vague so I'll try to elaborate. I have a function               makeFoo(int bar) -> returns Foo or throws Exception.      I also have a batch version of this               makeFoos(int[] bars) -> returns Foo[]      which basically loops through bars and runs makeFoo() on them. Issue is, if while running makeFoos(), makeFoo() throws an Exception, what do I do? I don't want to break out of makeFoos() because I want to continue processing the rest of the bars. But also, I want to retain the Exception that was thrown. My initial solution is, instead of returning Foo[], I return Result<Foo>[]. Where Result is a wrapper class:               class Result<T>:         T data;         Exception e;      Is there a better way that I can approach this? * * * Edit: Apologies if this is considered a duplicate post, but I posted a more general version of this question here: Result Object vs. Exceptions


How do .so files avoid problems associated with passing header-only templates like MS dll files have?

Based on the discussion around this question. I'd like to know how .so files/the ELF format/the gcc toolchain avoid problems passing classes defined purely in header files (like the std library). According to Jan in that answer, the dynamic linker/loader only picks one version of such a class to load if its defined in two .so files. So if two .so files have two definitions, perhaps with different compiler options/etc, the dynamic linker can pick one to use. Is this correct? How does this work with inlining? For example, MSVC inlines templates aggressively. This makes the solution I describe above untenable for dlls. Does Gcc never inline header-only templates like the std library as MSVC does? If so wouldn't that make the functionality of ELF described above ineffective in these cases?


Program Design clearness vs convenience

I've recently disputed with my colleague about the following situation: I've developed a framework that processes the resources (in java, although its not really important). It goes (simplified, pseudo-code) like this:               class Algorithm {         Processor processor = ...;         execute() {             forEach(Resource r : readResourceNamesFromFileSystem()) {                DomainObject do = convertResourceToDomainObject(r);                processor.process(do);             }                }           }          interface Processor {          process(DomainObject do);     }      Class **Algorithm** is an entry point to my framework. Resource is a representation of some content in the filesystem (it has methods for reading the data from file and the file name, which is important) Class **DomainObject** (declaration is omitted) is a java representation of the content of the file depicted by Resource. DomainObject only has data and doesn't have a filename inside. Class **Processor** represents the business logic layer, the DomainObject can be processed, stored in Database and so forth. The content data is supplied by others, we just know that these files contain the data that can be converted into DomainObject(s) which is a real object we work with in the framework. We store one DomainObject in one file. Now we argue about the file name. Colleague of mine wants the file name to be propagated into the Processor and potentially to all the layers because its easy to print the logging message/throw an exception that contains a file name if something goes wrong during the processing, or maybe to write the message like "domain object stored in file ( **here__comes__filename** ) has been processed successfully". I see the point of my colleague (convenience) but I'm sure it breaks the design and encapsulation because the processor module shouldn't really be aware of the "origin" of the DomainObject (today we store them in files one DomainObject per file, tomorrow we'll maybe use something else, something that doesn't necessarily has a filename). I claim that we better catch the exception in the Algorithm.execute method and rethrow the exception with a filename/ log the filename. The log file will be less readable but the encapsulation won't be broken. In my understanding its a design vs clearness. Could you please share your opinion, who is right, who is wrong? Should I sacrifice the design for the clearness of logs? BTW I've promised my colleague to ask this question so we'll read the possible answers together :) Thanks a lot in advance and have a nice day


Shared FIFO file descriptor

is ok to open fifo with one FD and share it with multiple threads? or is it better to have multiple fds opened for the same fifo and share these fds with the threads? BTW, I'll be doing write and read. The environment is linux, C, pthreads


Using Visual Studio as a Task-Focused IDE

Are there patterns or libraries or any official Microsoft SDK for using Visual Studio as a specifically Task-Focused UI? For example, both Revolution R (IDE for the R language) and SQL 2012 (and I think SQL 2008 and possibly 2005) use Visual Studio as the underlying IDE framework. Is there an officially supported SDK and/or examples/samples for doing this type of thing? I am building a language Parser for an existing language - whose only available IDE is INSANELY expensive - using Irony (and eventually will generate a Language Service as well). Any direct or indirect suggestions/answers are appreciated.


Relative encapsulation design

Let's say I am doing a 2D application with the following design: There is the Level object that manages the world, and there are world objects which are entities inside the Level object. A world object has a location and velocity, as well as size and a texture. However, a world object only exposes `get` properties. The `set` properties are private (or protected) and are only available to inherited classes. But of course, Level is responsible for these world objects, and must somehow be able to manipulate at least some of its private setters. But as of now, Level has no access, meaning world objects must change its private setters to public (violating encapsulation). How to tackle this problem? Should I just make everything public? Currently what I'm doing is having a inner class inside game object that does the `set` work. So when Level needs to update an objects location it goes something like this:               void ChangeObject(GameObject targetObject, int newX, int newY){      // targetObject.SetX and targetObject.SetY cannot be set directly      var setter = new GameObject.Setter(targetObject);      setter.SetX(newX);       setter.SetY(newY);      }      This code feels like overkill, but it doesn't feel right to have everything public so that anything can change an objects location for example.


What if any languages treat undisposed resources as an error?

I've seen lots of code like the following example. It's in Python, but the same mistake is made in all languages with managed resources:               f = open('foo.txt', 'rb')     for line in f: print line      That's it. The error is that `close(f)` wasn't called so the file handle is kept open until some indeterministic time in the future when the runtimes memory management decides to reclaim memory. Python has `with` and c# has `using` to help make resource cleanup easier, but let's disregard those features for a minute. Given that:   1. It's a programming error not to explicitly close open files.   2. The runtime can detect that an open file has not been closed. Why then doesn't the runtime throw an error instead of being "helpful" and closing the file for the programmer? That would be the fail fast and fail early strategy. Is there a technical reason why it can't? Is there any languages that does it? Has the idea been considered before (I've googled but not found anything)? Here is how you **almost** implement the feature in Python:               class mustclose:         def __init__(self, f):             self.f = f         def __del__(self):             if not self.f.closed:                 raise Exception("You forgot to close() me!")     k = mustclose(open('foo.txt', 'wb'))     #k.f.close()      Two problems: It requires wrappers, Python doesn't like to throw exceptions from destructors. (Read this http://stackoverflow.com/questions/2807241/what-does-the- expression-fail-early-mean-and-when-would-you-want-to-do-so SO question for background on why failing fast is often desirable)


How do I preview my mobile web application on a Windows 7 PC?

I am developing a mobile web application that may be browsed in an iPhone. I would like to test this application, but I lack a mobile web device. How can I test this mobile application on a Windows 7 PC?


What should I recommend a small company looking for C# developers

Here is the issue. I am a senior developer, and one of the start-ups I designed the system (management system/database/web) a long time ago, have grown and need software updates. I have left their system to another developer long time ago, but apparently he has left the job, and so they are asking me if I can suggest them where to find a new one. The problem is that the company has no clue that the IT is not cheap. They expect multiple features to be added for 40$, so that's an issue. Actually one of the reasons why I left the project when I did. Lots of expectations, little pay, also I know those people outside work, so I decided to avoided stressing the nonwork-relationships and left the project gracefully. Today they asked me for an advice, and I told them that the feature list they want is probably going to cost some if they'll get a senior developer for the job. So I guess their best bet is to find someone who loves coding and has just finished the school. Which would give someone a chance to code for money which is good for a student, and at the same time, allow the student to get some hands on experience. Then again, the system is not exactly 20 line console program, there is an MSSQL database, ASP.NET web page and content management system with all the AJAX stuff and some other things. So student straight out of school could have some problems with that. But, I thought about the issue some more, and I think that junior developer is a tricky deal, without mentoring, he can either screw up royally, or just do what's asked. Also, it seems no one is coming to interviews at all, which is weird, or maybe not. What should I suggest them?


Maintaining Method Signatures across languages?

I'm finishing up a port I did of a portion of a Java Library. The library calculates sunrise and sunset for a given latitude and longitude. The original Java library also calculated various times based on sunrise and sunset, which I plan to get to later. That said, I'm working with Objective-C and the Cocoa touch framework. The original methods, being Java, all began with `get` and took their arguments in parenthesis. However, Objective-C has a different method structure, so the methods end up looking different. For example, `public double getUTCSunset(AstronomicalCalendar astronomicalCalendar, double zenith, boolean adjustForElevation)` becomes this: `- (double) getUTCSunsetForDate:(NSDate*)date andZenith:(double)zenith adjustForElevation:(BOOL)adjustForElevation`. The problem here is twofold. First of all, according to the Apple Documentation on coding convention, method names (and "getters"), should not include `get` in them. However, a second issue arises if we drop the `get`. We end up with a method signature that begins with a capital letter, which is also not supposed to happen. How would you rewrite this method, while keeping the method signatures similar enough to be recognizable to each other?


Preparing For a New Programming Project

I consider myself to be a novice programmer -- a noob is you like. As such I'm still not sure how to get started on a project where I will be doing stuff that I've never done before. For instance, I would like to write a program that can download videos from YouTube and convert them to a format specified by the user. I've never done anything like this before and I really have no idea where to start. Rather, I have no idea what I should search for. If I search for "YouTube Downloader" then I get hit with a bunch of useless links to existing YouTube Downloader sites, most of which don't work. What I want to know is how to get started on a project that I know nothing about. How do I find out what is required for this project? How do I find out what languages are best suited for this? How can I find out if there are any APIs that would be particularly useful? Also, what other questions should I be asking myself when preparing to take on a new project?


Optimizing programs by identifying and taking evaluation (calculation) shortcuts

Recently I am working on a project that involves a lot of simple numerical calculations being applied to large arrays. The numerical values are very simple but there are many different types, such as positive integers, negative integers, small floating point numbers, and so on. SIMD programming techniques (such as SSE) are widely used. I noticed that a lot of times processing speed can be improved if I can find shortcuts in the calculations. For example, if the inputs are integers and the outputs are also integers, I should try my best to avoid converting to floating point numbers if possible. For simple chained calculations this is easy. However, when we increase the number of operations that can be combined, we find that we have to manually code those SIMD instructions for each case. I have studied the approaches taken by various vectorization libraries, and observed that while their approaches are very elegant in code using metaprogramming techniques, most compilers aren't able to generate optimized machine instructions from the results. If I represent the calculations with command objects, will I have a better chance of matching small sections of the command chain and substituting with shortcuts?


When to do code reviews when doing continuous integration?

We are trying to switch to a continuous integration environment but are not sure when to do code reviews. From what I've read of continuous integration, we should be attempting to check in code as often as multiple times a day. I assume, this even means for features that are not yet complete. So the question is, when do we do the code reviews? We can't do it before we check in the code, because that would slow down the process where we will not be able to do daily checkins, let alone multiple checkins per day. Also, if the code we are checking in merely compiles but is not feature complete, doing a code review then is pointless, as most code reviews are best done as the feature is finalized. Does this mean we should do code reviews when a feature is completed, but that unreviewed code will get into the repository?


Calculation of Milestones/Task list

My project manager assigned me a task to estimate the development time for an iPad application. Lets assume that I gave estimation of 15 working days. He thought that the number of days where too many and client needed the changes to the application urgently (as in most of cases). So, he told me: "I am going to assign **two** developer including you and as per my understandings and experience it won't take more than **seven** working days." **Clarifications** I was given the task of estimating development time for an individual. How could I be sure that 2 developers are going to finish it within 7 days? (I am new to team & I hardly know the others abilities) **Questions**   * Why do most of project managers / team leaders have understandings like:      * If one developer requires N days,     * Then two developers would require N/2 days,   * Do they think something like `developer = s/w production machines`?   * Should a team member (developer, not team lead or any higher post) estimate other developers work? I didn't deny anything in the meeting and didn't said, but what should be the appropriate answer to convince them that N/2 formula that they follow is not correct?


Do TODO comments make sense?

I am working on a fairly big project and got the task to do some translations for it. There were tons of labels that haven't been translated and while I was digging through the code I found this little piece of code               //TODO translations      This made me think about the sense of these comments to yourself (and others?) because I got the feeling that most developers after they get a certain piece of code done and it does what it's supposed to do they never look at this until they have to maintain it or add new functionality. So that this `TODO` will be lost for a long time. Does it make sense to write this comments or should they be written on a whiteboard/paper/something else where they remain in the focus of developers?


Requirement, architecture data capture tool

Are there any tools available for the following use case: I am planning to write a complex application and now I just know about the basic functional requirments. I am refining the functionality with more and more details. I am also writing down how to implement this in software architecture perspective. I am in a situation where there are multiple ways implement a certain functionality and based on the selected approach, other parts of the program will also change. At this moment, I don't want to decide on the approach to use, I just want to list down all the options, present to a wider audience and get it finalized. Are there any standard software tools to do this? I know I can use MS excel or some mind mapper tools, but just thinking of some standard tools (not just for programmers, but for managers and other) availability Thanks, Den


What relationship would this be and how to implement

I have a pet project where I am making a Grade Book Application to better teach several different topics in DB, OOP and Planning. Im running into some issues with the database planning of things. For the record I am learning all of this by using online resources, books and trial and error in no way am I professional. I have 3 Tables (Teachers, Courses, and Assignments). 1) Many Teachers can Teach Many Courses - So this would be a M2M Relationship where I would need a third table to cross reference Teachers and Courses by their PK. Is it okay to have that third table have extra columns to show unique data about the courses like Title of the course or should that go into the course table? And if it depends how would you know which is the best way? 2) One Course can have Many Assignments or is it Many Courses can have Many Assignments? I feel this is a stupid question but I can not grasp on which would be a correct fact statement? 3) Does anyone know of any Database Diagrams that shown an example of a very simple gradebook layout, I have been looking on google but couldn't find anything that was not in my realm.


Sequentially/parallel algorithm for extracting blob outer perimeter/contour length

I have labelled the connected components in a binary image and found their areas and bounding boxes. The components are not necessarily filled, and may contain holes. I wish to identify the component that resembles a pupil the most. For this, I would also like to extract ( **only** ) their outer perimeter lengths, for calculating circularity, since these are good features for pupil detection. I plan to do this sequentially and then move the algorithm to CUDA afterwards, so the algorithm should be parallelisable to some extent. I should note that this work is for my thesis, and I am not asking you to solve anything for me, just provide some feedback on my research so far. I investigated tons of articles for this problem, but it seems most of them are concerned with connected component labelling and not feature extraction. Alas, I found three candidates, and ~~two~~ one of my own design:   1. **The Marching Squares algorithm**. It sounds promising (also embarassingly parallel), but it appears to extract all perimeter lengths, including inner contours, without modification, which will likely overestimate perimeter lengths. However, since I am looking for the pupil, a homogenously colored area, it will likely not overestimate the pupil. The overestimation might also yield bad results for other irregularly shaped blobs, which should be fine if they are then not selected.   2. **The Chain Code algorithm** (used by OpenCV's findContours function): Seems pertty good as well, and parallel solutions do exist, but I worry it might fail if the stopping criterion is not good enough (see here, at the bottom near Jacob's stopping criterion). However, it should be able to extract only the outer contour and give good approximations.   3. **The Convex Hull algorithms** : While parallel solutions exist, I worry that it might make a blob more circular than it really is, if points are scattered in a way that favors this. Should give good results for the pupil blob though.   4. ~~**Algorithm 1** : You could launch some threads that trace from each side of the blob's bounding box towards the opposite side. When the threads "hit" a pixel with the blob's label, they mark it as visited and sum the hits. When another side is traced, visited pixel are ignored, hit pixels are summed again etc., and the total is returned.~~   5. **Algorithm 2** : I also tried counting the number of pixels with a background pixel in their Moore neighborhood, but this overestimates the contour if enough holes are present. I would appreciate some suggestions before I try to code everything since I am on a schedule. Again, I'm just asking for advice, not solutions.


In what situations does it make sense to use an enumeration when writing object-oriented code?

Enumerations1 are often associated with procedural code rather than object- oriented code. They tend to give rise to similar switch statements scattered through the code, and in general, these are replaced by polymorphism in object-oriented code. For example, see _Replace Type Code with Class_ , _Replace Type Code with Subclasses_ , and _Replace Type Code with State/Strategy_ in _Refactoring_ by Martin Fowler. Closely related, see _Replace Conditional With Polymorphism_ in the same volume; Bob Martin also has quite a bit to say on the disadvantages of switch statements in _Clean Code_ (for example, heuristic G23 _Prefer Polymorphism to If/Else or Switch/Case_ ). However, since object-orientation, like any other good paradigm, can be a powerful tool but is not a silver bullet, are there times when using an enumeration is a good decision? * * * 1I use this term broadly; not just for something which is strictly an `enum` in a C-based language, but for any set of entities that are used to represent it (a class with a set of static members, etc...).


In Asp.net, how browser knows a textbox is registered with server side TextChanged event?

When I evaluate asp.net control events, I am not able to identify how the browser is aware of asp.net textbox is subscribed to serverside textchanged event or not. When I look the server generated HTML code, there is not information about the TextChanged event. **ASP.Net Declaration**               <asp:TextBox ID="txtInput" runat="server" OnTextChanged="txtInput_OnTextChanged"         AutoPostBack="false" />      **Server Generated HTML Code**               <input name="ctl00$MainContent$txtInput" type="text" value="SivaText Input ChangedText Input Changed.V ChangedText Input Changed.V Changed" id="MainContent_txtInput">


How to be better at reviewing code?

First I firmly believe in the code review process and always want someone else to review my code. My question really centers around how can I do a better job at performing a code review for someone else? I know that to perform a code review you need to have knowledge of the how the existing code works and a knowledge of what the local standard is, both of which I feel that I know very well. Still I feel like I never do a good enough code review for other people. Also I know that certain people seem to do a better job review code than others so I am wondering for those that are great code reviewers what are the techniques that you use?


Handling multiple clients using single application

We are developing an ERP web application using Vaadin framework where each of the potential client companies will have their own data and file storage. Current implementation only allows having one client company per application instance, what consequently requires separate database schema and file storage. Some of the clients may want specific customizations based on their needs. Having few clients doesn't cause much trouble, but if number of clients would grow, then maintaining dozens of application instances will be a real challenge. We are reaching that point where we have to choose one these options:   1. Improve our architecture to allow all client companies manage their data on a single application instance and restrict personal customizations to the application;   2. Stick with the current implementation and just keep increasing number of running application instances on the server. Which of these options is considered better practice and would make the system easier to maintain? Is there a different solution for this kind of situation? Edit: Application is currently in development stage. The server with all the potential application instances will be run by ourselves. Each instance will be deployed in a WAR package via Apache Tomcat server.


What technologies are used for an Android/iPhone App to interact with a database

Do Android/iPhone Apps use AJAX to interact with the backend? If yes, is this common? Or do most apps use a different method for fetching database information. And if so, what other methods are there? Are server-side languages ever involved, and if so, is that more common to see with app development?


What happens to get database information on the server-side with AJAX?

I'm slightly confused about how AJAX works. I mostly understand the PHP/MySQL model of retrieving database information for the user, but how does AJAX do it? From what I understand the AJAX engine sends an HTTP request to the backend which does some magic and returns XML data to the AJAX engine which translates it to HTML+CSS for the user to see, but what happens when it sends that first HTTP request to the backend? Is a server-side language acting as the middleman there to get data from the database for the rest of the process? Also, does HTML5 put any extra spin on the usage of AJAX?


Meaningful concise method naming guidelines

Recently I started releasing an open source project, while I was the only user of the library I did not care about the names, but know I want to assign clever names to each methods to make it easier to learn, but I also need to use concise names so they are easy to write as well. I was thinking about some guidelines about the naming, I am aware of lots of guidelines that only care about letters casing or some simple notes. Here, I am looking after guidelines for meaningful but yet concise naming. For example, this could be part of the guidelines I am looking after:   * Use Add when an existing item is going to be added to a target, Use Create when a new item is being created and added to a target.   * Use Remove when an existing item is going to be removed from a target, Use delete when an item is going to be removed permanently.   * Pair AddXXX methods with RemoveXXX and Pair CreateXXX methods with DeleteXXX methods, but do not mix them. As the above samples show,I would like to find some online material helping me with naming methods and other item complying with English grammar and word meanings. The above guidance may be intuitive for native English speakers, but for me that English is my second language I need to be told about things like this.


WCF vs Web API, Deeper details?

**Before I continue, I just want to mention I have heavily researched and searched on this topic, but I need the opinion of people who have worked/and or have practical knowledge with regards to this topic.** We are currently looking at developing an API so that clients can utilize this. We are definitely set on REST as opposed to SOAP, but I am still a little unclear about what exactly the difference is, if you go down to microscopic detail. Having a look at msdn (Choosing which technology to use), the link below: http://msdn.microsoft.com/en-us/library/jj823172.aspx The differences are clear. However, the first point states for **WCF** : Enables building services that support multiple transport protocols (HTTP, TCP, UDP, and custom transports) and allows switching between them. For **ASP.NET Web Api** : HTTP only. First-class programming model for HTTP. More suitable for access from various browsers, mobile devices etc enabling wide reach. So, both support HTTP, but WCF supports more protocols in addition. What makes ASP.NET Web API more suitable for, I quote: "More suitable for access from various browsers, mobile devices etc enabling wide reach." if both support HTTP? We have until now, relied heavily on PC use. What I am getting to, and finally my question is: We plan on going mobile, and moving a lot more to multiple devices, browsers etc. But I just would not like to go on a service on the basis of a bit of text saying "Web API" is more suitable? IS it more efficient, less resource intensive etc.? With regards to future proofing? Would we be better of with WEB API and why? Just lastly, we have existing SOAP services, everything we have is built in SOAP. Please do not hesitate to go into detail, I am not an experienced dev, just trying to add a contribution to this project. Just a last couple of requirements: 1) We plan on utilizing JSON. 2) We are limited to .NET 3.5/4. 3) Must be REST.


boolean operations in C using bitfields

I am trying to implement boolean data type in C. Basically, I am working with sets. The following code can be used to access each bit but I am unsure whether I can represent sets using this method. Can somebody clarify this for me?               struct SET {     unsigned int b0     :1;     // bit 0 single bit     unsigned int b1     :1;     // bit 1 single bit     unsigned int b2     :1;      unsigned int b3    :1;      };      I can define two structures s1 and s2.. and I will be able to access each bit of these structures (treated as boolean strings). I will have to perform set operations like UNION, INTERSECTION and MEMBERSHIP. Is this even possible in C? Note: I cannot use Java, only C.


Does it make sense to implement OAuth for a 2 party system?

I'm under the impression that OAuth is for authentication between three parties. Does it make sense to implement OAuth in a context where there is just a client and server. We have a server, and a client (HTML/javascript). Currently we authenticate via the normal "post credentials to server, get a cookie, use cookie to authenticate all subsequent requests" method. Will implementing OAuth be a benefit in this situation?


Do you consider mainframe as part of large application deployments?

When you are setting up your system landscape for large and/or multiple application deployments, do you consider mainframe? If not, why not? If so, what factors are you considering. If you take a _real_ TCO look at large ERP and/or consolidated application landscapes, mainframe is actually quite cost-effective. My own consultations have included recommendations for scale-up/mainframe/mid- size systems on some specific needs. Honestly, I've never had a customer take said recommendation, rather defaulting to countless scale-out VMs on Intel boxen (in non-trivial cost) and yet still to this day have system management and performance issues. Curious your take on this. We need to remember that the virtual machines we manage (and apparently love in IT departments) today have been done for decades on mainframe. Most mid-size and mainframe shops have small fractions of support persons managing larger and more complex applications. Your thoughts appreciated.


Are NoSQL databases going to take the place of relational databases? Is SQL going away?

Does anyone have experience with NoSQL databases (CouchDB, MongoDB, Google's BigTable, Dynamo, Cassandra...)? What was it like? Was it actual production/on the job experience? What will happen to the relational databases in 5 years? 10 years?


When is it appropriate to use Microsoft's Enterprise Library (EntLib)?

I'm not exactly sure when to use Enterprise Library, and when not to... and that is making me not learn it at all. I feel that I have enough of a reason to **start learning** then perhaps one day I'll **use** it. Are there times when I should use EntLib? When shouldn't I use it?


Have objects delivered in terms of code reuse?

I have often heard it said that objects have not delivered in terms of code reuse. Do you agree? If you believe that they haven't, why not?


How to choose the right next step in learning programming and mastering new technologies? I have experience with WinForms applications in C# .NET. Next what I see as a good area of expanding the knowledge is ASP.NET. Language I already know, C #, so I think there is now more a matter of mastering new technologies. Also I have interest in WPF. Perhaps the best is to work on ASP.NET and WPF at the same time. Sometimes the problem is when we do not have motivation, but also known to become a problem when we want to much :) How to choose a new technology for mastering and not lose sense of reality and practicality?


Switch interface implementation using configuration

We want to allow the same core service to be either fully implemented or, as other option, to be a proxy toward a client legacy system (via a WSDL for example). In that way, we have both implementation (proxy & full) and we switch which one to use in the configuration of the app. So in a nutshell, Some desired features:   * Two different implementation (proxy, full) instead of one implementation with a switch inside   * Switch implementation using configuration: dependency injection? reflection?   * Nice-to-have: the packaged delivered to the client doesn’t have to change depending on the choice between proxy or full   * Nice-to-have: Client can develop their custom implementation of the Core Interface and configure the applciation to use that one With this background, the question is: What alternatives we have to choose one implementation or other of an interface just changing configuration? Thanks


how to create a data model for the following problem

How to tackle 2-D and 3-D space in data ? lets say you are working on a power grid problem. You need to represent Towers; transmission lines; transformers and every thing else in a 2-D space. How would you design a Data Model for this 2-D space ? I can use a               class tower  {     int x_cor;     int y_cor;     string power_properties     }      But how to represent the ... say map of the power grid itself ? is there some standard solution to this ? some logical template people follow here ? i want to be able to slice this map by shape or area etc; i should be able to compose small maps to make a large one .. So what is the solution here ?? By the way i am not working on a power-grid project (LOL) so please keep answers generic .. P.S. non-noobs please help me make the question better.


Possible problems in a team of programmers

I am a "one man team" ASP.NET C#, SQL, HTML, JQuery programmer that wants to split workload with two other guys. Since I never actually thought of possible issue in a team of programmer, there are actually quite a few that came to my mind. delegating tasks (who works on what which is also very much related to security). I found Team Foundation Service could be helpful with this problem and started reading about it. Are there any alternatives? security (do now want for original code to be reused outside the project) How to prevent programmers from having access to all parts of code, and how to prevent them from using that code outside of project? Is trust or contract the only way?


Are there any technical obstacles for implementing `function* ()` syntax

In Python we have `yield` which is very similar to that one which is proposed in ES6 (in fact, pythonic co-routines were the main source of inspiration for implementing co-routines in I wonder what are the reasons for choosing a separate `function* ()` syntax for generators compared to just defining "regular" functions with yeilds - just like in python by the way? I'm talking strictly of technical issues and peculiarities. Why it had been decided that a separate form will be more appropriate?


How do you demo software with No UI in the Sprint Review?

We are doing agile software development, basically following Scrum. We are trying to do sprint reviews but finding it difficult. Our software is doing a lot of data processing and the stories often are about changing various rules around this. What are some options for demoing the changes that occurred in the sprint when there isn't a UI or visible workflow change, but instead the change is a subtle business rule on a processing job that can take 10s of minutes or even a couple of hours?


How to properly shield a Product Owner from outside?

**Update:** We are a very small team (3 people) and thus I (Scrum Master) and the Product Owner are also developers doing some coding. We are aware of this situation and we are actively trying to recruit some new talents. But it's hard! * * * Meanwhile... we need to adapt... so my question: The Product Owner complains about having too much outside noise (mainly stakeholders feature requests), and he can't focus on the sprint realisation. We agree that we should try to educate people on our process implications (sprint durations and product backlog), to reduce the noise. But as a Scrum Master, how am I supposed to shield a PO from outside? Isn't he supposed to be in contact with the management and business? Also, if people outside don't want to waste too much time learning agile, what is the best way to educate them?


How to cope with the problem of (compiling) a large code base?

Although I can code, I don't yet have any experience with working on large projects. What I did so far was either coding small programs that get compiled in matter of seconds (various c/c++ exercises like algorithms, programming principles, ideas, paradigms, or just trying out api's...) or working on some smaller projects that were made in a scripting language(s) (python, php, js) where no compiling is needed. The thing is, when coding in a scripting language, whenever I want to try if something works - I just run the script and see what happens. If things don't work, I can simply change the code and try it out again by running the script again and keep on doing that until I get the result that I wanted.. My point is that you don't have to wait for anything to compile and because of that it is quite easy to take a big code base, modify it, add something to it, or simply play with it - you can see the changes instantly. As an example I will take Wordpress. It is quite easy to try and figure it out how to create a plugin for it. First you start by creating a simple "Hello World" plugin, then you make a simple interface for admin panel to familiarize yourself with API, then you build it up and make something more complex, in the mean time changing how it looks a couple of times.. The idea of having to recompile something as big as WP over and over again, after each minor change to try "if it works" and "how it work/feels" just seems inefficient, slow and wrong. Now, how could I do that with a project that is written in a compiled language? I would like to contribute to some open-source projects and this question keeps bugging me. The situation probably differs from project to project where some of them that were pre thought wisely will be "modular" in some way while others will just be one big blob that needs to be recompiled again and again. I would like to know more about how this is done properly. What are some common practices, approaches and project designs (patterns?) to cope with this? How is this "modularity" called in programmers world and what should I google for to learn more about this? Is it often that projects grow out of their first thought proportions which becomes troublesome after a while? Is there any way to avoid **long compiling** of not-so-well designed projects? A way to somehow modularize them (maybe excluding non-vital parts of program while developing (any other ideas?))? Thanks.


How can a large, Fortran-based number crunching codebase be modernized?

A friend in academia asked me for advice (I'm a C# business application developer). He has a legacy codebase which he wrote in Fortran in the medical imaging field. It does a huge amount of number crunching using vectors. He uses a cluster (30ish cores) and has now gone towards a single workstation with 500ish GPUS in it. However where to go next with the codebase so:   * Other people can maintain it over next 10 year cycle   * Get faster at tweaking the software   * Can run on different infrastructures without recompiles After some research from me (this is a super interesting area) some options are:   * Use Python and CUDA from Nvidia   * Rewrite in a functional language. For example, F# or Haskell   * Go cloud based and use something like Hadoop and Java   * Learn C What has been your experience with this? What should my friend be looking at to modernize his codebase? UPDATE: Thanks @Mark and everyone who has answered. The reasons my friend is asking this question is that it's a perfect time in the projects lifecycle to do a review. Bringing research assistants up to speed in Fortran takes time (I like C#, and especially the tooling and can't imagine going back to older languages!!) I liked the suggestion of keeping the pure number crunching in Fortran, but wrapping it in something newer. Perhaps Python as that seems to be getting a stronghold in academia as a general-purpose programming language that is fairly easy to pick up. See _Medical Imaging_ and a guy who has written a Fortran wrapper for CUDA, _Can I legally publish my Fortran 90 wrappers to Nvidias' CUFFT library (from the CUDA SDK)?_.


Need advice on which route I should take for porting app from Android to iOS

I have developed this android application  and I am looking to port it to iOS. My questions are: 1) I am planning to finance the iOS development with the money earn't from the android sales which is about $200 at the moment. Would it be reasonable to get the project done for this amount even if it is outsourced to elance or odesk etc? 2) I have heard the code quality for outsourced iOS projects to be bad, I dont want any memory leaks and crashes because of overflows etc. 3) I currently dont have a full time job so I can technically do the project myself, however I dont have a apple pc or iPhone (dont really want to get them either). I know C pretty well but I haven't really released a major C project that must be 100% stable. How many hours to learn iOs and do the port? And would it be worth my time taking into consideration that if I do enjoy it I may get into it fulltime. 4) What would the demand be like for someone that can do Android and iOS? Thanks


Data encryption/protection - where to find info about high-level best practices

I feel that no one in the group I work in, myself included, _really_ groks encryption and security, or the reasons behind making certain decisions. For example, we recently had a conversation regarding encryption of data that we handle for another group that we work with - the data ends up in a database that is on our secure corporate network (I work in a small group in a large software company, so the integrity of the corporate network is very high), along with everything else we handle. Of course, standard guidelines call for "encryption" of this data. Obviously, that could mean many things - IPSec/encrypted connections, encrypted fileshares, encryption implemented in the DB (whole-DB or column), encryption of the actual bits in the file, etc. - and some people in the group are under the impression that the only kind of encryption that really counts is directly encrypting the bits that are stored, the argument being that everything else is too easy to circumvent - "if the DB is encrypted, I could still log into it and see the data there; if the file share is encrypted, as long as I have permissions to the folder I can just grab the file; but if the bits are directly encrypted, I won't be able to read it". My instinct says that that statement is based on limited understanding: they can see themselves logging into SQL Server Management Studio to see the data, but since they wouldn't know how to take a stream or array of encrypted data and use a certificate that they probably have access to to decrypt it, it's probably safe. Are they right? Am I right? No one seems to really know, so decisions get based on the opinion of the loudest or highest-paid person. Anyway, that's just kind of an extended example of what I'm talking about. I feel like it's the blind leading the blind here, with decisions based on limited understanding, and it's frustrating. I'm no expert on the technical bits of encryption, but I know how to use standard libraries to encrypt streams and arrays and the like - where I really need more knowledge is about architecting data security and information on which I can base decisions like the above. Where can I read about this kind of stuff?


Why don't we use browser detection and platform-specific CSS?

Nowadays, the common phenomena is to develop a website for a browser and then corresponding apps for Android phones, iPhone, tablets and so on. Since all the platforms come with a browser, why aren't companies using CSS to accommodate them? Surely we can detect from the request which browser was used and from which platform the request came. Reading those values, why don't we just implement the corresponding CSS for different platforms. Like we do for IE, Chrome and Safari. This way we can use the platforms' browser capabilities and don't need to develop subsequent apps for a platform.


Why is the Repository pattern needed in NHibernate?

I am reading the official Your first NHibernate based application. While the tutorial is good and easy to follow, I am wondering why the Repository pattern is used. In the various `Add`, `Update`, `Remove` methods in the `ProductRepository` implementation, the code is nearly identical - they are all using transactions, and the difference is in the "meat" i.e. call `session.Save` int the `Add` method, `session.Delete` in the `remove` method. ( _The page lacks HTML anchors, but you can search the page for the relevant code like`public void Remove`, `public void Add`_) That code just "feels wrong". Why is the author using the Repository pattern - is it just for demonstration of using NHibernate or is that required or some other reason? Ps. My background is from Ruby on Rails using ActiveRecord so I'm trying to make sense of how NHibernate works/is used.


Best projects that illustrate the strengths of the languages they are implemented in?

I'm looking for a who's who list of projects(open source) that really illustrate the strength of the languages they are written in. Ideally the project should make use of some features of a given language that would otherwise be clunky or difficult to do in another language.


Scrum and Scrum Master on a global team

I work in a company that runs on a model of using one developer as tech lead (me), with an onshore co-ordinator/developer who co-ordinates the offshore team, and on the offshore team there's an off-shore co-ordinator. It sounds bizarre but it basically works. The rest of the developers are offshore. I happen to be on a project now that has an additional onshore developer. My question is, do you think I can use some agile methodologies here in a loose sense (we're a waterfall company, but maybe I could do scrum, sprints, planning poker, etc)? Also, do you think we could benefit from a scrum master? What if I didn't have the additional onshore developer (so basically I'd be one of two onshore developers then, and neither of us might be on the project full time)? What about me giving up the coding I do and becoming scrum master & tech lead? See my comment below for my duties now.


Do Flexibility and Inconsistency,Unsafety Overlap?

I was lately doing some research about different programming languages. I was interested particularly to learn unique features of popular programming languages and situations where these assets shine. I believe this can help me to decide what language to use depending upon the problem to solve. I found that many languages offering high level of flexibility ("can adapt to new, different, or changing requirements") are also inconsistent, for example in JavaScript (just an example, no offense to js people), arguments of a function get be manipulated either by naming them in the function declaration (classic approach):               function max(x,y)      Or by using the `arguments` variable:               function max() {         if (arguments[0] < arguments[1])             return arguments[1];         else             return arguments[0];     }          c = max(1,2);      The arguments variable is useful for many situations such as function overloading, however, it defeats the purpose of function prototyping (which is to give information about the function), and I saw many JavaScript samples where the argument variable is being used despite there is no need for it, which clearly makes the code harder to understand and debug. I know that this depends heavily on the users of the language, but usually, code written in a language offering high flexibility tends to be unsafe, harder to understand,optimize and to debug. Do flexibility and inconsistency overlap? How do languages designers make the choice? Edit: I'm not critiquing any particular language here, I'm rather focusing on the relation between Flexibility,Safety,Consistency of programming languages.


How to make a GPL license with more severe penalties?

I am considering open sourcing some software, but when I read the answers on this questions, it seems like the penalty of ignoring a GPL license is rather small, compared to the costs of the suing party to document that the other party has included GPL code in their proprietary code and the costs of suing. Therefore, I would like to know if there is a way to make a license or some kind of contract before source code is accessed, which is stricter than GPL. What I want to achieve is that a company including GPL code in their proprietary code have to GPL their whole code, and not just rewrite the GPL code. Is this possible?


What exactly is "Web API" in ASP.Net MVC4?

I know what a Web API is.   I've written API's in multiple languages (including in MVC3).   I'm also well practiced in ASP.Net.   I just discovered that MVC4 has "Web API" and without going through the video examples I can't find a good explanation of what exactly it IS.   From my past experience, Microsoft technologies (especially ASP.Net) have a tendency to take a simple concept and wrap it in a bunch of useless overhead that is meant to make everything "easier".   Can someone please explain to me what Web API in MVC4 is exactly? Why do I need it? Why can't I just write my own API?


What useful expressiveness will be impossible in a language where an expression is not a statement?

I am contemplating writing a programming language. Most grammars define expressions as being a kind of a statement. But really I cannot come up with a single example of any useful expression that would pass as a statement. See http://stackoverflow.com/questions/19132/expression-versus-statement for an easy definition of expression vs statement. EDIT: Why are so many grammars making the distinction between expr and stmt when as noted in the answers, it makes no sense.


Choosing a restrictive licence for open source work

If you were putting some work of yours online (say, a research project still in development or something alike) and **_it had to_** be made available to the public, but you wished that if someone uses it, he has to acknowledge the original author (i.e. you don't want anyone pushing your research as their own) what would be a good licence to use? In other words, you wish to protect your own work which, were it not for some rules, would never been actually made public.


Science degrees that are complementary to programming

I hope this wouldn't be closed especially since I think a lot of people can benefit from this question that are in similar positions to mine. I'm been programming for a long time (since I was about 13/14, now I'm 22) and now I'm in that stage in life when I'm thinking whether and what to study. Since I'm programming for a long time I'm pretty certain that I will not pursue a degree in Computer Science/Software Engineering because I think a lot of the material will be about things I already know. Even if it will benefit me, I think I will lose a lot of motivation because I will be bored in class and I will always think to myself that "I'm wasting time" or that "I'm not really gonna use the material that is taught in this class". Science really interests me, especially Physics, but Chemistry/Biology is also interesting to me. and it's also possible to study two together like a BSc in Physics and Chemistry or Chemistry and Biology, which are both offered at the university I want to go to. So the question is, what Science degree can benefit me the most in a career as a programmer? Are there fields that incorporate software engineering and Physics/Chemistry/Biology and that have a lot of demand? or are expected to have a lot of demand? Are there any specific careers that you know of that incorporate software engineering and Physics/Chemistry/Biology? This is not a question of whether to study or not, this is a question of "if I decide to do a Science Degree that isn't Computer Science/Software Engineering, but which will benefit me as a programmer or widen my range of opportunities, which one do you recommend?"