Do unit tests sometimes break encapsulation?

I very often hear the following: "If you want to test private methods, you'd better put that in another class and expose it." While sometimes that's the case and we have a hiding concept inside our class, other times you end up with classes that have the same attributes (or, worst, every attribute of one class become a argument on a method in the other class) and exposes functionality that is, in fact, implementation detail. Specially on TDD, when you **refactor** a class with public methods out of a previous tested class, that class is now part of your interface, but has no tests to it (since you refactored it, and is a implementation detail). Now, I may be not finding an obvious better answer, but if my answer is the "correct", that means that sometimes writting unit tests can break encapsulation, and divide the same responsibility into different classes. A simple example would be testing a setter method when a getter is not actually needed for anything in the real code. Please when aswering don't provide simple answers to specific cases I may have written. Rather, try to explain more of the generic case and theoretical approach. And this is neither language specific. Thanks in advance. **EDIT:** The answer given by Matthew Flynn was really insightful, but didn't quite answer the question. Altough he made the fair point that you either don't test private methods or extract them because they really are other concern and responsibility (or at least that was what I could understand from his answer), I think there are situations where unit testing private methods is useful. My primary example is when you have a class that has one responsibility but the output (or input) that it gives (takes) is just to complex. For example, a hashing function. There's no good way to break a hashing function apart and mantain cohesion and encapsulation. However, testing a hashing function can be really tough, since you would need to calculate by hand (you can't use code calculation to test code calculation!) the hashing, and test multiple cases where the hash changes. In that way (and this may be a question worth of its own topic) I think private method testing is the best way to handle it. Now, I'm not sure if I should ask another question, or ask it here, but are there any better way to test such complex output (input)? OBS: Please, if you think I should ask another question on that topic, leave a comment. :) **EDIT2:** I accepted a answer as my correct because it made me think and decide my course of action, altough it didn't answered my queston completely. But for those who face the same problem as I do (one cohesive class that will change together, but is still too hard to test by itsfelf), I'll tell what I did and why. I decided that the output of that class is simply too hard to a computer to test correctly, so I didn't test it. I could have used a framework to test it's private methods (which would be the best idea, I think), but I didn't want to get to that point. If you are wondering what it is that is cohesive and respects SRP, and still is too hard to a computer to test, I'll give some examples: heightmap generation, hashing functions, procedural music generation (you can test some units, but the highest level unit is simply too subjective).


Any Code Review tool with direct connection to CVS?

I've found many Code Review tools:   * Phabricator (by Facebook) - http://phabricator.org/   * Rietveld (by Google) - http://code.google.com/appengine/articles/rietveld.html   * GitHub - https://github.com/   * Crucible - http://www.atlassian.com/software/crucible/overview   * GitLab - http://gitlabhq.com/demo.html   * SmartBear - http://smartbear.com/products/software-development/code-review   * etc. But didn't found any, which would be directly connected with the versioning system. As I want the code review proccess to be required, so nobody can push any single line of unreviewed code to master, I need my versioning system to **deny all pushes of revisions which were not reviewed yet**. Is there any tool which does that? Or is there any easy way how to do that?


How to manage a winforms application installed in many PCs connected to a single sql database?

I have a winforms application that connects to a single sql server 2012 database and is executed in many PCs of a company. I'm having several problems with some transactions inside the application, deadlocks and timeouts so the refactor idea comes to my head. Actually the app is using DbConnection object (the app starts with Framework 2.0 and recently was updated to Framework 3.5 but the data access layer was not changed) to perform the sql calls to the database and in the Program.cs the connection is opened and until the user doesn't close the app the connection maintains opened. What are my options to refactor this app?   * Entity Framework? => With this I must to say that the SQL database has not Foreign Keys   * Refactor the Data Access Layer to use a more efficient connection? Maybe using TransactionScope?   * Is the always connected app efficient?


Designing a plug-in system

I'm working on a Java project and I would like to add a plug-in system. More precisely, I would like to let the user design his own module, pack it into a jar, leave it in a "plugins/" subfolder of my application and be done with it. I've managed to get a child classloader to instantiate objects of classes located in external jars, but now I'm facing a design dilemma: Say Joe makes a plug-in and he packs it in joeplugin.jar. I would really like Joe to have a class named "instantiation.Factory" and I would also like everyone to have this class with this exact location and name. (This factory class obviously implements a interface that I provide and through it I get what I want from the plug-in.) If Joe wouldn't be restricted in this way I would have to look into his entire jar for some class that implements my factory interface and I don't want to imagine how complicated things get. So my question is: should I enforce a strict naming convention for this single class? I have no idea how plug-in systems work.


Benefits of Java in education?

I hope this isn't too off-topic and/or opinion based. I'm looking for examples and reasons why Java is an acceptable language for education purposes. Here's why: I learned programming on my own in C at the age of about 15. In school we used Pascal (which I think is quite OK, especially in educational context). In University, Java was used and I was disgusted. Examples: Verbosity:               RenderingHints rh = new RenderingHints(          RenderingHints.KEY_ANTIALIASING,          RenderingHints.VALUE_ANTIALIAS_ON);     g2.setRenderingHints(rh);      * * * Listener classes instead of functions. * * * No overloading (resulting in ugly `.equals()` and `.get()` instead of `==` and `[]`). * * * When I was able to pick a programming language on my own again, I chose Python and everything "felt just right". Now the problem is that I'm going to become a teacher for computer science in german secondary schools (grade 5-13), where I will be forced to teach Java. So I'm looking for the _pretty parts_ of Java. What is especially easy/readable/... to implement in Java? Preferably in an educational context, but also from a professional programmer's point of view.


Why doesn't Haskell have a 'format' function for string interpolation?

I'm trying to use Shake and I stumbled upon the following problem: there's no easy and convenient way to interpolate a string. I know about `Text.Printf` — it's not what I'm looking for. The interpolation syntax I'm talking about is like this: (Make)               HEADERS_DIR := /some/path/to/dir          CFLAGS := "-g -I$(HEADERS_DIR) -O2"      (Python)               headers_dir = "/some/path/to/dir"          cflags = "-g -I{headers_dir} -O2".format(**locals())      And now compare this to possible Haskell's solution. Firstly:               $ cabal install interpolatedstring-perl6     $ ghci -XExtendedDefaultRules -XQuasiQuotes      And then:               > import Text.InterpolatedString.Perl6 (qq)     > let headers_dir = "/path/to/some/dir"     > [qq| -g -I$headers_dir -O2 |] :: String      While I think Make goes maybe a step too far in its eagerness to interpolate even when not asked, I wonder why Haskell doesn't have a `format` function like Python does. It could parse the supplied string and pull the value with same name as referenced in pattern:               let headers_dir = "/path/to/some/dir"     format "-g -I$headers_dir -O2"      Is there a specific reason why it's not implemented, or everyone is just happy with `Text.Printf`'s verbosity and/or lengthy setup of interpolation libraries? **Update** : A lot of people misinterpret the question as asking about general string formatting, with possibility of precision specification in case of integers, etc. The examples provided demonstrate one specific case of interpolation, which is just "substitute the result of `show a` at the place of name". It does allow for simpler syntax, and it does not use a variadic function per se.


Development of algorithmical concept for scheduling and allocation problem

I have to solve a problem in the field of _operations research_. I want to gather some general approaches to evaluate them to pick the most promising to design a problem-related program. * * * **Problem definition** Company ACME that sells customized collages and has a production that adheres to mass customization principles. **Production**   * A _desk_ **D** where the _collages_ are created (maybe there will be more desks in future, but not for now)   * A _collage_ **C** is composed of...   * Diverse _square pictures_ **P** We can consider the collage as created, when the last needed square picture is created.   * _Marker_ **M** of _color_ **T** and capacity **c_m** A _picture_ is drawn with one or more _marker(s)_ of same _color_. Each _picture_ consumes a certain amount of _marker capacity_. It is possible that a pictures can _consume_ more than one marker. Empty _markers_ can be refilled but that takes a fixed amount of time. The drawer is an android that works 24/7 (since androids have no human rights yet) and can hold _mutliple markers_ (there is a limit, we can assume 2 for now), if one _marker_ is empty, he can switch to the next and doesn't loose time because of refilling. Changing the _marker_ because another _color_ is needed, also takes time. The _markers_ are **not** at the android's desk, only the one he currently uses. They get there at the time they're scheduled. The problem now is to schedule the specific _square picture assignments_ , the according _marker assignments_ , _marker refills_ and _color switches_ so that every single step of the collage production is planned considering a high output rate (that includes the minimaziton of color switches). * * * **Question** I need help finding algorithms and ideas for solving the problem. Maybe there are some best practices or problem instances to map I haven't thought of. E. g. _TSP_ , where I'm not sure how to apply it in this special case. * * * **My Solutions/Ideas so far**   * Simulated Annealing The square Pictures assignments, marker assignments, etc. are consindered as events. Find a permutation of events that minimizes global cost function.   * Auction class algorithms Every square picture assignment gets a balance of money according to the return value of a per-assignment cost function. The assignments can _buy_ the needed resources in an auction house. Upon a valid buy, the resource and the assignment are scheduled.   * Map to _graph instance_ (Don't know exactly how to do that yet) and find path with minimum weight. * * * **Additional info** There is a meta tier with a superior **ERP** (Enterprise resource planning) system, that already does some rough planing. The task here is the detailed planing as a **MES** (Manufacturing Execution System) would do it. But I don't know the number of collages I have to plan in a given time frame. I just know that it is an ongoing problem, and that there is no need to use an online algorithm. The program I'll intend to develop gets called on demand to schedule the production for some days. I found a way to map the problem to simulated annealing and another approach following the auction class algorithms. I need help with evaluating these approaches, or even collecting new ideas, best practises to solve this problem, since I never dealt with a problem instance like this before. E. g. an answer like take a look at algorithm xyz would help me out, or first approaches to a graph mapping.


How to test software that burns CDs without wasting CDs?

I want to write an application that can be used to burn CDs (music). I know I should test it with real CDs anyway, but I don't want to do this every time I make a small change. But I do want to know and test if the right data will be burnt, so you don't get corrupted CDs. I am using a library which only exposes APIs to directly burn to a physical drive; it doesn't allow you to write to a disk image (which would be much easier to test). How could I test this without wasting CDs and time for every change/few changes I make?


Looking for a better Factory pattern (Java)

After doing a rough sketch of a high level object model, I am doing iterative TDD, and letting the other objects emerge as a refactoring of the code (as it increases in complexity). (That whole approach may be a discussion/argument for another day.) In any case, I am at the point where I am looking to refactor code blocks currently in an if-else blocks into separate objects. This is because there is another another value combination which creates new set of logical sub- branches. To be more specific, this is a trading system feature, where buy orders have different behavior than sell orders. Responses to the orders have a numeric indicator field which describes some event that occurred (e.g. fill, cancel). The combination of this numeric indicator field plus whether it is a buy or sell, require different processing buy the code. Creating a family of objects to separate the code for the unique handling each of the combinations of the 2 fields seems like a good choice at this point. The way I would normally do this, is to create some Factory object which when called with the 2 relevant parameters (indicator, buysell), would return the correct subclass of the object. Some times I do this pattern with a map, which allows to look up a live instance (or constructor to use via reflection), and sometimes I just hard code the cases in the Factory class. So - for some reason this feels like not good design (e.g. one object which knows all the subclasses of an interface or parent object), and a bit clumsy. Is there a better pattern for solving this kind of problem? And if this factory method approach makes sense, can anyone suggest a nicer design?


Design pattern for method to accept one of several static items in C#?

I want to illustrated my question by way of a (hopefully) representative example. Lets say I have a situation where I am developing a class library in C# to be used in some simulations. I want to define the planets (Earth, Mars, Saturn, etc.) and have each of them have some properties and methods that are common in interface (name, signature, etc.) but unique in implementation per-each. I.e. Earth.Mass is not equal to Mars.Mass. So far no big deal. I want to have some other classes/methods/algorithm that accept as an argument a planet and use its defined properties and method:               double MyApparentWeight(Planet someplanet, double MassInKG)     double DistanceFromInKM(Planet someplanet, Planet originplanet)      Planets could be used all over the place by someone using this library. All "Earth"s should be identical and all "Saturn"s should be identical. Obviously the "Earth"s are distinct from the "Saturn"s. I also want a user of the library to be able to easily create a new planet (e.g. Vulcan, Endor, Tralfamadore, Persephone, Rupert, etc.). It should be forced to supply the properties and methods of the existing ones and hence be useable by the MyApparentWeight and DistanceFromInKM methods. So the base level approach is that there is a Planet class and then the specific ones (Earth, Vulcan, etc.) simply inherit from that. In this case though a user needs to either create an instance of Earth and carry it around or create a new one every time it is needed. That could be unnecessarily clunky (especially in light of the expected users) and possibly a performance hit since some Planets could have initialization steps of reading date from files, etc. The next idea was the above but with a singleton paradigm. That's basically what I've done so far. This seems to be dictating internal implementation to any new Planets that are created (and again some what of a concern given the potential level of some users). This project is how I've been cutting my C#/.NET teeth. My initial naive approach was to try to do static classes with interfaces or inheritance. Obviously I learned quickly the folly of that path. At a high level that is the kind of paradigm I would have wanted though. Is there some other design pattern that I'm missing that could cover this type of situation? Appreciate any suggestions. # Updates I may not have made it clear that this `Planet` example was only meant to be illustrative structurally and not directly representative of the actual computations. Some people seemed to get a little wrapped up in the implementations of what data is being represented within them and other peripheral aspects. The suggestions of the individual planets (like Earth) merely being instances of the `Planet` class didn't catch my points about potentially significant different implementations for their internal mechanics supporting their methods and properties. I'm also at a loss as to how it helps with not wanting to manage carrying around those instances potentially anywhere you may want to use them or having to create new instances. Glenn's extension of Stephen's suggestion I think actually works the best in the context of what I need here. I can couple that with rsbarro's suggestion of having static properties for the built in `Planet` children. (Actually more like `interface IPlanet` implementers). That provides the easiest access for the users for the most commonly used items and offers a slight performance improvement of not having to retrieve from the dictionary by name each time. It still offers the ability for the users to dynamically add more types of Planets. I don't yet have the rep to up-vote all of the answers I mentioned above or I would. Thank you all for your suggestions and feedback.


What do you do if you find a rewrite is taking too long?

I know Joel says that rewrites are always bad, m'kay, but that is assuming the person who wrote the code in the first place had some idea what they were doing. I've got a medium sized (for a single developer anyway, ~18k LoC) C++ project, which I started when I did not truly know C++. Therefore, there are several things that are just... wrong. Wrong is the only way to describe it. It needs to be rewritten, plain and simple. However -- I've spent a long freaking time doing the rewrite -- bugs in the original aren't getting fixed. However, some of the bugs themselves are problems with the architecture of the original tool -- and some of that is what I need to fix would require touching almost every line of code anyway. On one hand, I feel fixing the bugs in the old program is going to be a massive wasted effort, because those bugs aren't even possible with the new design I've been working on. On the other hand, I've felt that I've neglected users of my original program because it's not been updated in so long. What should I do?


What are the worst things that inexperienced developers forget to think about?

As a young developer, I would find it useful to get some advice regarding things to think about in order to develop a high-quality application. In my college courses, most teachers emphasized input validation and some talked about security concerns, but no one covered the importance of certain other things, like logging for example. What are some mistakes that inexperienced developers tend to make which could lead to frustration for more experienced developers?


Make shareware program free in some countries

**Idea.** To make my shareware program free in less-developed countries. Or release a free edition for these countries. **Purpose.** More users, bug reports, extensions, active forum, etc. Anyway, 90% sales are in ~30 richest countries. Why not make it free in China, India, Russia... **Question.** What are possible problems? I can't find info on this topic. It seems that almost nobody does it (I know only Windows 7 Home Basic). **Algorithm.** How would you implement it? I know it's possible to detect country using IP. It's OK if would fail to detect in 20% cases. When country is detected, the user would get license key for free. Country detection and license key generation can be implemented in web server. EDIT: Country detection can be performed when user wants (clicks button 'Register for free'). Then program connects to my website, which detects country and generates a license key from user's hardware ID. Then the free key can be used on that PC like a purchased key, and no internet connection required. On other PC/hardware the user can simply repeat the procedure, as long as he/she is in one of these countries. EDIT: Country detection is easy and fast, i tested it with this php script+database. It worked with all IPs of my website visitors of this month. However some of them may actually live in other countries (see jwenting answer).


Do logged in users need to browse a site over https?

I've never thought it was necessary, but a client has requested that all webpages served to logged in users be delivered over HTTPS. Aside from the implementation standpoint, which I don't think I'm going to pursue is there any real reason for this request ? For clarity, the login / logout process, account settings, registration preferences and all user related scripts are served over https. but I can't see the point in my news articles, press releases, events etc... being served in this manner? Am I missing something ?


Has anyone used a Stub in production code?

I have a situation where some procedure returns an object (kind of like a DTO) with a certain interface:               interface ISomeInterface     {         string StringReadOnlyProperty { get; }         int IntReadWriteProperty { get; set; }     }      (In the real implementation, there are more properties). There are two different places where these objects are handled - one process that generates new instances, and another process that manipulates existing instances. Internally, these two implementations are very different. The "new" instance is just a stub, and the "existing" instance has lots of tracking logic. So I need to have this "Stub" implementation kicking around all the time. I was thinking about how nicely Rhino Mocks can stub up implementations of an interface without having to generate a concrete class. Has anyone ever used a "stubbing" mechanism like Rhino Mocks, but in their production code rather than in their unit tests? It just seems like a bad practice, because of the dependency to a testing framework.


Java stored procedures in Oracle, a good idea?

I'm considering using a Java stored procedure as a very small shim to allow UDP communication from a PL/SQL package. Oracle does not provide a UTL_UDP to match its UTL_TCP. There is a 3rd party XUTL_UDP that uses Java, but it's closed source (meaning I can't see how it's implemented, not that I don't want to use closed source). An important distinction between PL/SQL and Java stored procedures with regards to networking: PL/SQL sockets are closed when dbms_session.reset_package is called, but Java sockets are not. So if you want to keep a socket open to avoid the tear-down/reconnect costs, you can't do it in sessions that are using reset_package (like mod_plsql or mod_owa HTTP requests). I haven't used Java stored procedures in a production capacity in Oracle before. This is a very large, heavily-used database, and this particular shim would be heavily used as well (it serves as a UDP bridge between a PL/SQL RFC 5424 syslog client and the local rsyslog daemon). Am I opening myself up for woe and horror, or are Java stored procedures stable and robust enough for usage in 10g? I'm wondering about issues with the embedded JVM, the jit, garbage collection, or other things that might impact a heavily used database.


Is there a standard for when you include libraries or not?

I often come across a class which has a single reference to another library and was wondering if its better to include the library or to reference the object by it's full name. Is one better then the other? Is one more of a standard then another? For example using System.Windows.Messagebox: Option A:               using System.Windows;          public class MyClass     {         SomeMethod()         {             MessageBox.Show("Something");         }     }      Option B:               public class MyClass     {         SomeMethod()         {             System.Windows.MessageBox.Show("Something");         }     }      If B, how many references do you need before you decide to add the entire library?


What are my options? - Separating out the UI

I'm working on a project where the everything is driven from the a .dll on the server. The UI and the business rules are all on this .dll This makes it pretty difficult to debug. My question is, I would like to present alternatives to allowing the users to the ability to still create customized screens without the UI and the rules being so tightly intertwined. Can anyone offer suggestions or references to ways of splitting out the UI but still allowing ultimate customization abilities? Let me know if I need to add further information.


Compute if a function is pure

As per Wikipedia: > In computer programming, a function may be described as pure if both these > statements about the function hold: The function always evaluates the same > result value given the same argument value(s). The function result value > cannot depend on any hidden information or state that may change as program > execution proceeds or between different executions of the program, nor can > it depend on any external input from I/O devices. Evaluation of the result > does not cause any semantically observable side effect or output, such as > mutation of mutable objects or output to I/O devices. I am wondering if it is possible to write a function that compute if a function is pure or not. Example code in Javascript:               function sum(a,b) {         return a+b;     }          function say(x){         console.log(x);     }          isPure(sum) // True     isPure(say) // False


Design pattern for syncing data in android

I have been seeing two implementations for syncing data between the server and the client on majority of the apps. This assumes no GCM is set up:-   1. Running an intent service periodically which downloads the data from the network and stores in the database.   2. Implementing a Sync Adapter which runs periodically. Which of the above would you recommend to have in your app and why?


Is it time to deprecate synchronized, wait and notify?

Is there a single scenario (other than compatibility with ancient JVMs) where using `synchronized` is preferable to using a `Lock`? Can anyone justify using `wait` or `notify` over the newer systems? Is there any algorithm that **must** use one of them in its implementation? I see a previous questions that touched on this matter but I would like to take this a little further and actually `deprecate` them. There are far too many traps and pitfalls and caveats with them that have been ironed out with the new facilities. I just feel it may soon be time to mark them obsolete.


Would a "downcast if block" be a reasonable language feature?

Consider the following "if cast":               class A     { public void f1() { ... } }     class B : A { public void f2() { ... } }          A a = foo(); // might return A or B          if ( a is B ) {         //  Inside block, implicitly "redeclare" a as type B         //  It's B, go for it         a.f2();         //  Wouldn't compile.         a = new A();     }      We don't enter the block unless `a` is a `B`, therefore within the block, the compiler treats `a` exactly as if it had been declared as type `B`. You could assign null to it in the block if it's a reference type, but it would be a compile-time error to assign `new A()` to it, for example (thanks @ThomasEding for bringing up that question). Anything that could break that assumption that `a` is `B`, could just as easily break the following legal C# as well:               if ( a is B ) {         B b = a as B;              b.f2();     }      The former looks to me like syntactic sugar for the latter. Even if this feature makes sense, I'm sure Anders Hjelberg's lads have more useful features to implement. I'm just wondering if it's a worse idea than I think it is. **UPDATE** A serious objection would be that the feature as described adds semantics without adding syntax: From one version of the language to the next, the meaning of the above block would change significantly. It would be more tolerable with a new keyword. But then you'd be adding a new keyword.


Custom .NET apps and clustering

So for a clustered environment - how would this work with your apps? what about your own custom .NET apps? Would there be a special way to develop them? I know that you can say create a simple Hello world app, and cluster that but they wouldnt be something you could see interms of the UI or anything, so they would effectively need to be developed as a Windows Service perhaps or even as a standard Console app which runs and not wait for user input but you wouldnt see any output from it (unless you redirect output to somewhere else) What im getting at here is... for those who have experience or developed a cluster application in .NET, how did you do it and what are the things to be aware of? For example we have the cloud service - fundamentally its built on clustering - if there is an outage, another node takes place and service is resumed as normal but we dont really see much of that downtime.


"state" or "status"? When should a variable name contain the word "state", and when should a variable name instead contain the word "status"?

Reading code and discussions pertaining to code, I often see the words "state" and "status" used interchangeably, but the following tendencies seem to exist:   * When a variable holds a value intended to indicate that something is in a certain state, the name of that variable more often than not contains the word "state", or an abbreviation thereof.   * However, when the return value of a function serves to indicate some such state, we tend to call that value a "status code"; and when that value is stored in a variable, this variable is commonly named "status" or something similar. In isolation that's all fine I guess, but when the aforementioned variables are actually one and the same, a choice needs to be made involving the perverted intricacies of English language (or human language in general). What is the prevailing coding-standard or convention when it comes to disambiguating between the two? Or should one of those two always be avoided? This english.stackexchange question is also relevant, I suppose.


Dominant team members in a Scrum team

What would you do in a situation where a team member tries to take responsibilities are not initially assigned to him but to the Scrum Master?


Advise on loose coupling between user controls

I have 5 user controls on the page and each control implements it's own interface that contains properties and events. In order to enable communication between user controls, I am creating a property of target user control inside other user control. Through this property, it's state can be altered and be able to register its events. Below is the pseudo code of results user control. It subscribes to OnSearch event of Search user control.               public interface IResults     {          //other fields         ISearch SearchControl { get;}     }          public partial class Results : IResults     {      //other fields           public ISearch SearchControl      {              get{         this.Page.Parent.FindControl("UCSearch") as ISearch;}      }           protected override void Page_Load(object sender, EventArgs e)      {         this.SearchControl.OnSearch += new EventHandler(testMethod);      }     }      Is it ok to have the reference properties inside user controls to subscribe to the events and manipulating the state. Does it create any maintenance problem in future. Does FindControl and type casting degrade the performance of the application.


Why is verbosity bad for a programming language?

I have seen many people around complaining about verbosity in programming languages. I find that, within some bounds, the more verbose a programming language is, the better it is to understand. I think that verbosity also reinforces writing clearer APIs for that particular language. The only disadvantage I can think of is that it makes you type more, but I mean, most people use IDEs that do all that work for you. so, What are possible downsides to a verbose programming language?


Does parallel mergesort run differently on mesh vs linear array of processors?

I'm currently taking course on introduction to algorithm and I came across the parallel mergesort algorithm. My question is: Is there any differences in the algorithm plan if it runs on a 2d mesh instead of infinite linear proccessors ? Thank you,


Can Objective C categories serve the same purpose as Traits do in Scala?

The statement of the question seems little abstract to me, so please read the details below. Since the time when C++ was the first choice Object Oriented Language for almost anything, we had a big problem of Multiple inheritance in C++ when two different implementations of same function declared or defined in a (abstract or concrete)parent class of the two, come to a common child class and create ambiguity, popularly known as the Diamond problem. C++ gave a solution : the "virtual" keyword, to be used while specifying the parent class(es) so that only one copy goes to the final child class being decided at runtime instead of compile time based on certain rules. Java tried to solve this by providing single inheritance and avoiding multiple inheritance completely. But then it lacked a feature where a class behaviour could be influenced by a bit and that may change in future or more behaviour may be added to it and we needed a way to encapsulate behaviour, then came the construct "interface" which had nothing but method declarations which each implementing class had to implement in their own way. Protocols in Objective C are more or less the same thing. However this approach has a major drawback, and this is where my question comes into picture. The drawback is, if a class has many subclasses implementing the same interface in the same way. The same code has to be written everywhere in each class. If it was all the classes, then the implementation could have been there in the parent class which gives the implementation. At max what can be done is to introduce a class with the implementation of the common method in between the current parent class and make all those classes inherit from it. But this can lead to lot of bugs if not done properly in a complex project. Scala provides Traits which not only serve as interfaces but can add full blown implementations for few of them that can be mixed with some classes that require it and removed when not. I haven't seen the syntax but I have heard that Ruby solves the same problem using something called as mixins. In case of Objective C, we have protocols but they have the same limitations as Java interfaces. So my question is, If I create a category of a class and import it in any subclass of that class, Will the subclass get all those implementation methods? Also if I remove it, will it be synonymous to removing the trait inclusion declaration for a class? I might be wrong in any of my assumptions above, I am newbie when it comes to OOP design (and just got interested in FP). I would also appreciate any better solutions than this one.


Going through The C Programming Language K&R in Visual Studio

From what I have read, K&R seems to be a good place to start learning programming in general, and C programming specifically. However, I've just started the first chapter and I have a few questions. They may be extremely simple, and I apologize if that's the case (I am new, after all) -- but your helping me answer them would be very appreciated. 1) I understand the book is written to describe C languages in general. Does this mean the examples they give are just rough outlines, and that for me to attempt them myself I have to "translate" the general outline given into C++ or C# or whatever? For example, the textbook gives this program:               #include <stdio.h>      main()      {      printf("hello, world\n");      }      But I've found a program to print "Hello, world" in C#, for example is:               // A Hello World! program in C#.      using System;     namespace HelloWorld     {         class Hello          {             static void Main()              {                 Console.WriteLine("Hello World!");                      // Keep the console window open in debug mode.                 Console.WriteLine("Press any key to exit.");                 Console.ReadKey();             }         }     }      And the program in C++ looks different from both the above... So my question is: does the book expect me to be able to translate the first program (or outline, whatever it is) to a C# or C++ program -- I am using Visual Studio -- to be able to practice myself? 2) If the book does expect me to do this, do you all have any tips on how I can go about translating general C code to C# or C++. 3) This may be opinion, but which should I base my learning on (and practice coding in) -- C# or C++?


Credibility of Windows azure architect program from Sundblad & Sundblad

I am planning to attend the Windows Azure Architect Program from S&S. http://www.windowsazurearchitect.com/ Although the website says it is a Microsoft Training Program, not sure how much credibility & recognition it has. If someone attended the program, please share feedback about the program as well.


Is there any example or resource explaining/showing code from High-level to Low-level to deep down Machine code?

I have been searching for an example over the internet that shows any operation like saving a file or drawing anything in UI or any other sort that shows the implementation from High-leve language code to Low-level code to deep down machine level code. The basic idea is to explain the computer working in a nutshell. Like, in high-level laguage we write `int c= int a + int b` which is compiled into low- level code `IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: add` and then to machine level code. Any example or code flowchart from high-leve language to deep down machine code will be helpful.


Can memristors change programming paradigms? In what way?

Think about persistent storage that can preserve pointers: among other things there is no need to serialize/deserialize data. For example, you typically build a tree structure and then serialize it into XML so that it can be stored permanently on disk. Now there is no need for that: the structure in memory can be left there as is, possibly given a name, so that it can be used by other programs. Thus the concepts of loading/saving may be transformed into something else, if not eliminated altogether. File systems can become something entirely different: e.g. just memory with symbolic labels. Serialization will still be used in network communication of course. Besides, considering process isolation, memory protection etc, the scenario above may be a bit more complicated than that. One thing is clear though: large persistent addressable storage can at least save a lot of time, and at most cause paradigm shifts in programming. It would be interesting to hear your insights on this.


What's the best way to deal with large compressed files over FTP?

In my application, I'm getting product information files from an FTP server. They are text files that have been ZIP-compressed. At first, I thought uncompressed the file on the server then reading the text over the web would work, but the uncompressed files are ~900 MB, making it slow and inefficient while causing out-of-memory exceptions. How should I handle this type of problem? Should I download the compressed files, uncompress and process them locally, then re-upload them? Or is there another, more efficient way to do this?


C#: Explicitly defining variable data types vs. using the keyword 'var'?

In C#, am I encouraged to use the all-purpose var keyword for every variable declaration? If yes, do I have to mention those special characters for literal values within the variable declaration like the M for decimal in the following statement:               var myDecimal = 14.5M;      If it makes a difference, I'm trying to do some web development with C#. Thanks for sharing.


Standard way of allowing general XML data

I'm writing a data gathering and reporting application that takes XML files as input, which will then be read, processed, and stored in a strongly-typed database. For example, an XML file for a "Job" might look like this:               <Data type="Job">         <ID>12345</ID>         <JobName>MyJob</JobName>         <StartDate>04/07/2012 10:45:00 AM</StartDate>         <Files>             <File name="a.jpeg" path="images\" />             <File name="b.mp3" path="music\mp3\" />         </Files>     </Data>      I'd like to use a schema to have a standard format for these input files (depending on what type of data is being used, for example "Job", "User", "View"), but I'd also like to not fail validation if there is extra data provided. For example, perhaps a Job has additional properties such as "IsAutomated", "Requester", "EndDate", and so on. I don't particularly care about these extra properties. If they are included in the XML, I'll simply ignore them when I'm processing the XML file, and I'd like validation to do the same, without having to include in the schema every single possible property that a customer might provide me with. Is there a standard way of providing such a schema, or of allowing such a general XML file that can still be validated without resorting to something as naïve (and potentially difficult to deal with) as the below?               <Data type="Job">         <Data name="ID">12345</Data>         . . .         <Data name="Files">             <Data name="File">                 <Data name="Filename">a.jpeg</Data>                 <Data name="path">images</Data>             . . .         </Data>     </Data>


How to choose the most suitable technologies for your project?

While architecting the system, often you have to choose the appropriate technologies to be used for every module. What are the different parameters to be considered while choosing the technologies/frameworks? How those parameters can affect the project quality, schedule, expense? Can anybody please explain in detail.


Building a complete program?

Reading books, watching videos, and reviewing tutorials is all very easy. Taking notes and actually learning the material may be slightly harder, but even then, anyone with a decent brain and a fair amount of interest, it's easy enough (not to mention, fun). The thing is, it doesn't really prepare you to write a full program or website. Let's say you're those teens (only in highschool, no true (college level) computer science or programming courses, and no real world experience), and you come out with Groupon. Or even Mark Zuckerburg, sure he was a genius, and he was a very capable programmer... but how? How do you recommend that people who are not necessarily new to programming, but new to programming real applications and real programmers go about developing it? What is the "development process" - especially for single programmers (or maybe 2-3 teens)? Also, as far as web development goes, what is the process? Was something like Facebook or Groupon written with a framework (like CodeIgniter or Zend for PHP)? Or do they develop their own frameworks? I'm not asking how to come up with a great idea, but how to implement great ideas in an effective way? Does anyone have advice? I've read a couple of books on both C and C++ (primarily the C Programming Language and the C++ Programming Language) and taken AP Computer Science (as well as read a few additional books on Java and OOP). I also have read a few tutorials on PHP (and CodeIgniter) and Python. But I'm still in highschool, and I'm technically not even old enough to work at an internship for a few more months.


How to organize code review process

I'm looking for a light-weight code review process. A couple of requirements, the reviewer must be able to do the review alone at the time of his/her choosing (not tied to check-ins), the reviewer must be able to easily find the target code, the review has to leave some document showing what was reviewed. I know there are tools available for code review but I work in a very ridig environment and introducing new tools is not an option. One idea I've been thinking about is to create a new Visual Studio Task List token called REVIEW, and use it to mark the code that needs reviewing. Something like,               // REVIEW doe_john: New method, not sure about the exception.      Then we would add a Review workitem in TFS (we're using the CMM template). Another possibility, which I would actually prefer, would be to have developers create a TFS Review workitem and add links to code to it, but I don't know if this is possible. Obviously you can add a link to a file, but I'd like to have a link to a particular method. PS. Posted originally to StackOverflow.


What is the common approach to component template databases?

**My Project:** I have employees who are required to go through a checklist when they encounter a duck, a cat, and a human. In our business, we have a set number of ducks, cats, and humans that come in and out of our doors. When they come in, we have to check that all of these features are present. **The features:** ![example](http://i.stack.imgur.com/rYyiV.png) **Here is our current database design:** ![enter image description here](http://i.stack.imgur.com/v4GP5.png) **Current Approach:**   1. When an animal enters our building, we get their ID.    2. Their ID gives us their animal record.   3. We create a new "check_in" record for the animal   4. Under the check_in record, we use the template given by the animal_type->feature_type relationship      * For example: Sam the duck will have a new check_in created with separate feathers, wings, beak, feet, and eyes check_in_feature entries.   5. We go through the process and set feature_is_present to true or false for each of the features   6. When done, we check them out and the check_in entry is complete **My Question:** In practice, this relational schema is very hard to work with. We've used it for years and are constantly slowed down when looking up information because of the weird joins this design tends to require. I have no doubt that this is a known problem with a more elegant solution than using this naive approach. Anyone know a better way to structure this, or better approach that will be easier and more efficient to work with? EDIT: Just realized there are artifacts from our actual system in the navigation properties sections, just ignore those. I don't want to recreate the images if I can avoid it


Which books are good resources for designing APIs

I am looking for a book on how to design a web-service API. I'm constrained to using RPC-style Web services. In particular, I'm looking for guidance on   * [balancing...] **granular** _vs_ **course services**   * **required parameters** _vs_ **optional parameters**   * **small chatty services** _vs_ **services with large payloads** I'm also looking to address strategies for making reference data and caching on the consumer side. Even things like how to establish a rational naming convention are helpful. Which books are good resources for designing a web API that addresses these questions?


Agile software development: How do you react *financially* to changing user requirements?

There's one thing I've always wondered when reading about all this "agile development" stuff here on SE and other sites: In "traditional" software engineering, you   1. collect the user's requirements,   2. write a specification based on these requirements,   3. give it to the customer and bill him for the work done so far,   4. do a (rough) technical design, so that you can estimate the cost of implementation,   5. give the user a price quote for the implementation,   6. wait for the customer to sign the specification and accept the offer,   7. design, implement, test,   8. bill. If, during the process, the requirements change, you send an offer (with a price) for the desired changes (or do it for free if the change is small, you like the customer and the customer doesn't do it too often). So, how does this work (financially) in an agile project, where frequent requirement changes are a part of the process?   * Do you write an offer for every design change? (Wouldn't this be quite a mess?)   * Or do you negotiate a fixed price and _hope_ that the customer does not change the requirements too often? (Could be risky, I know customers who would use this opportunity to request new features for years before accepting that the project is completed.)   * Or do you just bill the customer for the total time required? (Could be risky for the customer, who does not know the cost in advance.)


Object construction design

I recently started to use c# to interface with a database, and there was one part of the process that appeared odd to me. When creating a SqlCommand, the method I was lead to took the form:               SqlCommand myCommand = new SqlCommand("Command String", myConnection);      Coming from a Java background, I was expecting something more similar to               SqlCommand myCommand = myConnection.createCommand("Command String");      I am asking, in terms of design, what is the difference between the two? The phrase "single responsibility" has been used to suggest that a connection should not be responsible for creating SqlCommands, but I would also say that, in my mind, the difference between the two is partly a mental one of the difference between a connection executing a command and a command acting on a connection, the latter of which seems less like what I have been lead to believe OOP should be. There is also a part of me wondering if the two should be completely separate, and should only come together in some sort of `connection.execute(command)` method. Can anyone help clear up these differences? Are any of these methods "more correct" than the others from an OO point of view? (P.S. the fact that c# is used is completely irrelevant. It just highlighted to me that different approaches were used)


OO Software Architecture - base class that everything inherits from. Bad/good idea?

I am reviewing a proposed OO software architecture that looks like this:   * `Base`     * `Foo`       * `Something`     * `Bar`       * `SomethingElse` Where `Base` is a `static` class. My immediate thought was that every object in any class will inherit all the methods in `Base` which would create a _large_ object. Could this cause problems for a large system? The whole architecture is hierarchical.. the 'tree' is much bigger than this really. Does this sort of architecture have a name (hierarchical?!). What are the known pros and cons?


How to discriminate commented code and documentation comments

After using version control tools, it is no longer necessary to comment out old code. However, some team members still comment out old code. Therefore, I want to clean them up. I want to mark commented lines which are really comments / documentation, so that every time I do not need to re-read all commented regions. The unmarked lines left are new commented code. How do I achieve this? Any existing tools or need to write on my own? Similar concept: in git, we have 'partial commit' to select some lines to commit. However, the lines marked in 'partial commit' is valid once only.


Path to learning compiler design

I'm not sure if this is an acceptable question, but compiler-os-design-where- to-start was, so I figured that I'd take a shot at it. I have taken no formal Computer Science classes. I have programmed in Python and attempted C# without success. My technical vocabulary is expansive, yet scattered over a very wide range of computer science topics. I have a very long way to go before I can get to a level where I could reasonably read a book about compiler design/theory. **I am asking what steps I need to take before attempting compiler design.** I have some examples here already:   * Computer architecture   * Binary   * How booting/kernels/OSes work   * Imperative vs. Comparative language design   * "Grammars" At least these are some examples of what I've seen. Edit: I can't for the life of me see how this problem is unclear. I quite clearly bolded what I was asking. I was expecting it to be marked as biased, vague/broad, or too generalized, but certainly not unclear. Don't be afraid to say it's unconstructive (just make sure whatever it is classified under is accurate).


Real world implementation of functional programming?

I am trying to acquaint myself with different types of languages to understand the areas in which each one of them is extremely good at. So far, I have dabbled into C - a procedural language, C++ & java - static typed Object Oriented languages and groovy - a dynamic typed Object Oriented language. Every programming language has probably been started to answer a need. And I presume every language is extremely good at at least one thing because of which it becomes a standard in a specific area or field. Like C, C++ have become standard in areas like browser or game development. Python in the Linux world for its easy scripting ability, Java in the enterprise world, etc. Now I am interested to learn a functional programming language like Clojure or Lisp. So, where are functional programming languages used in real world scenarios? I don't think that one would use Clojure or Lisp for developing applications or UIs. So on what kind of projects should I indulge into after going through the basic tutorials and learning resources to get a brief understanding about the implementation of functional programming? And do you strongly recommend on One language in specific, like say clojure?


Is MVC now the only way to write PHP?

Hey... its XMAS Eve and something is bugging me... yes, I have work on my mind even when I am on holiday. The vast amount of frameworks available for PHP now use MVC. Even ASP.net has its own MVC module. I can see the attraction of MVC, I really can and I use it frequently. The only downside that I can see is that you have to fire up the whole system to execute a page request. Depending on your task this can be a little wasteful. So the question. In a professional environment is this the only way to use PHP nowadays or are their other design methods which have alternative benefits?


Avoiding null in a controller

I'm trying to work through how to write this code.               def get(params):         """ Fetch a user's details, or 404 """         user = User.fetch_by_id(params['id'])         if not user:             abort(404)         # Render some template for the user...      What's the best way to handle the case where the lookup fails? One principle says you should avoid returning null values from functions. These lead to mistakes and AttributeErrors etc. later on in the file. Another idea is to have `fetch_by_id` raise a ValueError or similar if no user exists with that id. However there's a general principle that you shouldn't use exceptions for control flow, either, which doesn't help much. What could be done better in this case?


DR-DOS, Plan, BSD, Sun Solaris, HP/UX, OpenServer.....and so on. Why high-tech OSs (like UNIX family) are mostly command based (rather than GUI based)?


For ASP.NET Programmers: Does the executable 'dcpromo' have any significance?

`Dcpromo.exe` is famous among MCSEs for being they only way to create a Windows Domain Controller (in other words an Active Directory Domain) ... which in turn is often used by the ASP.NET Membership system. I'm trying to determine if I should put content on "www.dcpromo.com" geared for developers or more towards sysadmins. To me, a logical extension of this "domain controller on the internet" is to use WIF for the ASP.NET Membership system. We'd then have a website that will serve the developer's interests in the SSO, SAML, user managment and identity areas we all struggle with. So my question is: **Q:** Do programmers see a connection between the utility `dcpromo.exe` and ASP.NET Membership? If so does it make sense to have a purpose of http://www.dcpromo.com help developers in the areas of membership and cloud computing?


How do programmers stay healthy?

Being a programmer is not a very healthy profession - long hours of sitting in front of a computer, with impending deadlines just over the cubicle. This takes a toll on the body and mind. So what tips do you have for programmers in order to stay healthy?


How to build configurable forms?

I'm working on two separate projects now that are essentially just CMSs -- a bunch of forms for recording various bits of information. Each project is built to serve many clients, and each client seems to want to record slightly different information. In one project we've handled this either by copying and pasting all the logic surrounding that form for each client so that we could make the changes without affecting the other clients, or we build a master form containing all possible inputs and then programmatically remove the inputs that the client doesn't want (our framework allows us to remove inputs (essentially from the 'controller') before the final template rendering). Neither solution is really clean and causes the forms to be riddled with "if" conditions based on which client we're serving. The other project I'm just starting, and I don't want to run into the same pitfalls again, but I'm having trouble coming up with a good way to solve this problem. I could list out all the input IDs for each form element in the database and then create a mapping between them and the clients, and then in my form template wrap each widget rendering with a check to see if the input is enabled for the current client. On the backend -- when the form is submitted -- I could save only the data that is submitted and forgo the conditionals for the most part. This creates a dependency on the IDs used in the template must match those recorded in the DB -- I don't want to create the entire form programatically as that wouldn't give me enough customizability. That's the best I can come up with. Has anyone dealt with this sort of problem before? How did you approach it? What worked, what didn't? * * * For comparison, you might consider sites like Freshbooks, or Trello, or a bug tracker, or Facebook -- if any of those apps let each user customize his or her page to add or remove inputs so that they could record only the stuff they care about -- how would they manage this complexity from an architectural point of view?


Rails vs. Drupal

I was querying indeed.com/salary to investigate general market trends. When comparing ruby on rails with drupal, you would observe a substantial difference between these two. I'm not sure if the data on indeed.com is reliable or not but I'd appreciate your comments if you have ever tried both rails and drupal. Actually I am a .net developer considering an alternative to my asp.net mvc skills and I like to learn some non-microsoft web programming skills as well.


How can I earn money on my software?

Over last several months I had written some good piece of numerical software in C# in .NET 4.0. Currently it has only versions for Windows XP/Vista/7/8/8.1 but thanks to Mono/Xamarin it wouldn't be too hard to port it to Linux, Mac OS and even to mobile devices. The software has some really nice features of programs like Mathematica, Matlab but it's easier and faster (and of course not that huge). But still it has: real and complex charts of any custom function, support for most of the special functions (bessel, gamma, mathieu etc), scripting language with easy matrix calculations, scientific calculator, numerical calculations etc. It has less bugs and more features every day because I really love to work on this. I was working on this software mainly as a hobby but few of my friend who are testing it told me that it is really good so I started to wonder how can I make money on it (or should I even try this). If I even try to publish it as a commercial product what should I do? I consider some options.   1. Make it free&open source, I would not make any money of it then but I would get a lot of users and popularity. It might be the best option for the development of my software. Still I feel like when it will be free and open source I would waste a lot of time on working for free.   2. Make it freeware on desktop but charge (or put ads in it) on mobile devices. It sounds reasonable but porting it on mobile devices would consume much time and I would need a lot of time to develop many different versions.   3. Make it commercial software. It could be nice if I will find people who will want to buy my application but it has many difficulties in it. I dont have any experience there, problems arrive: how should I charge for this, code obfuscation, key licensing etc. Any help would be appreciated here on how to do this.   4. Something else? I have some other questions too, e.g. what I need to do in the start. I guess I need to create support website and put some bug tracking software? Any components would you recommend for this (support website+ bug tracking software)?


Is there a purpose for using pull requests on my own repo if I am the only developer?

So I got started with a real project of mine on GitHub and things are going pretty well and ideas are flowing a lot faster than I initially thought. In order to keep things organized, I setup some branches so I can develop different features separately. Now when I push my branch to GitHub, I have that section where I have two buttons : `Pull Request` and `Compare` with the name of the branch I recently pushed to. I understand the purpose of the `Compare` button but I don't get why I would want to create a pull request on my own repo. Can someone explain me why I would do that? Is it useful to make pull request on my own repo if I am the only developer?


What is the standard term for my role?

I'm doing work that involves writing code and managing developers in a "special projects" division of a large company. I'd like to define my role better and figure out if there's an industry standard term for what I do, so that it will be easier for me to research best practices and work on a career path What I do all day:   * A macro that connects an Excel sheet to an Access database is acting funny; I get called in to figure out what's happening and debug it.   * Someone needs data extracted from a bunch of files on Sharepoint. I figure out a client-side solution because I'm not authorized to do anything server-side and getting IT to do anything would take several months and need a business case.   * A manager wants a new data entry tool for their team. I interview the manager and team members to work out the functional requirements, then design/develop/test the application.   * Someone needs a VBA script to crunch some data for their presentation that's due in two hours. I drop everything I'm doing to hack out a quick script and run the analysis, without much in the way of testing.   * A developer has been hired to build a database for one of the teams, since I'm working on too many different things and don't have time to take this project on in the timeframe required. I direct his work and push him to meet certain deadlines, interview stakeholders to get more info that will help him figure out how to build the necessary forms, and modify the functional requirements of the database to fit in the timeframe.   * Someone wants to load a set of data into a GIS system and set up an ongoing refresh and reporting of this data set. I facilitate the conversation between the GIS developers and the owners of this data set, and design a demo application as proof of concept. It's kind of an "all-purpose programming and IT management" position, but it's not officially IT because the company has an actual IT department with a rigorously defined system of submitting requests, developing code, and managing projects. What I do, I guess, is more of a handyman job, where stuff falls to me because I'm the geekiest one in the room. Is there a standard term in the software world for what I do?


Am I doing wrong in my programming learning journey?

Well, I always liked programming, but I've never been committed or tied to any real project. I learned some autoit, some c#, some html and css. Now I've been hired **as apprentice** as programmer by an IT firm and I find hard times to understand the whole thing. They use a mix of C#, T-SQL, html, php, javascript, ASP and a lot of other things. I am missing the whole thing. I have to do C# programs that connects databases and synchronize data between them. But there is always some kind of problem with that _effin_ SQL. They use SQL management studio to put up their servers and that buggy piece of "software" by microsoft has 10212020 options, problems, dynamics and so on. EXAMPLE: I'll highlight in bold every technology or object I needed to link togheter or Had to/Hadn't to get togheter But the most frustrating thing is that I don't know enough. Every technology has tons of other ways to interface with others and to be configured and they expect me to know it. For example last week they expected me to know how to use **C#** to make a **Http** webrequest to consume a **wsdl webservice** with **soap** to get in response a long **XML** string which contained some orders made by another firm. Then I had to parse that string in **DataTables** and **Datasets** using **LINQ** because it's faster and "easier" (NO) than **XmlReaders** with **Xpath**. After that I had to make **Stored Procedures** in **T-SQL** to elaborate those orders and avoid duplicates after loading them into the **database** with various **SqlCommand, SqlConnection, DataAdapters, Connection strings** and so on. And every time it's something like this. For doing something you have to know how to use multiple technologies and become crazy because they have to set up 1000 settings or you'll get some weird Exception (Encoding, Comparing settings, blah blah blah). It seems too wide and too big for me. I don't know If I can do it. Until today, by documenting myself I managed to do the job in some way or with the help of workmates (and I'm thankful to them for teaching me). But there is just too much to know. A project can become big in a few minutes. In 1 month and half I had to mix what I already knew and get documented about: -Hardware specifics -Hardware settings -Hardware pieces of all kinds -All kind of sql weird behaviours, best pratices,strange settings -C# weird casting rules -C# **thousands** of objects you must use to accomplish even the simplest task -html -Weird and less used languages like Zebra language or Arduino (which is C-like) -Old and new technologies, like serial ports, MAC/linux systems (always been on windows), iOS 7 -A good way to interface different technologies (see the examle I made before, If it was for me, I would have done in a whole different way...) and the list could keep going for a long time, because I had to learn just too much. It's right for a programmer to have to know all of this? I think it's just too much for me or I'm just too stupid for it... I'm thinking to get another job, this is becoming too much of a stress and it seems to me that I'll never get "the whole design of the thing", meaning a clear idea of what I'm using or doing. What do you think? Have you felt the same way? Should I keep going? I feel sorry and ashamed I had to rely many times on my workmates or to have to google for everything...


Best practice for unused inherited virtual functions (implementing superclass methods)

Let's assume I have a hierarchy of several classes each derived from each other using virtual functions. The base class acts as an interface and defines functions, which may not be required by all of the derived classes. Now I wonder what the best practice is for such intermediate functions. Should those still be implemented and simple chain down to the base class, or should they be skipped? The problem I have is, that implementing such a function, when it isn't needed, simply adds noise to the code. On the other hand, when using a higher class, in C++ you can not simply call a superclass method (like in Java), so you need to know in which base class the method is really implemented. And to my mind, this would violate encapsulation, because I would need to know some implementation details of the base class. To illustrate what I mean here is an artifical exmaple:               class MyInterface     {         virtual void foo(bool) = 0;         virtual void foo1(int) = 0;     };          class Base : public MyInterface     {         void foo(bool param) override         {             // do some stuff here.         }              void foo1(int param) override         {             // do some stuff here.         }     };               class A : Base     {         void foo(bool param) override         {             // do some stuff here.             Base::foo(param);         }         // class doesn't need foo1() here so it is not implemented.     };               class B : A     {         void foo(bool param) override         {             // do some stuff here.             A::foo(param);         }              void foo1(int param) override         {             // This class needs foo1() but as A doesn't have it implemented             // I have to knwo this and skip A going directly to Base             Base::foo1(1);         }     };      Here the class `B` needs to know that A doesn't implement `foo1` and has to skip it. Of course this can be seen in the header, but if I want to later change class `A` it shouldn't be neccessary to touch all the other classes that are derived from it (encapsulation and isolation principle) So even worse, if I implement now `foo1()` in `A` later, `B` would still skip it and never realise that the functionality has changed. So from an object model point of view I would assume that such empty functions should still be designed into a class?


Define "Intermediate" (PHP) developer

I'm looking at the job market (as I imagine many are at the moment...) and I wanted to ask what the general consensus is on the skill levels required for "intermediate" or "junior" developers (PHP). For example, what tasks should an "intermediate" developer be able to handle - and what would you expect from a junior?


Changing Careers from Testing to Development

I am a Test Automation Engineer, when i entered I.T. i aspired to be a Java developer but as a fresher i did not have any choice and was put into Test Automation. I am in Test Automation for the past 2 years and I want to kn if it is possible for me to switch to development ?


Authentication strategy for mobile app with backend app using bcrypt

I have a backend app in node.js which implements user management, and it uses bcrypt to handle the password. So the password is stored in a single field using a format like `<header><salt><hashed password + salt>`. This part of the backend cannot be changed. I am writing some REST APIs for mobile apps to (among other things) authenticate the user, but I would prevent the password from being sent in clear (although over an SSL connection) from the mobile app to the server. At beginning I designed a process by which the client requests for an authentication token to the server, which is randomly generated and stored in a database. The client combines the token with the password (entered by the user, not stored locally), plus a secret key, hashes it all, and send to the server along with the authentication token. The server generates the same hash, compare it with the one obtained from the client, etc. The problem is that at server the password is hashed, so that doesn't work. An alternate way I thought about is for the server to return the salt along with the authentication token, so that the client can regenerate the same hash that's stored in the database, combine it with the authentication token, hash it again, and send back to the server. I feel that sending the salt to the client is not safe. I would like to know if that's a good strategy, and if not, which one would be more suitable and safer for this case? I remind that I cannot modify how the password is stored and managed at server side.


Immutable design with an ORM: How are sessions managed?

If I were to make a site with a mutable language like C# and use NHibernate, I would normally approach sessions with the idea of making them as create only when needed and dispose at request end. This has helped with keeping a session for multiple transactions by a user but keep it from staying open too long where the state might be corrupted. In an immutable system, like F#, I would think I shouldn't do this because it supposes that a single session could be updated constantly by any number of inserts/updates/deletes/ect... I'm not against the "using" solution since I would think that connecting pooling will help cut down on the cost of connecting every time, but I don't know if all database systems do connection pooling. It just seems like there should be a better way that doesn't compromise the immutability goal. Should I just do a simple "using" block per transaction or is there a better pattern for this?


Reactive programming vs MVVM pattern for managing GUI updates

Reactive programming and MVVM are two approaches that can address the problem of separating the domain layer from the UI.   * MVVM does this by defining a viewmodel, which is a data structure mapped to UI components. The UI display the data, and maybe update it when user occurs.   * a reactive framework defines a graph of observables which notify the UI that some piece of data has changed Reactive frameworks are gaining mind share, both in mainstream platforms (with Rx in .net & java, react.js) and more experimental places (FRP in haskell). I have mainly used MVVM with angular, and I find the simplicity to expressiveness ratio quite satisfying, although I have only worked on small/medium projects with it. **What does a reactive framework buys the developer that mvvm don't?** **Is there really a difference?** For example, knockout.js is advertised as a mvvm framework, but has a reactive feeling in its interface:               this.firstName = ko.observable("John");     this.lastName = ko.observable("Smith");          this.fullName = ko.computed(function() {         return this.firstName() + " " + this.lastName();     }, this);


Non Existent Keys Returning Null Instead of Exception

I have inherited a project from another developer, and it is riddled through and through with the following type of error:               echo $data['example'];           Notice: Undefined index: example      Obviously, I'm going to refactor this to check for the existence of the key prior to the print statement. However, my question is not related to the code per-se. Is there a version of PHP, or perhaps a setting within PHP whereby `echo $data['example'];` would simply return null or 0 in the case of a non-existent key? I ask because I'm trying to ascertain whether the previous developer had written bad code, or whether their development environment is misconfigured. If it's the latter, we can obviously resolve these issues for that developer's future projects.


Exceptions or Error codes

We are building a web service(SOAP, .Net) which would be talking to (mostly) native clients (windows, C++) and we are wondering what is the best way to communicate errors to the client (e.g. SomethingBadHappened like login service not available or something like user not found) and haven't been able to decide between throwing exception to the client or using some kind of error code model to do the above. What you would prefer on the handling on the client side: receiving a error code or handling a ServerFault exception which contains the reason for the error?   1) Why are we thinking exception: Because it would make server side code a lot more uniform   2) Why are we thinking error codes: Because we _think_ it makes more sense from the client side perspective. If 2) is really true we would probably want to go for error codes than exceptions? Is that the case here? Also, would the answer change if we were talking to managed clients instead of native clients?


How difficult is it to install and maintain IBM Rational DOORS?

I want to use IBM Rational DOORS for software development, but I would probably have to install and maintain it myself. How much effort is required? Is it something I can easily deploy on a server and start using right away, or do I have to basically become an IBM Rational specialist in order to properly deploy it? In other words, do I run a couple setup programs and, "Voila, it's done!" or do I have to install and perform deep configuration on a dozen other enterprisey prerequisites before I can even run the DOORS installer?


Scons, make, jam, ants, autotools etc and project files?

I wanted to get your thoughts. I see build systems like scons, make, jam, ants, autotools. Why do they exist? are they something like cross platform 'project files'? Do they address another need? to me .NET has almost a standard project file (xbuild on mono can build some of my projects created by msvc) I seen makefile's in each directory and sub-directory. In your opinion is this 'wrong'? My gut says if they are a 'project' file that allows you to pass in a few parameters for a complete build it should all be in one place (even if its multiple files). More importantly why do all of these tools exist?


Java or Python for internet application?

In choosing a technology for internet applications where the number of users may scale over time, which one should we consider: Java or Python? What are the considerations in choosing one and not the other? If speed and scalability is our main criteria, which one should we use? We have looked around and it seems that there are more websites that use Python [i.e : Quora, digg, reddit, bitbucket and disqus] than Java. Based on that, can we say that Python is more suitable for internet applications where speed and scalability is the main criteria? However we have browsed around and found some comments saying that Java is actually faster than Python. Thank you for your insights.


Best Practices for Handing over Legacy Code

In a couple of months a colleague will be moving on to a new project and I will be inheriting one of his projects. To prepare, I have already ordered Michael Feathers' _Working Effectively with Legacy Code_. But this books as well as most questions on legacy code I found so far are concerned with the case of inheriting code as-is. But in this case I actually have access to the original developer and we do have some time for an orderly hand-over. Some background on the piece of code I will be inheriting:   * **It's functioning:** There are no known bugs, but as performance requirements keep going up, some optimizations will become necessary in the not too distant future.   * **Undocumented:** There is pretty much zero documentation at the method and class level. What the code is supposed to do at a higher level, though, is well-understood, because I have been writing against its API (as a black-box) for years.   * **Only higher-level integration tests:** There are only integration tests testing proper interaction with other components via the API (again, black-box).   * **Very low-level, optimized for speed:** Because this code is central to an entire system of applications, a lot of it has been optimized several times over the years and is extremely low-level (one part has its own memory manager for certain structs/records).   * **Concurrent and lock-free:** While I am very familiar with concurrent and lock-free programming and have actually contributed a few pieces to this code, this adds another layer of complexity.   * **Large codebase:** This particular project is more than ten thousand lines of code, so there is no way I will be able to have everything explained to me.   * **Written in Delphi:** I'm just going to put this out there, although I don't believe the language to be germane to the question, as I believe this type of problem to be language-agnostic. I was wondering how the time until his departure would best be spent. Here are a couple of ideas:   * **Get everything to build on my machine:** Even though everything should be checked into source code control, who hasn't forgotten to check in a file once in a while, so this should probably be the first order of business.   * **More tests:** While I would like more class-level unit tests so that when I will be making changes, any bugs I introduce can be caught early on, the code as it is now is not testable (huge classes, long methods, too many mutual dependencies).   * **What to document:** I think for starters it would be best to focus documentation on those areas in the code that would otherwise be difficult to understand e.g. because of their low-level/highly optimized nature. I am afraid there are a couple of things in there that might look ugly and in need of refactoring/rewriting, but are actually optimizations that have been out in there for a good reason that I might miss (cf. Joel Spolsky, _Things You Should Never Do, Part I_ )   * **How to document:** I think some class diagrams of the architecture and sequence diagrams of critical functions accompanied by some prose would be best.   * **Who to document:** I was wondering what would be better, to have him write the documentation or have him explain it to me, so I can write the documentation. I am afraid, that things that are obvious to him but not me would otherwise not be covered properly.   * **Refactoring using pair-programming:** This might not be possible to do due to time constraints, but maybe I could refactor some of his code to make it more maintainable while he was still around to provide input on why things are the way they are. Please comment on and add to this. Since there isn't enough time to do all of this, I am particularly interested in how you would prioritize. _Update:_ As the hand-over project is over I have expanded this list with my own experiences in this answer below.


Designing an administrator area in my CMS

I am trying to create a small CMS with ASP.NET MVC3, but I got confused in designing the administrator section. I decided to create two areas, one for users and another for admin. In my CMS I have a `Post` and a `News` object, and I want to put create/edit/delete functions in the admin area and other function that related to users in the user area to achieve functionality in my CMS. For example I have two `NewsController`, one in the admin area (include create/edit/delete functions) and another in the user area (include `preview(id)` function). Is this design good? How can I improve it?


I would like to improve in writing goal-oriented user stories/features

I would like to improve my user stories writing abilities so I need your experience and guidance. I think that each _variable_ part of a user story can be improved by following certain guidelines. ## 1\. Role Defining possible roles may be the easiest part. The only problem is that user stories usually just describe functional features that need development.   * **Do you write non-functional stories?** And I'm not thinking about technical stories that are related to other aspects of product planning like administrative things. I'm more thinking of additional supporting stories that support the same high-level goal. Like advertising related stories that are related to features? ## 2\. Feature Defining features seems to be easy but it turns out it's not. Because I can see stories that are heavily related so certain roles can't be developed until others are finished. Example: User registration is a pillar user story that needs to be done first in order to develop other user stories that are related to registered user roles (logged in users and/or admins etc.). This one is very obvious but sometimes relationships are much more subtle.   * **How do you avoid relationships between user stories?** Is there a technique to break related stories apart so we can have better development parallelism? Breaking relationships also helps better sprint cycles because one story can't stall the whole sprint. ## 3\. Benefit This one is the hardest part that I think I have least knowledge how to write good user stories with clear benefits.   * **Do you actually write benefits per story or do you rather provide high level goals instead?** Providing these instead of benefits makes it easy to see why certain user story is more important than the other? So it helps prioritisation.   * **Is it wise to have shared benefits/goals between set of user stories?**   * **Do you write user stories without benefits part?** Is that wise and what do you do instead?   * **Do you write benefits in a way so they can be measurable?** Can we do that and is it beneficial? ## 4\. User stories as a whole   * **Have you ever defined all user stories as epics?** This would help filter out/prioritise those that give more to the common goals. Then split them into digestible chunks or per single feature user-stories.   * **What additional metadata do you add to user stories?** Also talking about user story grouping per higher feature or goal...


Custom Domain or Attribute Reference Table or Both?

I'm designing my first real database and I'm weighing the pros and cons of how to enforce uniformity in my data. My first option is to create a custom domain and program my UI to only allow certain options. My second option is to create an "attribute reference table" that would store allowed values. My UI could query that table for allowed values and display them in a drop down box. Or I could do both My thoughts on the first is that it would be more difficult to maintain the UI. If the domain were to change, then I would need to alter the UI (unless there is a way to query the domain for values?). I don't know whether there is, but my thought is this would process and return results faster than having to query a second table. An attribute table seems beneficial in that I can design the UI to adapt on the fly, but less optimal in the sense that the data values are not controlled by the DBMS and it requires an additional query. Doing both would add all of the complexity, increase processing time, and increase UI maintenance.


moore's law and quadratic algorithm

I was going thru a video (from `coursera - by sedgewick`) in which he argues that `you cannot sustain Moore's law using a quadratic algorithm`.He elaborates like this In year 197* you build a computer of power X ,and need to count N objects.This takes M days According to `Moore's law`,you have a computer of power 2X after 1.5 years.But now you have 2N objects to count. If you use a quadratic algorithm, In year 197*+1.5 ,it takes (4M)/2 = 2M days 4M because the algorithm is quadratic,and division by 2 because of doubling computer power. I find this hard to understand.I tried to work thru this as below               To count N objects using comp=X , it takes M days.     -> N/X = M          After 1.5 yrs ,you need to count 2N objects using comp=2X     -> 2N/(2X) -> N/X -> M days      where do I go wrong? can someone please help me understand?


Why is "tight coupling between functions and data" bad?

I found this quote in "The Joy of Clojure" on p. 32, but someone said the same thing to me over dinner last week and I've heard it other places as well: > [A] downside to object-oriented programming is the tight coupling between > function and data. I understand why unnecessary coupling is bad in an application. Also I'm comfortable saying that mutable state and inheritance should be avoided, even in Object-Oriented Programming. But I fail to see why sticking functions on classes is inherently bad. I mean, adding a function to a class seems like tagging a mail in Gmail, or sticking a file in a folder. It's an organizational technique that helps you find it again. You pick some criteria, then put like things together. Before OOP, our programs were pretty much big bags of methods in files. I mean, you have to put functions somewhere. Why not organize them? If this is a veiled attack on types, why don't they just say that restricting the type of input and output to a function is wrong? I'm not sure whether I could agree with that, but at least I'm familiar with arguments pro and con type safety. This sounds to me like a mostly separate concern. Sure, sometimes people get it wrong and put functionality on the wrong class. But compared to other mistakes, this seems like a very minor inconvenience. So, Clojure has namespaces. How is sticking a function on a class in OOP different from sticking a function in a namespace in Clojure and why is it so bad? Remember, functions in a class don't necessarily operate just on members of that class. Look at java.lang.StringBuilder - it operates on any reference type, or through auto-boxing, on any type at all. P.S. This quote references a book which I have not read: Multiparadigm Programming in Leda: Timothy Budd, 1995.


Domain Logic in Service Layer exposed as WCF service

I am designing an enterprise solution which consists of modularized products within a product range using Entity Framework code first to define the domain model and provide the data access. e.g. Solutions:               ProductRange.Authentication     ProductRange.Gateway     ProductRange.OrderSystem     ProductRange.MarketingSystem      Each of these products (solutions) will have similar layers, currently: Projects in each solution:               ProductRange.OrderSystem.Model (contains code first POCOs)     ProductRange.OrderSystem.DataContext (contains the dbContext)     ProductRange.OrderSystem.DataAccess (contains the Generic Repository)     ProductRange.OrderSystem.Service.DomainLogic (contains business logic)     ProductRange.OrderSystem.Service.ApplicationLogic (contains application logic)     ProductRange.OrderSystem.Presentation.AdminWebsite     ProductRange.OrderSystem.Presentation.CustomerWebsite      Some of the products will need to access the domain logic of another product, especially they will all need to access the ProductRange.Authentication but also ProductRange.MarketingSystem will need to query ProductRange.OrderSystem I am thinking to expose the domain logic between products in the range via a WCF service. But I will also need to reference the product locally (e.g. creating project references). How should I go about implementing this? Should I create a WCF service e.g. ProductRange.OrderSystem.WCF which calls the domain logic and exposes it or should my domain logic itsself be a WCF service? If the latter, would I always have to reference my domain logic via the WCF, even from the local ApplicationLogic? I guess I am looking for some guidance about what layers to have and how best to provide inter connectivity between the solutions.


Best practices for refactoring parameter file structure in multiple environments

**Background info and what I've tried** Within each of two mostly distinct environments, say 'Research' and 'Production', there is a need for a structured parameter file. The file contains things like database connections, tables, and some other parameters, nothing unusual. The current approach is to have two distinct parameter files, say "params.txt" and "params_prod.txt" (for production). (Also, in case it helps, we're not actually using .txt for this, we're using a markup language, but the details of that don't really matter for this question.) Most of the information is duplicated between these two files, leading to lots of copy/paste. Plus, in version control, everyone has to manually make changes to two files and we have to trust that they are propagating changes if checking things in. Needless to say, this leads to headaches to resolve when some divergence happens between the files. We have tried workarounds, like writing tests to check that the files are identical in all the ways they need to be, but this is not a perfect science since the structure of the files can change and the definition of what, exactly, must be identical between them changes too. I have had one idea: Just use a single file, but create sub-sections within the file. There can be a sub-section for general parameters that are always shared, another section for things that should be treated as the 'default' parameters (the 'Research' environment settings) and then another section for the 'Production' environment settings. We already have code that parses the parameter files and instantiates objects, loads data, etc. etc., based on the parameters. We could go back and add some options to that code, such that it loads data according to which sub-section of the parameter file it is told to use and ignores parameters from the other section. This has some benefits: (1) everything is in one file, so there's no "just trusting" that people are propagating changes. (2) It also does not require copy/paste code since anything that is shared between both environments needs to only appear in one section at the top of one parameter file. (3) If anything, this should make the parameter files themselves more modular and easier to use. (4) We save time/cost that would have been spent creating complicated test-based work-arounds that check whether the files are being propagated together during check-ins with version control. We don't need to do that in this case. It does have costs too: (1) time spent making the newly formatted parameter file specifications in XSD so we can validate it and ensure it is backwards compatible; (2) costs if we do need to re-code and make our software-that- interfaces-with-parameter-files have options for whether to use 'Research' or 'Production'. (3) If any of the properties that are currently considered to be in the sub-section that is shared, but which suddenly become things where we want to have different options between 'Research' and 'Production', we would then have to refactor all parameter files to move that item down into the other sections. (3) Seems like the biggest worry, but it also forces us to constantly re- factor these parameter files, which is a good thing in my view. Besides, if we want flexibility about re-assigning a parameter from one sub-section to another, there ought to be better ways to achieve it than duplicating the entire file. **Question** Are there any significant pitfalls that I am failing to realize about the proposed idea regarding don't-repeat-yourself vs. build-in-flexibility trade- offs in parameter file design?


Mapping a list of optional values to an optional list of values

I have encountered the following pattern while programming in Haskell (but the pattern could occur in any language supporting lists, option types, and mapping of a function over a list). I have types `a` and `b` and a function               f :: a -> Maybe b      Now I want to define a function that maps f on a list of type `[a]`, but I am not interested to have a result of type `[Maybe b]`. Rather, I want to have `Just [y1, ..., yn]`, if `[f(x1), ..., f(xn)] == [Just y1, ..., Just yn]`, and `Nothing` otherwise (i.e. if `f(xi) == Nothing` for at least one i). So the result must be of type `Maybe [b]`. I solved this by using the following helper function:               combine :: Maybe b -> Maybe [b] -> Maybe [b]     combine me ml = do                        l <- ml                        e <- me                        Just (e : l)       and then               g :: (a -> Maybe b) -> [a] -> Maybe [b]     g f xs = foldr combine (Just []) (map f xs)      So, for example, if I have               f x = if x > 0 then Just x else Nothing     xs0 = [1, 2, 3, 4]     xs1 = [-1, -2, 3, 4]     xs2 = [-1, -2, -3, -4]      then               map f xs0 = [Just 1, Just 2, Just 3, Just 4]     g f xs0   = Just [1, 2, 3, 4]     map f xs1 = [Nothing, Nothing, Just 3, Just 4]     g f xs1   = Nothing     map f xs2 = [Nothing, Nothing, Nothing, Nothing]     g f xs2   = Nothing      The solution with `combine` and `foldr` works, but I wanted to ask if you know of a more compact solution for turning a `[Maybe a]` into a `Maybe [a]` as described above.


What are some best practices for report writing?

I need to give a presentation to a coworker on some of the best practices regarding reports. Right now I use jaspersoft's iReport to do my reports and I need to give some input to a coworker. I'm looking for some general knowledge and insight on the topic.


Power failure should be considered as a scenario to implement?

Do you think that power failure is a scenario to implement? At what time that scenario should be taken into consideration? If power failure will cause some data loss so do you care about it ? if(IsImportant(data)) ... else .. ? What do you think If our application doesn't work anymore even power failure scenario shouldn't be fault to consider if power failure broke the application permanently ? So we have to consider these situations always ? Can you suggest pragmatic approaches for power failure scenarios ?


How to get started with computer science research

I started programming later in my career (mid 30's) simply because I enjoyed it and had an opportunity to contribute at my job. While I still have tons to learn, at some stage I would like to know what is going on the area of computer science research. I'm wondering if folks here on the exchange can point me in the right direction of some methods or resources; good journals, etc. Are there some good topics to start with? Also, in what areas was reading research papers most helpful to you?