问:
Threads or ThreadPool? Fixed or Dynamic ThreadPool?
I have a java program which listens on a port for input. Based on Input, it calls a webservice and then returns a success/failure back to the client program.

I fork a thread for each client connection. The response back to the client which connects to the program has to be quick.

These are the choices I am considering

use regular threads

use ExecutorService with newFixedThreadPool

use ExecutorService with newCachedThreadPool

The reason I am considering Pools is because my threads are shortlived - they just call a webservice, return result to the client and close the connection.

I don't think newFixedThreadPool would be the right thing because then connections would be waiting in queues to get a thread.

newCachedThreadPool would have been perfect except for one thing - threads die after a minute. In my case, I get bursts of connections - i.e. multiple connections and then there may be a lull for a few minutes and then again bursts. I think the threads in the CachedThreadPool would die and and would again have to be recreated - so in this case, it may work like #1 sometimes.

Ideally I would have loved to have newCachedThreadPool with a minimum - i.e. a setting which says number of threads would never go below say 20. So idle threads are killed but never allow to go below a minimum threshold.

Is there anything like this available? Or are there any better alternatives?

答:
i think using a wrapper over a ThreadPoolExecutor is a good way to go. A wrapper so you can expose some initialization (like a pool name, number of threads etc) and a method to add a task (Runnable) to a pool made earlier with one of your init methods.

The wrapper can change which pool it uses without affecting other code, plus can expose other methods like number of threads, audits (before / after task) in a consistent fashion

You can also implement your own Thread factory for your pool, which can have a custom name, priority and at the very least hook on an UncaughtExceptionHandler so you can log any errors.

in my pool wrapper we have methods like

```<code>public static boolean queqeAdd(String poolName, int coreSize, int maxSize, boolean usePriorityQ, String threadNamePrefix, int timeOutSeconds) {...}
public static void execute(String poolName, Runnable command, Integer priority){...}
public static long tasksCount(String poolName)
public static long tasksCompletedCount(String poolName)
public static int clearPoolRequest(String poolName, boolean intrpt)
public static int shutdownPoolRequest(String poolName)
public static void executeAll(String poolName, List<Runnable> lst)
</code>```

Body:
i think using a wrapper over a ThreadPoolExecutor is a good way to go. A wrapper so you can expose some initialization (like a pool name, number of threads etc) and a method to add a task (Runnable) to a pool made earlier with one of your init methods.

The wrapper can change which pool it uses without affecting other code, plus can expose other methods like number of threads, audits (before / after task) in a consistent fashion

You can also implement your own Thread factory for your pool, which can have a custom name, priority and at the very least hook on an UncaughtExceptionHandler so you can log any errors.

in my pool wrapper we have methods like

public static boolean queqeAdd(String poolName, int coreSize, int maxSize, boolean usePriorityQ, String threadNamePrefix, int timeOutSeconds) {...}
public static void execute(String poolName, Runnable command, Integer priority){...}
public static long tasksCount(String poolName)
public static long tasksCompletedCount(String poolName)
public static int clearPoolRequest(String poolName, boolean intrpt)
public static int shutdownPoolRequest(String poolName)
public static void executeAll(String poolName, List<Runnable> lst)


问:
Source Code Only Allowed With One Open Source Project
I have an open source project that is licensed under the GNU General Public License v3 and it's done in Windows Presentation Foundation. I came across someone that sells themes/skins for WPF projects and he is willing to donate one of the skins for use with open source project. However, he only wants the skin to be allowed to be used with my project. I was wondering what the best way would be to prevent other people from stealing the skin and using it with their projects? Is there a license that would fit this requirement? Or is there a better way to accomplish this?</p>

答:
Your best option is to politely refuse the offer.  IMO.

Is there a license that would fit this requirement?

None that I'm aware of.  Or at least not one of the common ones.  Of course, you could talk to a lawyer and draft a license expressly for this purpose.  But you are likely to get heat from various quarters for doing it.

Surely it is not worth it ... for a bit of eye candy.

ContentLicense: CC BY-SA 3.0


问:
How much redundancy/robustness should complex software implement?
The focus of this question: Some software performs "extra work" in order to increase the chance of a "eventually successful/satisfactory" outcome, despite one or more internal errors in the software, which requires a longer execution time when those errors happen. All these happen without the user's knowledge if the outcome was successful.

Definition of complex software:

Contains code written by (contributed from) more than 10 developers over its lifetime, and not written in the same time frame

Depends on more than 10 external libraries, each with caveats

A typical software task (for generating a result wanted by the user) requires 10 or more input parameters, where most of them have default values but are configurable if the user needs control.

Most importantly, software that has the appropriate complexity relative to the task being performed, i.e. not unnecessarily complicated.

Edited: What is complex? Please see There is a big difference between Complex and Complicated. (direct link)

Definition of Redundancy/Robustness within this question:
(Added Robustness based on comments)

If a software task failed when the current set of parameters was used, try different parameters.

Obviously, there must be inside knowledge that those "different" parameters use a different code path, possibly resulting in a different (hopefully better) outcome.

Sometimes these different code path are chosen based on observations of the external libraries.

At the end, if the actual task performed is slightly different from the user's specification, the user will receive a report detailing the discrepancy.

Finally, like the 10-plus configurable parameters, the redundancy and reporting are also configurable.

Example of such software:

Database Migration

Business database

Source control database, etc.

Batch converting between a Word document and an OpenOffice document, PowerPoint and OpenOffice Draw, etc.

Automatic translation of an entire website

Automatic analysis of software package, such as Doxygen, but where the analysis needs to be more dependable (i.e. not just a documentation tool)

Network communication, where packets may be lost and a number of retries are expected

This question was originally inspired from How do you deal with intentionally bad code?
 but is now focused on just one of the causes of software bloat. This question does not address any other causes of software bloat, such as addition of new features.

Possibly related:

How to deal with complex codes in (huge) projects

How do people manage to write and maintain extremely complex and hard to read code?

答:
Software should be forgiving of user mistakes, and completely intolerant of programmer mistakes.

Meaning, software should be very robust and allow smooth recovery for things like user input errors, and system configuration errors.  At the very least a friendly error message stating where the error occurred (input box, config file, command line argument, etc...) and what constraint was violated ("must be less than X characters," "valid options are [X,Y,Z]", etc...)   For additional robustness, the software can suggest an alternative, or use a reasonable default (but it should always indicate that it is not using exactly what the user specified).

I can't think of a lot of situations where an automatic retry with different defaults is warranted, but there are some (auto retrying to establish a communications link seems reasonable).  I agree with @William that this level of 'redundancy' is a buisness decision.

On the other hand, there should be no run-time robustness against programmer error.  If there are pre-conditions for a function's parameters, they should be checked with asserts, not run-time checks.  It is a huge pet peeve of mine to see redundant errror checking and reporting on the same parameter three or four levels into the call stack:

```<code> int A(int x)
 {
   if (x==0) return -1
   ...
 }
 int B(int x)
 {
   if (x==0) return -1
   err = A(x)
   if (err) return err;
   ...
 }
 // and so on and so on....
</code>```

This is just additional unneeded complexity.   You should not spend timing figuring out how one function should handle an error introduced by misusing another one.  If this is the type of 'robustness' you are referring to - you don't need it.  Replace it with asserts and thorough integration testing.

ContentLicense: CC BY-SA 2.5

Body:
Software should be forgiving of user mistakes, and completely intolerant of programmer mistakes.

Meaning, software should be very robust and allow smooth recovery for things like user input errors, and system configuration errors.  At the very least a friendly error message stating where the error occurred (input box, config file, command line argument, etc...) and what constraint was violated ("must be less than X characters," "valid options are [X,Y,Z]", etc...)   For additional robustness, the software can suggest an alternative, or use a reasonable default (but it should always indicate that it is not using exactly what the user specified).

I can't think of a lot of situations where an automatic retry with different defaults is warranted, but there are some (auto retrying to establish a communications link seems reasonable).  I agree with @William that this level of 'redundancy' is a buisness decision.

On the other hand, there should be no run-time robustness against programmer error.  If there are pre-conditions for a function's parameters, they should be checked with asserts, not run-time checks.  It is a huge pet peeve of mine to see redundant errror checking and reporting on the same parameter three or four levels into the call stack:

 int A(int x)
 {
   if (x==0) return -1
   ...
 }
 int B(int x)
 {
   if (x==0) return -1
   err = A(x)
   if (err) return err;
   ...
 }
 // and so on and so on....

This is just additional unneeded complexity.   You should not spend timing figuring out how one function should handle an error introduced by misusing another one.  If this is the type of 'robustness' you are referring to - you don't need it.  Replace it with asserts and thorough integration testing.


问:
Design guidelines for this scenario in C#?
I have to create a validation system(I don't want to use Data Annotation or any other system) for my C# application using .Net Compact Framework, where I have an object which contains many other objects.

Many of the properties are dependent on each other means they have some sort of dependencies.

I can write a simple validator class which goes through all the properties
and checks them one by one with lots of if and else but I want to design something dynamic e.g. I should be able to specify list of dependencies on a property and specify a method which should be invoked during validation.

I mean some design guidelines would be appreciated ?

Example ( just for demo purpose ):

```<code>    public enum Category
        {
            Toyota,
            Mercedes,
            Tata,
            Maruti
        }

        class MyBigClass
        {
            public Category Category { get; set; }
            public double LowerPrice { get; set; }
            public double UpperPrice { get; set; }

            public SomeOtherObject OtherObject { get; set; }

public List<string> Validate()
        {
            List<string> listErrors = new List<string>();
            ParameterInfo pInfo = null;
            switch (Category)
            {
                case Category.Toyota:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Toyota);
                    break;
                case Category.Mercedes:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Mercedes);
                    break;
                case Category.Tata:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Tata);
                    break;
                case Category.Maruti:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Maruti);
                    break;
                default:
                    break;
            }

            if (LowerPrice < pInfo.Min || LowerPrice >= pInfo.Max)
            {
                listErrors.Add("LowerPrice");
            }

            if (UpperPrice > pInfo.Max || UpperPrice <= pInfo.Min)
            {
                listErrors.Add("UpperPrice");
            }

            return listErrors;
        }
        }

        public enum PTYPE
            {
                RATING,
                Category_Tata,
                Category_Toyota,
                Category_Mercedes,
                Category_Maruti
            }

            public class ParameterInfo
            {
                public PTYPE Type { get; set; }
                public int Min { get; set; }
                public int Max { get; set; }
                public int Default { get; set; }
            }

       public class ParameterStorage
        {
            private static Dictionary<PTYPE, ParameterInfo> _storage = new Dictionary<PTYPE, ParameterInfo>();
            static ParameterStorage()
            {
                _storage.Add(PTYPE.Category_Maruti, new ParameterInfo { Type = PTYPE.Category_Maruti, Min = 50000, Max = 200000 });
                _storage.Add(PTYPE.Category_Mercedes, new ParameterInfo { Type = PTYPE.Category_Mercedes, Min = 50000, Max = 800000 });
                _storage.Add(PTYPE.Category_Toyota, new ParameterInfo { Type = PTYPE.Category_Toyota, Min = 50000, Max = 700000 });
                _storage.Add(PTYPE.Category_Tata, new ParameterInfo { Type = PTYPE.Category_Tata, Min = 50000, Max = 500000 });
            }

            public static ParameterInfo GetParameterInfo(PTYPE type)
            {
                ParameterInfo pInfo = null;
                _storage.TryGetValue(type, out pInfo);
                return pInfo;
            }
        }
</code>```

In the above example I have a MyBigObject which contains some properties and some other objects and I have a storage class which keeps all the limits of properties which will be required to validate a property.

As described in the above example I have to get ParameterInfo for each property and then compare, I am looking for some kind of automatic way/dynamic way of doing the same.

答:
What about extracting the validation, and putting it at the same level as the input?

What I want to say is that it's not the role of an object to validate itself. An object should always be valid: creating an invalid one doesn't make too much sense. In the same way, you don't create a person with an age of -50, because an age is always a positive value or zero.

In order to ensure an object is valid, one uses Code contracts in .NET Framework. Invariants would be especially useful, since they would not only prevent creating an invalid object, but also alter a valid one so it becomes invalid. In the same way, constraints in databases prevent invalid data from being stored.

Then, finding a place for input validation will depend on the context. If the object is created from user input (including, for example, an application which is using your API), validate the input. Other situations would mitigate the validation somewhere else. If creating an object is a difficult task, one will use a factory, which will how to create an object, without violating its contracts.


问:
What are some good assignments for an introductory course, to reach today's students?
I periodically teach an introduction to programming course using Java. I want to give my students some exciting assignments that they can relate to or find interesting. At the very least, I want assignments that make sense and have an internal cohesion (for example, some very bad programming exercises seem contrived just so that you have to use the most recent programming construct covered).

To give you an idea of scope, here's what's being covered:

The assignments must be in Java, using some external library can be done, but it would need to be a simple API and not a full framework

Variables, Primitives and Strings

Console input and output

if, for, while

Arithmetic and logical operators

Simple graphics with line and shape drawing

Static methods

One-dimensional arrays

The students will not go into advanced topics (e.g., no recursion, no emphasis on inheritance). Thus, I'm not looking for complex projects: "Have them write a C compiler. I did it when I was 5 and it was the only way I learned!"

If you have ideas that are more advanced than the scope, please post them on the "Challenging" question linked below, and not this one.

Instead, what I'm looking for are interesting ideas that can be accomplished in a short program. For example:

Students can write a console version of the "Star Wars Name" Generator. This is effectively reading Strings and using substring, but I think it's fun. A similar variation would be a "Mad Libs" program. I used this one five years ago, and perhaps it's already "stale."

Using some trig supplied to them, students can draw regular polygons, and create interesting spiral shapes.

It's also not out of the question to use some simple animation class with most of the code supplied to them. And if you know a Twitter or Facebook service that can be accessed with a simple API, I would be very interested to know.

Please note that this question is different from the "Challenging Java questions for beginners" Question. I'm not looking for challenging per se, just interesting. I think if students work on something where they can easily answer "why would anyone ever want to program that?" then they will learn better.

Even simple problems like computing Miles per Gallon can be good. Although, if there's a way to update it to be more relevant, all the better. If you have an exercise from somewhere else (a book or a website), please cite the source.

To help you think about the typical freshman today, check out the Beloit Mindset list, for many examples that will surely make you feel old.

答:
I taught intro way in the last century, and it was BASIC, but like you I wanted to get the students going on a fun project of their own devising. So I suggested a bunch of possibilities:

Simple adventure game, like Wumpus

Sports simulation (text only, graphics for the ambitious) for baseball or whatever

Science, like simulating genetic evolution

Sport/science, like sailboat racing

Finance, like having your own bank for the people in your household, or investments

Music or simple graphical games

... or whatever students thought of. They would come to me and say "how about a program to do XYZ?" and I would always say "Great", and then maybe guide them a little not to make it too complicated.

Usually their projects ended up being a few hundred lines of code, and they always enjoyed it.

P.S. I gave this assignment after the students were competent with basic control structures, I/O, arrays, and sequential files. It was a term project, a major part of their grade, and I had intermediate milestone assignments, like an outline part way through, so they didn't try to do it all at the end and hit a wall. I wanted to get them into this as early in the semester as possible, when they had enough skills to get started, typically around week 6 or 8.


问:
Priority queue for Kruskal's algorithm with running time O(E lg V)
I'm reviewing my notes on Kruskal's algorithm and have a question about getting the runtime down to O(E lg V). By using a PQ with edges and a boolean array of which vertices we have added to our tree T, the running time is O(E lg E), but in my notes there is also a variant with running time O(E lg V), by using a PQ with vertices instead of edges. However, this requires the PQ to support updating weights (important part highlighted):

Maintain a PQ of vertices connected by an edge to T, togethether with
  the edge that connects it to T. The priority of this tuple is the
  weight of the min-weight edge connecting it to T. When adding a new
  vertex to the tree, we add all vertices adjacent to this new vertex to
  the PQ unless it's already in the PQ. If it is in the PQ and the new
  edge connecting it to T is of lower weight, we update its weight and
  the edge associated with it, if not, we do nothing.

When thinking about how to actually implement this, I realized that all priority queues I have seen have O(n) updates, since the ordering is too weak for us to be able to find an element faster. I tried searching a bit but couldn't find any PQs that support updating in O(lg n) time, except some references to fibonacci heaps that can do it in O(1) time, but looks like a much more complex data structure.

Is there a simple way to get O(lg n) updates of a priority queue? I could insert keys and references to elements in a hash table and use that to quickly find and update elements, is this a viable solution? (I realize that this will require O(n) extra space.)

答: A simple binary heap can support O(log n) updating of an element if you have a pointer/reference to that element's position in the heap (which can be acquired through an auxillary hashtable if necessary). The O(log n) is actually due to the necessary work to preserve the heap property.</p>


问:
Using third party/ open source controls
I usually feel reluctant to use any third party or open source controls while coding in Objective-C iPhone due to following reasons.

Open source controls are developed in incremental manner. So once integrated I have to keep looking for update and will have to update my code. Will increase effort.

Open source controls may likely add memory leaks and thus make application incompetent in terms of memory.

Third party libraries are difficult to manage, as well as they keep conflicting with your classes.

Please correct me on these points, so that I may feel comfortable with open source codes.

答:
Everything you said applies to commercial, close-source software too.

Updates: the difference is that FOSS code is much more honest about their incremental development schedule. Closed source world wants to to think their product is the last and final finished version.. with regular security updates and patches.. until the next version comes out that they want you to buy. Notice how many updates you still get with close sourced software?

Memory Leaks: you're kidding now. Software is software, most FOSS stuff is not written by kids in their back bedroom, its written by people who write closed source software during their day jobs. So there's no reason why they would suddenly become poor programmers in the evening. The other aspect here is that if there is a memory leak in FOSS you can fix it yourself! Try doing that with a closed source product.

Conflicts: not at all, as before its the same stuff only packaged differently. FOSS would conflict where closed source doesn't just doesn't make sense.

The problems with FOSS is more to do with documentation, you generally get the code and no support, tutorials, examples or any help. If you're the kind of guy who needs to be told how to code, then FOSS is not for you. That said, there are plenty of resources available for a lot of FOSS stuff, it just depends on the individual product.

Title: Using third party/ open source controls


问:
Modify then sell another person's code
I am working, with a co-author, on a data modeling toolbox that will someday be sold. Part of the functionality is the extremely common PCA, which we are doing in a more robust way. Thus, we need a PCA function that has the usual algorithm with some modifications. For non-commercial peer-review academic research, I could easily find PCA code that is already written, modify it to suit my needs and use it, citing the author in my research.

My co-author insists that in this commercial venture, it is entirely appropriate to do the same thing. We can take another author's copyrighted code (ex "Copyright (c) 1997 by blah blah blah", not necessarily a GNU license), modify it to suit our needs, and distribute it with the toolbox we are selling. He says that as long as we cite the original author, it's entirely acceptable.

I'm just as strenuously insisting this is not legal, but have been unable to find straightforward documentation. Can someone point me to unambiguous documentation of this?

答:
Contact the author of the code you intend to modify and ask for permission in writing to do what your partner wants.  That won't cover you, but a strongly worded "don't modify my code" letter might convince your partner that this is a bad idea.

As the many comments have pointed out, asking for legal advice from a bunch of strangers who don't claim to be lawyers (let alone live in your country) is a bad idea.

If you're going to make anything more than beer money it will be very important to be able to prove that you have clear rights (either ownership or appropriate FOSS license) to everything.

Talk to a local lawyer

Spending money on a lawyer is cheaper than defending (or worse, losing) a lawsuit.

Title: Modify then sell another person's code


问:
Using only UI testing. Is that Ok?
I am a sole developer working with an offshore employer. I do realize the importance of unit testing (although haven't practiced before) but currently, the code hasn't ever been tested. The problem with the code is that it isn't what I call "been moduled well", some parts are really messy, extensive use of globals and the code doesn't really show loose coupling. If I am not wrong, the code might require heavy refactoring before being able to be unit tested. Also, it seems the employer, isn't quite interested in testing. He rather suggests to spend this time in building features.

So what I suggested to him is UI testing. Because UI testing is something we do every time, testing features, clicking, checking if something is  not broke, it made sense to both of us to use it to automate the process of checking features and save us time.

Since I have never done UI testing before, I don't know what possible disadvantages might be associated with using just UI testing alone or will it be much beneficial at all?

答:
UI tests are not what you're looking for. To get messy legacy code under test, you start writing Acceptance Tests. These are blackbox tests on the outer layer, but widely independent from the user interface. You can look at tools like Cucumber to get an idea about the approach.

As you're going to refactor and improve the code, you should add unit and integration tests for new code as you go along.

Title: Using only UI testing. Is that Ok?


答:
I think that it entirely depends on what you define as modifying. If you change his code but leave most of the work intact, you're basing your copyrighted code on his copyrighted code.

If however you take his code and use it as inspiration for your code then your code is not based on his copyrighted code but on his (patented) implementation.
Basically: write your own implementation of what the original author did. Shouldn't be hard because you can use his code as inspiration.

Title: Modify then sell another person's code

Body:
I am working, with a co-author, on a data modeling toolbox that will someday be sold. Part of the functionality is the extremely common PCA, which we are doing in a more robust way. Thus, we need a PCA function that has the usual algorithm with some modifications. For non-commercial peer-review academic research, I could easily find PCA code that is already written, modify it to suit my needs and use it, citing the author in my research.

My co-author insists that in this commercial venture, it is entirely appropriate to do the same thing. We can take another author's copyrighted code (ex "Copyright (c) 1997 by blah blah blah", not necessarily a GNU license), modify it to suit our needs, and distribute it with the toolbox we are selling. He says that as long as we cite the original author, it's entirely acceptable.

I'm just as strenuously insisting this is not legal, but have been unable to find straightforward documentation. Can someone point me to unambiguous documentation of this?


问:
MVC URL formatting/design
In refactoring a lot of MVC code, I have run into an issue with my URL design. For example, let's say we have a Venue object

```<code>public class Venue
{
    public long ID { get; set; }
    public List<Event> Events { get; set; }
}
</code>```

and an Event object

```<code>public class Event
{
    public long ID { get; set; }
    public Venue Venue { get; set; }
}
</code>```

So my initial set up was to have an action set up in the EventController like

```<code>public ActionResult List (long? ID) // http://example.org/API/Events/List/12
</code>```

where the ID specified the Venue, so it would return a list of events for that venue. If an ID is not specified, it returns a list of all events. This results in a confusing URL, because the ID parameter is ambiguous and misleading.

I then thought to change it to

```<code>public ActionResult List (long? VenueID) // http://example.org/API/Events/List?VenueID=12
</code>```

which makes a lot more sense and is more clear.

An even cleaner URL would exist if the action was moved to the VenueController and set up like

```<code>public ActionResult Events (long? ID) // http://example.org/API/Venue/12/Events
</code>```

as the ID would clearly specify the Venue's ID. The issue with this URL is that you are primarily dealing with Event objects in the VenueController, which seems wrong.

I have been leaning towards the first option (http://example.org/API/Events/List?VenueID=12) because, even though the other option is cleaner, it seems like I should keep the Event pages (as I view this List page as more related to the Event object) in the EventController. Any recommendations?

答:
Your best answer is going to be: Decide what you want it to look like, then modify the routing to match.

You can customize how the routing engine processes URLs.  See here for examples.  Our website uses MVC, but you wouldn't be able to tell it from the URLs.

In your specific case, I'd suggest making a route which looks for the pattern "Venue/{id}/Events" and routes it to the Event controller.

Title: MVC URL formatting/design


问:
Is there a name for when a sales team irresponsibly promises non-existent features?
It's a common issue to see a company's sales team promise new features in order to close a sale. Many times these new features are still in development or are still being designed. Sometimes features are sold before the development team even knows about them.

If the customer understands the features are not yet implemented this can help guide the product's design. However, if the sales team promises these features with an uninformed time frame it can put significant amounts of stress on the developers who are charged by management to meet the deadlines.

Additionally, sometimes non-existent features are sold to customers as being either completed or near completion when development may not even be aware of the requirements yet (legal/ethical issues notwithstanding).

Is there a word or phrase that can be used to describe the uninformed/irresponsible/unethical applications of this practice?

It's similar to feature creep, but occurs before development or design.

答:
"Normal"

Keep in mind that sales teams are there to ... sell the product you wrote. They are naturally adapting to client demand and selling features that their (and yours!) clients need.  You actually want them doing this; it means that revenue is coming in the door and that your product is staying relevant to market needs.

I'll note that this can be related to vapor-ware, in which things are promised and promised but never delivered.  But there's a nuance behind that term that's not applicable to your question.

It's only an issue when delivery schedules aren't clearly defined or when the sales team over-promises on what can be delivered.  And while this creates stress for the developers involved in implementing those visions, ultimately it isn't their issue to resolve.  Upper management and product development management needs to work with the sales management to define when features can be advertised for sale and what schedules can be committed to.  Over-commitment tarnishes the company's image and is rightfully an issue for upper management to resolve.

Generally speaking, Developers (and Sales...) like to see a Design => Sell => Develop approach to sales and marketing.  Development has an idea of what might be flogged to the potential clients and Sales has an idea of when idea XYZ could actually be delivered if the potential client is interested.

There are cases where you'll see Sell => Design => Build, and this path is more likely to cause problems for the development team.  On the one hand, if the Sales team really understands the code base* then this can be an effective route to new contracts.  On the other hand, there is a greater chance to over-promise what can actually be delivered in a reasonable period of time.  Your question calls out some of the keys in determining how well this approach will work out.

*Yes, I know the cynical reply of "that never happens." But it can occur when one of the founders of a firm was highly technical and has moved into a role driving more sales.  There is also whole branch of "Technical Sales" personnel as well.


答:
I would recommend picking up Michael Feathers' Working Effectively with Legacy Code. In the book he defines "legacy code," somewhat interestingly to me, as "code without tests". The impression that I get is that your situation is pretty common: not only is your code not covered by tests, but in its current state it can't be covered by tests. The book describes some ways to deal with this situation. I won't list them here because they a) are complicated and b) aren't committed to my memory.

What I do if I were you is put some of the code in a "test harness". At first I wouldn't even worry about adding meaningful tests at all. Just get to the point where you have one or two unit tests testing trivial parts of the system. Once you have that little beachhead, from there it's mostly a matter of expanding on the work you've already done (not to say that that is easy). It may feel pointless in the beginning, but a few semi-meaningless tests are better than no tests at all, and maybe after some gradual refactoring you'll have some meaningful tests.

Title: Using only UI testing. Is that Ok?

Body:
I am a sole developer working with an offshore employer. I do realize the importance of unit testing (although haven't practiced before) but currently, the code hasn't ever been tested. The problem with the code is that it isn't what I call "been moduled well", some parts are really messy, extensive use of globals and the code doesn't really show loose coupling. If I am not wrong, the code might require heavy refactoring before being able to be unit tested. Also, it seems the employer, isn't quite interested in testing. He rather suggests to spend this time in building features.

So what I suggested to him is UI testing. Because UI testing is something we do every time, testing features, clicking, checking if something is  not broke, it made sense to both of us to use it to automate the process of checking features and save us time.

Since I have never done UI testing before, I don't know what possible disadvantages might be associated with using just UI testing alone or will it be much beneficial at all?


答:
As you describe it, there is nothing wrong with this technique of selling.

It only becomes similar to feature creep when the sales team promise things that cannot be delivered in the time frame they promise them in.

When this happens, the software development process can often fall by the wayside, things must be delivered quickly, and this can lead to

bad code

bad design

not enough (or no!) testing

Sadly, this is very common.

Title: Is there a name for when a sales team irresponsibly promises non-existent features?

Body:
It's a common issue to see a company's sales team promise new features in order to close a sale. Many times these new features are still in development or are still being designed. Sometimes features are sold before the development team even knows about them.

If the customer understands the features are not yet implemented this can help guide the product's design. However, if the sales team promises these features with an uninformed time frame it can put significant amounts of stress on the developers who are charged by management to meet the deadlines.

Additionally, sometimes non-existent features are sold to customers as being either completed or near completion when development may not even be aware of the requirements yet (legal/ethical issues notwithstanding).

Is there a word or phrase that can be used to describe the uninformed/irresponsible/unethical applications of this practice?

It's similar to feature creep, but occurs before development or design.


问:
Getting practicality of PHP from Ruby or Python
I have a rather odd problem. I love the practicality of PHP - specifically that I can fairly safely assume that on any random server I'll have access to the MySQL libraries, and that I can go between PHP/HTML with <? and ?>. That said, I find the language atrocious - Ruby and Python are considerably more expressive, yet since they're not web-specific, they lack both of those features - at least last I used them both.

So my question is, is there some way to get the practicality of PHP from Ruby or Python (specifically the two issues I mentioned)? If not, is there some other language that doesn't feel like a C/C++ parser gone wrong?

答:
Unless you're dealing with a large legacy codebase, it's relatively easy to avoid PHP's warts. Most hosts will have PHP 5.3 and, except for a few of the gems from 5.4, you're going to get a lot of functionality. </p>

<p>What specifically about PHP is it that you are trying to avoid? </p>

Body:
Unless you're dealing with a large legacy codebase, it's relatively easy to avoid PHP's warts. Most hosts will have PHP 5.3 and, except for a few of the gems from 5.4, you're going to get a lot of functionality.

What specifically about PHP is it that you are trying to avoid?


答:
This is a kind of organizational anti-pattern. I've heard a few terms for this practice:

Sales-Driven Development

Sales-Oriented Programming

Coding by the seat of your pants

Although there's nothing fundamentally wrong with this, and occasionally it can be very good for the business, if over used, it degenerates pretty rapidly into a variety of well known problems: feature bloat, big ball of mud, magic pushbuttons, etc.


问:
Retrieving maximum value from a range in unsorted array
I have an unsorted array. I have queries in which I give a range and then the maximum value from that range has to returned.
For example:

```<code>array[]={23,17,9,45,78,2,4,6,90,1};
query(both inclusive): 2 6
answer: 78
</code>```

Which algorithm or data structure do I construct to quickly retrieve maximum value from any range. (There are a lot of queries)

EDIT:
This is indeed a simple version of the actual problem. I can have the array size as large as 100000 and the number of queries upto 100000. So I definitely require some preprocessing which'll facilitate a fast query response.

答:
To complement ngoaho91's answer.

The best way to solve this problem is using the Segment Tree data structure. This allows you to answer such queries in O(log(n)), that would mean the total complexity of your algorithm would be O(Qlogn) where Q is the number of queries. If you used the naive algorithm, the total complexity would be O(Qn) which is obviouslly slower.

There is, however, a drawback of the usage of Segment Trees. It takes up a lot of memory, but a lot of times you care less about memory than about speed.

I will briefly describe the algorithms used by this DS:

The segment tree is just an special case of a Binary Search Tree, where every node holds the value of the range it is assigned to. The root node, is assigned the range [0, n]. The left child is assigned the range [0, (0+n)/2] and the right child [(0+n)/2+1, n]. This way the tree will be built.

Create Tree:

```<code>/*
    A[] -> array of original values
    tree[] -> Segment Tree Data Structure.
    node -> the node we are actually in: remember left child is 2*node, right child is 2*node+1
    a, b -> The limits of the actual array. This is used because we are dealing
                with a recursive function.
*/

int tree[SIZE];

void build_tree(vector<int> A, int node, int a, int b) {
    if (a == b) { // We get to a simple element
        tree[node] = A[a]; // This node stores the only value
    }
    else {
        int leftChild, rightChild, middle;
        leftChild = 2*node;
        rightChild = 2*node+1; // Or leftChild+1
        middle = (a+b) / 2;
        build_tree(A, leftChild, a, middle); // Recursively build the tree in the left child
        build_tree(A, rightChild, middle+1, b); // Recursively build the tree in the right child

        tree[node] = max(tree[leftChild], tree[rightChild]); // The Value of the actual node,
                                                            //is the max of both of the children.
    }
}
</code>```

Query Tree

```<code>int query(int node, int a, int b, int p, int q) {
    if (b < p || a > q) // The actual range is outside this range
        return -INF; // Return a negative big number. Can you figure out why?
    else if (p >= a && b >= q) // Query inside the range
        return tree[node];
    int l, r, m;
    l = 2*node;
    r = l+1;
    m = (a+b) / 2;
    return max(query(l, a, m, p, q), query(r, m+1, b, p, q)); // Return the max of querying both children.
}
</code>```

If you need further explanation, just let me know.

BTW, Segment Tree also supports update of a single element or a range of elements in O(log n)

Body:
To complement ngoaho91's answer.

The best way to solve this problem is using the Segment Tree data structure. This allows you to answer such queries in O(log(n)), that would mean the total complexity of your algorithm would be O(Qlogn) where Q is the number of queries. If you used the naive algorithm, the total complexity would be O(Qn) which is obviouslly slower.

There is, however, a drawback of the usage of Segment Trees. It takes up a lot of memory, but a lot of times you care less about memory than about speed.

I will briefly describe the algorithms used by this DS:

The segment tree is just an special case of a Binary Search Tree, where every node holds the value of the range it is assigned to. The root node, is assigned the range [0, n]. The left child is assigned the range [0, (0+n)/2] and the right child [(0+n)/2+1, n]. This way the tree will be built.

Create Tree:

/*
    A[] -> array of original values
    tree[] -> Segment Tree Data Structure.
    node -> the node we are actually in: remember left child is 2*node, right child is 2*node+1
    a, b -> The limits of the actual array. This is used because we are dealing
                with a recursive function.
*/

int tree[SIZE];

void build_tree(vector<int> A, int node, int a, int b) {
    if (a == b) { // We get to a simple element
        tree[node] = A[a]; // This node stores the only value
    }
    else {
        int leftChild, rightChild, middle;
        leftChild = 2*node;
        rightChild = 2*node+1; // Or leftChild+1
        middle = (a+b) / 2;
        build_tree(A, leftChild, a, middle); // Recursively build the tree in the left child
        build_tree(A, rightChild, middle+1, b); // Recursively build the tree in the right child

        tree[node] = max(tree[leftChild], tree[rightChild]); // The Value of the actual node,
                                                            //is the max of both of the children.
    }
}

Query Tree

int query(int node, int a, int b, int p, int q) {
    if (b < p || a > q) // The actual range is outside this range
        return -INF; // Return a negative big number. Can you figure out why?
    else if (p >= a && b >= q) // Query inside the range
        return tree[node];
    int l, r, m;
    l = 2*node;
    r = l+1;
    m = (a+b) / 2;
    return max(query(l, a, m, p, q), query(r, m+1, b, p, q)); // Return the max of querying both children.
}

If you need further explanation, just let me know.

BTW, Segment Tree also supports update of a single element or a range of elements in O(log n)


答:
You don't need to contact a lawyer for every question about law! Some issues are very straightforward.

You don't say where you live, which makes it hard to give an appropriate reference. Here's one for where I live: a UK government website on intellectual property law. Summary quote

You may need to get permission from a copyright owner if you wish to copy written work [including software] in any way, unless any exceptions apply [they don't in your case]

Search for a website from your own government for a reference for your own country.

Going beyond the question. You might want to ask a lawyer to write an agreement for the original author to sign, to be sure it will stand up in court, or just choose an unrestrictive open source license like MIT.

Title: Modify then sell another person's code


问:
Will real world applications ever need a 128-bit flat address space?
This is a bit "one megabyte should be enough for anyone", but...

A 64-bit flat address space allows up to 4.3ish billion times more space than a 32-bit address space. That's 17,179,869,184 GiB.

Obviously, the transition from 8 bits to 16 bits was pretty quick (I'm viewing things in a teen-during-the-80s way, ignoring all those mainframes and minis because they couldn't run a port of Elite). The transition from 16 bits to 32 bits took a bit longer, and 32 bits actually lasted quite a while.

Now we have 64 bits, would it be stupid to say "17,179,869,184 GiB should be enough for anyone"?

This is a programmers question because I really have the programming viewpoint in mind. Even if a computer some day has a seemingly infinite amount of working memory, that doesn't mean that applications will need to see a seemingly infinite flat address space.

Basically, can we programmers breath a sigh of relief and say "well, whatever integers or floats may do, at least I don't have to worry about my pointers growing any more?".

答:
20 years ago, there were 2 billion less people on the planet and most computer systems had addressable memory that could be measured in kilobytes. Today, the population of the world increases at the same rate and the number of computer users increases exponentially every year. </p>

<p>It is true that very few systems need a full 64 byte address space. Some systems store terabytes of information every day, however. This has been possible due to the increase of computer users and internet speeds. We can already support 10 GB/s internet speeds after only 23 years after HTTP was invented. At this rate I think it would be foolish to not expect 1 TB/s or higher internet speeds in 50 years. When we can all move data this fast, there will be more data to be stored while more people will exist to store this data and it is almost inevitable that there will need to be another widespread transition into a 128 bit system, and eventually 256 and 512 bit. </p>

Body:
20 years ago, there were 2 billion less people on the planet and most computer systems had addressable memory that could be measured in kilobytes. Today, the population of the world increases at the same rate and the number of computer users increases exponentially every year.

It is true that very few systems need a full 64 byte address space. Some systems store terabytes of information every day, however. This has been possible due to the increase of computer users and internet speeds. We can already support 10 GB/s internet speeds after only 23 years after HTTP was invented. At this rate I think it would be foolish to not expect 1 TB/s or higher internet speeds in 50 years. When we can all move data this fast, there will be more data to be stored while more people will exist to store this data and it is almost inevitable that there will need to be another widespread transition into a 128 bit system, and eventually 256 and 512 bit.


答:
Are you looking for something like Python Server Pages?</p>

```<code><html>
<%
  import time
%>
Hello world, the time is: <%=time.strftime("%Y-%m-%d, %H:%M:%S")%>
</html>
</code>```

Title: Getting practicality of PHP from Ruby or Python

Body:
I have a rather odd problem. I love the practicality of PHP - specifically that I can fairly safely assume that on any random server I'll have access to the MySQL libraries, and that I can go between PHP/HTML with <? and ?>. That said, I find the language atrocious - Ruby and Python are considerably more expressive, yet since they're not web-specific, they lack both of those features - at least last I used them both.

So my question is, is there some way to get the practicality of PHP from Ruby or Python (specifically the two issues I mentioned)? If not, is there some other language that doesn't feel like a C/C++ parser gone wrong?

Body:
Are you looking for something like Python Server Pages?

<html>
<%
  import time
%>
Hello world, the time is: <%=time.strftime("%Y-%m-%d, %H:%M:%S")%>
</html>


问:
create function of object prototype
I am reading "Javascript : The good Parts" to improve my Javascript bases and knowledge. I was reading stuff about prototype and I encountered in this function :

```<code>var stooge = { ... }
if(typeof Object.create !== 'function'){
   Object.create = function(o) {
   var F = function () {};
   F.prototype = o;
   return new F();
   };
}
var another_stooge = Object.create(stooge);
</code>```

I didn't really get the meaning and the benefit of creating this function.

答:
It's only a shim for the standard Object.create function which isn't available in some browsers (yes, you guessed which one).

Note that it's not complete : it doesn't do everything that is done by Object.create but it's probably enough for the author.

As for why the author wanted to use Object.create instead of a explicit prototype based OOP, it's probably because it's a little simpler.

Title: create function of object prototype


问:
Web hosting deciding to pay for hosting or host your own?
Is there a guide out there on how to choose when to pay for web hosting vs. hosting your own? Assuming that root access is a must I would like to compare things like cost, scalability and personal stress.

Here is what I could come up with.

Paying for web hosting:

Benefits:

Much cheaper for a small scale.  I assume anything under $50 a month would be cheaper than paying for the bandwidth of hosting.

No stress in dealing with power outages, server restarts or internet going down.

For the most part less busy work involved with setting up.

Negatives:

Cost goes way up when higher specs are needed (for example monthly cost triples with ability to use 8gb of ram that you can buy for $90 ).  This means you have to target a particular ram usage and monitor so your instance stays within the threshold.

root access for the most part is a premium.

You may get tied into a vendor specific deployment process.

Hosting on own :

Positives:

100% control of specs and software.

When you get past paying for the bandwidth you get much more bang for your buck by building your own machine.

Negatives:

Doesn't make financial sense if bandwidth costs are more than web hosting costs.

Having to deal with power outages, server restarts or internet going down.

I think the best of both worlds would be if there was a place that dealt with bandwidth, power outages and server restarts but you provided your own server.  Kind of like a 24 hour day care for a server.  Does anything like that exist?

答: Would you consider leasing a VPS paying for hosting or hosting your own? I find it's the best of both worlds, and these days it's quite cheap. I've had better than 99.99 uptime in the last three years, which is also incredibly good.</p>


答:
The 24x7 care are looking for is called Managed Hosting -- many firms exist that do that in various capacities for various fees. I'll note it is nice but it still won't necessarily replace having a good, knowledgeable engineer who knows your application and stack around to put out fires -- the host often can do little more than tell you your database server has locked up but they likely can't fix it.

In 2013, if you are building an internet facing application, there is very, very little reason to burden yourself with hosting the production instances yourself unless you happen to have in your possession a data center with all the typical niceties they come with like redundant power, redundant internet connections, 24x7 skilled labor around to support your box. If you've got those you'd also probably appreciate what stuff like that costs and why it seems dramatically more expensive.

Title: Web hosting deciding to pay for hosting or host your own?

Body:
Is there a guide out there on how to choose when to pay for web hosting vs. hosting your own? Assuming that root access is a must I would like to compare things like cost, scalability and personal stress.

Here is what I could come up with.

Paying for web hosting:

Benefits:

Much cheaper for a small scale.  I assume anything under $50 a month would be cheaper than paying for the bandwidth of hosting.

No stress in dealing with power outages, server restarts or internet going down.

For the most part less busy work involved with setting up.

Negatives:

Cost goes way up when higher specs are needed (for example monthly cost triples with ability to use 8gb of ram that you can buy for $90 ).  This means you have to target a particular ram usage and monitor so your instance stays within the threshold.

root access for the most part is a premium.

You may get tied into a vendor specific deployment process.

Hosting on own :

Positives:

100% control of specs and software.

When you get past paying for the bandwidth you get much more bang for your buck by building your own machine.

Negatives:

Doesn't make financial sense if bandwidth costs are more than web hosting costs.

Having to deal with power outages, server restarts or internet going down.

I think the best of both worlds would be if there was a place that dealt with bandwidth, power outages and server restarts but you provided your own server.  Kind of like a 24 hour day care for a server.  Does anything like that exist?


答:
I would say "paid" hosting has many many different flavors (shared, dedicated virtual, dedicated, etc..). And those comparisons are most likely available all over. When comparing that to hosting your own (I'm assuming in your home / garage), there is no comparison for any real world application if uptime, security and reliability are a concern.

Hosting your own machine is okay for information websites that wont sue you for going down, but you take on all the risk for uptime and security. both of which can drive your clients away (if that's your model), or compromise your customers data (if you're hosting their data).

you can get a basic hosting plan for very cheap, even free, and will require much less pain so it doesnt really make sense

if you want full control and 100% of the resources, then I would recommend getting a dedicated box from a hosting company, generally you just have to pay for the OS license if that even applies.. then you can RDP in and do whatever you want to it, you'll still have to worry about local security, but the power company wont be shutting you down during the day for their normal maintenance.

Amazon offers some free virtual instances, and I would recommend starting there.. the machines are pretty weak, but the price justifies the performance you get.


答:
It's not the modification that's the problem -- modifications are of course your own work, and you own that part. The problem is the unmodified code, and the fact that you're basing your work on someone else's in the first place.

If your partner thinks it's okay to use someone else's work without permission, he doesn't understand what copyright means.

May you reprint a copyrighted book and sell it*, even with proper attribution? No.

May you re-record a copyrighted song and sell it*, even with proper attribution? No.

May you re-use copyrighted code and sell it*, even with proper attribution? No.

One has to wonder how your partner would feel about someone taking your code and selling it without permission.

*without permission of the author

Title: Modify then sell another person's code


答:
Overly optimistic scheduling is the term used by Steve McConnell in his book Rapid Development. He also uses the term wishful thinking.

McConnell writes (with supporting evidence) that an overly optimistic schedule actually makes the project later.

I had a bad experience with schedule pressure once. A customer was unhappy with a timeline, even though it was in line with similar projects. We hired a contract programmer with the hopes of shortening the timeline. The customer added many more features. (There was no review of "hey, the project is taking too long, and now you want more features?") The contract programmer was not as good as we had hoped, and I spent lots of time fixing bugs and design problems.

I don't want to live through that experience again as much as I can help it.

Yes, you should look for creative ways to help the sales team and management meet their commitments. Sales pay your salary.

Yes, you should be politely and firmly speak up about unrealistic schedules. The schedule may not change, but you did what you could. You owe it to your management to give them your best professional opinion, even when it is not what they want to hear.


答:
My organization would call this violating safe harbor, or selling based on forward-looking statements.

Every press release and sales presentation comes with a safe harbor statement, which boils down to, "Make your purchasing decisions based on our current features, since we don't guarantee delivery on features that haven't been released yet." Our salespeople are obligated to never promise new features on any given date, and if they do, they do so in contradiction to the safe harbor statement.


问:
Can/should the Single Responsibility Principle be applied to new code?
The principle is defined as modules having one reason to change. My question is, surely these reasons to change are not known until the code actually starts to change?? Pretty much every piece of code has numerous reasons why it could possibly change but surely attempting to anticipate all of these and design your code with this in mind would end up with very poor code. Isn't it a better idea to only really start to apply SRP when requests to change the code start coming in? More specifically, when a piece of code has changed more than once for more than one reason, thus proving it has more than one reason to change. It sounds very anti-Agile to attempt to guess reasons for change.

An example would be a piece of code which prints a document. A request comes in to change it to print to PDF and then a second request is made to change it to apply some different formatting to the document. At this point you have proof of more than a single reason to change (and violation of SRP) and should make the appropriate refactoring.

答:
I think the definition of SRP as "having one reason to change" is misleading for exactly this reason. Take it exactly at face value: the Single Responsibility Principle says a class or function should have exactly one responsibility. Having only one reason to change is a side effect of only doing one thing to begin with. There's no reason you can't at least make an effort toward single responsibility in your code without knowing anything about how it might change in the future.

One of the best clues for this sort of thing is when you're choosing class or function names. If it isn't immediately apparent what the class should be named, or the name is particularly long/complex, or the name uses generic terms like "manager" or "utility", then it's probably violating SRP. Similarly, when documenting the API, it should become rapidly apparent if you're violating SRP based on what functionality you're describing.

There are, of course, nuances to SRP that you can't know until later on in the project - what seemed like a single responsibility turned out to be two or three. These are cases where you'll have to refactor to implement SRP. But that doesn't mean that SRP should be disregarded until you get a change request; that defeats the purpose of SRP!

To speak directly to your example, consider documenting your print method. If you'd say "this method formats the data for printing and sends it to the printer," that and is what gets you: that's not a single responsibility, that's two responsibilities: formatting and sending to the printer. If you recognize this and split them up into two functions/classes, then when your change requests came along, you'd already have only one reason for each section to change.


问:
Encoding to ASCII where original encoding of string is not known
Given that we do not know the encoding of a string what is the best way to make sure that it is transformed to say ASCII? Also in such situations we are willing to accept potential loss of data.</p>

答:
I would follow these steps:

Detect the original character set.  Jimmy Hoffa's suggestion of the Mozilla character set detectors is as good as any. Google becomes your friend here too.

Select top one or two choices for character set.

Convert to ASCII

Convert ASCII string back to assumed character set

Compare original string to old to determine amount of information lost during conversion.

You may want to indicate strings that didn't convert correctly along with how far they were off by.  That and the assumed source character set may facilitate future conversions.


答:
The cynic in me wants to say "Consulting", but that isn't entirely fair, because there are many consultants out there who are honest.

It is incredibly common in software consulting to sell something you haven't built yet, especially if you are doing bespoke, green-fields projects. Many organisations sell consulting services around their product, which invariably include customizations or unique features (SAP, Microsoft Dynamics, Microsoft SharePoint, etc).

It sounds to me like you are facing the frustration that comes from having sales people who are too disconnected from the technical team. There are many ways to improve this situation, but one we are starting at my workplace is "learning sessions" where different people teach the rest of the team about their job. Developers can learn about sales, and the challenges therein; Salespeople can learn about the challenges of software development. Another technique is to have the salesperson sit with the people whose services they sell. It breaks down the "us vs them" boundaries, and encourages everyone to play for the same team.


问:
How To Become More Comfortable with the Technical Terms
I have been working freelance for a few years, and before that I worked as an entry-level coder for a non-technical company. I "understand" how delegates, and MVC, and how to make an app and make it work, but I have done a few interviews recently and they are throwing questions at me that I don't know the answers to. These are questions that I think I should know the answers to, but I basically haven't ever had to use the technical language. Needless to say I feel very stupid when this happens but I don't know how to prepare / remedy this problem without going back to Comp Sci 101. It's like I can do the work, but I don't know what they're talking about.

Any suggestions would be much appreciated.

答:
Jargon familiarity is something that should improve as you get more experienced, but even veterans will run into jargon problems sometimes -- not just at interviews, but as part of daily interaction with clients and even team members.

The most important skill for such cases is the ability to ask for clarification.  Even if you think you should know the answer, you need to learn not to let that stop you.  Even if you think you probably do know the answer, you might want to consider asking anyway, to make sure you're tracking properly -- misunderstandings can be costly.

Learning to ask such questions gracefully will come with practice, also, but that is a skill of secondary importance...

As part of the basic research that is helpful before any interview, you can try brushing up on jargon relevant to the particular job.  However, I would not advise giving much effort to or reliance on such cramming, as that kind of knowledge is shallow and fragile.  Other elements of such research (such as what the company does) are likely to be more important.

Finally, if you feel you need a general refresher on CS101, you have a couple of options.  You can go to the library (or to Amazon, or the Internet), locate a good text or three, and do some self-study on whatever subjects you feel weak on.  Or, you could look into some local institution that offers continuing education, and actually take a refresher CS course or two.


问:
Is this solution RESTful and secure?
Our product registers new players on our service, and we've chosen to host it on Azure (we're using .NET) and we wanted it to be stateless (for scalability) and relatively secure.

Since this is the first REST WS I'm writing, I wanted to get some feedback on whether or not it's a solid solution.

Some presumptions to know about our app:

Users are logged into the service anonymously, without requiring a password from a user

The WS must be completely stateless to allow horizontal scaling

We're connecting using HTTPS (SSL) to prevent 3rd party snooping

EDIT:

We target for native iOS/Android devices

Our main concern is making sure only non-tampered clients are able to send requests

And the abstract authentication process:

The client creates a simple hash (UDID:Timestamp) and encrypts it using the timestamp with some basic algorithm (for example, secret key is every 2nd character from the hash)

The client sends his UDID, Timestamp & hash to the server

The server rebuilds the hash and decrypts the encrypted hash sent from the user

If the two are equal - we know that it was actually sent from our client (and hopefully not from a malicious sender)

Any input/suggestions would be great - obviously since it's the first time I'm handling this issue I might have designed it incorrectly.

Thanks!

2nd update:

Reading the security specs for OAuth, it seems that there is no real answer to my question - since the client and server must know the secret keys and the client is locally stored on our users' mobile devices (as opposed to a web app).

From the OAuth security guide (http://hueniverse.com/oauth/guide/security/):

When implementing OAuth, it is critical to understand the limitations of shared secrets, symmetric or asymmetric. The client secret (or private key) is used to verify the identity of the client by the server. In case of a web-based client such as web server, it is relatively easy to keep the client secret (or private key) confidential.

However, when the client is a desktop application, a mobile application, or any other client-side software such as browser applets (Flash, Java, Silverlight) and scripts (JavaScript), the client credentials must be included in each copy of the application. This means the client secret (or private key) must be distributed with the application, which inheritably compromises them.

This does not prevent using OAuth within such application, but it does limit the amount of trust the server can have in such public secrets. Since the secrets cannot be trusted, the server must treat such application as unknown entities and use the client identity only for activities that do not require any level of trust, such as collecting statistics about applications. Some servers may opt to ban such application or offer different protocols or extensions. However, at this point there is no known solution to this limitation.

答:
The key about REST is that you are using the inherent features in http:

GET: for simply retrieving data

POST: for inserting a new data point

PUT: for updating a data point

DELETE: for deleting a data point

Some of the other guidance is that your urls should be intuitive, ie if your url for players is http://example.com/api/player then a sensible way for exposing their last history of scores might be http://example.com/api/player/1/scores (ie the scores for player id 1).

As for security, what you have read from the OAuth spec is very true... if you are embedding some sort of private key in a binary that other people can get their hands on, you cannot assume it to be entirely private. I would suggest that if you have any sort of private key in your code, you set it up so that you can expire it, and then push out an update to change it. By all means, take the opportunity to protect it with encryption and all the rest, but make it easy to disable if it is hacked. The reality is that twitter et al suffer this same challenge, where every now and then the secret keys for their official apps are discovered and posted on the internet, and they have to update their apps.

Title: Is this solution RESTful and secure?


问:
How do I include the copyright/license for a library if I use on 1 function?
How do I include the copyright/license for a library if I use on 1 function?

Say if I have a class that I have taking 1 function from another library:

```<code>class MyClass {
    ...
    public function someOtherLibrariesFunction() {}
}
</code>```

And the at the top of the file I took the function from it says:

```<code>/*
 * This file is part of the Other Library package.
 *
 * (c) James Smith <j.smith@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
</code>```

And the LICENSE file:

```<code>Copyright (c) 2004-2013 James Smith

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

...standard as is warranty...
</code>```

So my understanding is I would have to have a copy of the LICENSE file included with my code, and I would also somehow point out the exact function it it applies to?

答:
I would include a file like "LICENSE_CodeFile_Function.txt", and then as a comment above the function, include an attribution, ie "This function is from ..... and is Copyright (c) 2004-2013 James Smith... please see the license ....."

In general, as long as you include the license in your distribution, and are very clear about where you got the code from, and who owns it etc, ie not trying to pass it off as your own, you should be fine.

Of course, for licenses like GPL, that require you to release your entire codebase under the same license, it is a little bit different.


问:
What's the dominant naming convention for variables in PHP: camelcase or underscores?
The consensus seems to be that one should follow the convention of the platform they're developing for. See:

Underscore or camelcase?

Naming conventions: camelCase versus underscore_case?

However, PHP doesn't seem to strictly follow any convention internally (no surprises there), even for methods and functions (e.g. mysqli::set_local_infile_default,
PDOStatement::debugDumpParams); however, underscores seem to be dominant in function names.

However, what I couldn't find was this: what's the dominant naming convention for variables in PHP?

答:
Personally, this can go either way. Some programmers prefer the CamelCase way of writing, others prefer underscore... So asking a question like this posses it's irrelevance as each programmer will have their own different opinion... Personally, I have the habit of doing  both depending on the situation...

Situation one:

You have joined a programming team and have joined an on-going project, you notice that an example variable is set out:

```<code>$theString = "This is a camelcase example";
</code>```

But you have a preferred style of:

```<code>$the_string = "This is not a camelcase example";
</code>```

in a situation like this, it would be best to keep to camelcase.

Situation two:

You wish to start a project solo.

In this sort of case... It just goes down to what you feel comfortable with, bear in mind bad practices in terms of:

```<code>$theString = "This is a sample String";
$the_string = "This is another sample string within the same project";
</code>```

This can easily cause unexpected output.. Just bear that in mind.

Body:
Personally, this can go either way. Some programmers prefer the CamelCase way of writing, others prefer underscore... So asking a question like this posses it's irrelevance as each programmer will have their own different opinion... Personally, I have the habit of doing  both depending on the situation...

Situation one:

You have joined a programming team and have joined an on-going project, you notice that an example variable is set out:

$theString = "This is a camelcase example";

But you have a preferred style of:

$the_string = "This is not a camelcase example";

in a situation like this, it would be best to keep to camelcase.

Situation two:

You wish to start a project solo.

In this sort of case... It just goes down to what you feel comfortable with, bear in mind bad practices in terms of:

$theString = "This is a sample String";
$the_string = "This is another sample string within the same project";

This can easily cause unexpected output.. Just bear that in mind.


答:
I think this is very common. It's surprising how different teams and people use completely different jargon but actually mean the same thing. One person might say "Make a web request" and someone else will say "Send a HTTPS GET" and they both mean the same thing, but they don't understand each other.

The best thing to do is to ask to rewind the conversation back to before you got lost. You need to start again back at the point when you both understood each other, and then start adding complexity from there. They might even be talking about internal system names which can be really confusing. You need to ask for clarification of terms, technologies and acronyms - once you say "Oh you said X, I call it Y", you'll be in a much better position, and they should respect that, and it actually shows good communication skills.

I've found that acronyms are the worst... just ask them "Sorry, what do you mean by XYZ"?

Title: How To Become More Comfortable with the Technical Terms

Body:
I have been working freelance for a few years, and before that I worked as an entry-level coder for a non-technical company. I "understand" how delegates, and MVC, and how to make an app and make it work, but I have done a few interviews recently and they are throwing questions at me that I don't know the answers to. These are questions that I think I should know the answers to, but I basically haven't ever had to use the technical language. Needless to say I feel very stupid when this happens but I don't know how to prepare / remedy this problem without going back to Comp Sci 101. It's like I can do the work, but I don't know what they're talking about.

Any suggestions would be much appreciated.


问:
Make the lines hide (logically speaking) in applets
I am developing an application where I draw large number of lines (color is given as black) and update them where I need to remove them from screen.

I thought of making their color to match with the background so that I can make them hide. It seems to be simple and works but in the practical sense I have 10000 points and almost more than 20000 lines to be drawn and as most the line overlap or cross each other it is so disgusting the view.

So I need some kind of function to actually remove those selected lines between two known points from screen. Even I have a problem with the background color I can match the exact background default color of the applets. Can anyone suggest me solution or the color?

答:
To draw usingbackground color can use http://docs.oracle.com/javase/6/docs/api/java/awt/Component.html#getBackground() which returns the background color, this can be set to the graphics object you are painting to.

Use double buffering, first clear the area by making a rectangle using default color :

g.setColor(backgroundColor);
   g.fillRect(0, 0, fullWidth, fullHeight);

and then draw only active lines. So no complicated algorithm, just start from a clean slate and draw only what is required

Refernece
http://docs.oracle.com/javase/6/docs/api/java/awt/Graphics.html#setColor(java.awt.Color)

fillRect(int x, int y, int width, int height) on same page

Double buffering is explained here
http://docs.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html

and https://stackoverflow.com/questions/4430356/java-how-to-do-double-buffering-in-swing you could make your own image to process off screen


问:
How to organize the quality testing of a large website?
I developed a pretty big website. I tested it myself to the best of my ability, but I cannot test all scenarios that my users may run in to.

I found a testing team in India, but they don't seem to have any systematic approach to testing website functionality. They test each individual page rather than the full process that user takes on website.

What processes or tools should I use to thoroughly test my website?

答:
Do you have unit testing and integration testing?

This alone is a good start. When you have enough code coverage (say 90%), you are pretty sure that the internals work as expected. It doesn't mean that the web application will work perfectly, but at least, it shows that it's not totally broken, and even if, for example, you forget to validate user input at the step when the form was just submitted, at least the invalid data has low chances to find itself in the database: the unit-tested business layer will take care of invalid input.

Do you have automated testing?

Tests done manually are not only subject to human mistakes, but also difficult to do. If I know that an automated tool will spend ten seconds testing something, I'm more incline to run it very often, for example before every commit, then if the test consists of wasting two minutes of my time logging in, going to different pages, filling the forms, etc.

Do you have testers?

Once you have enough code coverage with unit tests and automated testing for some basic scenarios, the ones which cannot be easily automated should be handled by testers, i.e. persons whose work is specifically to:

test scenarios which are too complicate for automated testing,

try to break the application by feeding it with crazily invalid input, using it in a non-ordinary way, etc., eventually proving that unit and integration tests, as well as automated and manual test scenarios are insufficient.


问:
OOP (php) for beginners - some unclarities
I started reading some tutorials about OOP, because I want to learn the basics.

I have a question about it. I understand how you can have a object "Car" and give it a color like this $oCar->setColor("white");

But there are some things unclear to me. Let's say I have a database with all kinds of cars. What is the best way to create the object "car"? A SQL-query instead the class?

And the other question is: how can I output a list of all cars? Do I need to create a object called "Garage" with has only one method within that selects all the cars from the database? Or does this kind of method belong in the "Car" object?

答:
when you iterate your sql records in loop you can create objects then and put it for example to array

```<code>$array = array();
$sql = 'select yourFunction(params...)';
$db = new PDO('pgsql:dbname=yourDBname');

$cmd = $db->prepare($sql);
while ($row = $cmd->fetch(PDO::FETCH_ASSOC))
{
   $car = new Car();
   $car->setColor($row['color']);
   array_push($array, $car);
}
</code>```

you can also fetch object as STD object( stdClass is php's generic empty clas). In PDO you can fetch object also to class using

```<code> $stmt->setFetchMode(PDO::FETCH_CLASS, 'MyRow');
</code>```

PDO::FETCH_CLASS: returns a new instance of the requested class, mapping the columns of the result set to named properties in the class. If fetch_style includes > PDO::FETCH_CLASSTYPE (e.g. PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE) then the name of the class is determined from a value of the first column.

http://php.net/manual/en/pdostatement.fetch.php

There is also one technology called ORM for mapping sql.

https://stackoverflow.com/questions/108699/good-php-orm-library

Body:
when you iterate your sql records in loop you can create objects then and put it for example to array

$array = array();
$sql = 'select yourFunction(params...)';
$db = new PDO('pgsql:dbname=yourDBname');

$cmd = $db->prepare($sql);
while ($row = $cmd->fetch(PDO::FETCH_ASSOC))
{
   $car = new Car();
   $car->setColor($row['color']);
   array_push($array, $car);
}

you can also fetch object as STD object( stdClass is php's generic empty clas). In PDO you can fetch object also to class using

 $stmt->setFetchMode(PDO::FETCH_CLASS, 'MyRow');

PDO::FETCH_CLASS: returns a new instance of the requested class, mapping the columns of the result set to named properties in the class. If fetch_style includes > PDO::FETCH_CLASSTYPE (e.g. PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE) then the name of the class is determined from a value of the first column.

http://php.net/manual/en/pdostatement.fetch.php

There is also one technology called ORM for mapping sql.

https://stackoverflow.com/questions/108699/good-php-orm-library

OwnerDisplayName: Robert Podwika


答:
Let's say I have a database with all kinds of cars.

Yes, let's say you have that database in the memory of your computer (in-memory-database) and let's say that the interface to it are variables in PHP.

What is the best way to create the object "car"? A SQL-query instead the class?

Obviously an SQL query makes no sense here. First of all in PHP there is only one (and a half) way to create the object car and I'm sure you know that already:

```<code>new car;
</code>```

Second SQL does not understand PHP directly. So using an SQL query would not make any sense.

Object orientation requires you to separate things. For example the object itself should not care about how (and when) it is stored into the memory, on disk, into an SQL database or printed out on paper to be typed in later again. If the car object would need to take care about all this, it would less be a car object but more the super-store-exchange-object called "car".

So just take care that one class is responsible for what it is good with:

Single responsibility principle

And create new objects with new. You can find many hints how to make your code more simple and still improving it when writing OOP code in the post Don't be STUPID: GRASP SOLID! (Dec 2011; by NikiC).

Title: OOP (php) for beginners - some unclarities

Body:
I started reading some tutorials about OOP, because I want to learn the basics.

I have a question about it. I understand how you can have a object "Car" and give it a color like this $oCar->setColor("white");

But there are some things unclear to me. Let's say I have a database with all kinds of cars. What is the best way to create the object "car"? A SQL-query instead the class?

And the other question is: how can I output a list of all cars? Do I need to create a object called "Garage" with has only one method within that selects all the cars from the database? Or does this kind of method belong in the "Car" object?

Body:
Let's say I have a database with all kinds of cars.

Yes, let's say you have that database in the memory of your computer (in-memory-database) and let's say that the interface to it are variables in PHP.

What is the best way to create the object "car"? A SQL-query instead the class?

Obviously an SQL query makes no sense here. First of all in PHP there is only one (and a half) way to create the object car and I'm sure you know that already:

new car;

Second SQL does not understand PHP directly. So using an SQL query would not make any sense.

Object orientation requires you to separate things. For example the object itself should not care about how (and when) it is stored into the memory, on disk, into an SQL database or printed out on paper to be typed in later again. If the car object would need to take care about all this, it would less be a car object but more the super-store-exchange-object called "car".

So just take care that one class is responsible for what it is good with:

Single responsibility principle

And create new objects with new. You can find many hints how to make your code more simple and still improving it when writing OOP code in the post Don't be STUPID: GRASP SOLID! (Dec 2011; by NikiC).


答:
there are many ways to do this, one i did was:

create a table

create a class with the same name

create in both the same attributes/column names

create a mapper or a parent class for your car class and create functions to load in all objects. (with static class)

create a standard getters and setters or use magic __call method

so you can do Car::Find() for example, to return al cars.

my code:

```<code>//Code for parent class:
abstract class databaseObject {
public static function getClassName(){
    return get_called_class();
}

public static function find(){
    mysql_query("SELECT * FROM ".static::getClassName().";");
    $cars = array();
    while($row = mysql_fetch_assoc())
    {
        $car = new Car();
        $car->setAttributes($row);
        $cars[] = $car;
    }
    return $cars;

}

public function setAttributes(array $values) {
    foreach ($values as $attribute => $value) {
        if ($this->{$attribute . 'Exists'}()) {
            $this->{'set' . ucfirst($attribute)}($value);
        }
    }
    return $this;
}

    //this function gets called when a function of an object gets called which does not exist
    public function __call($name, array $args) {
    // get attribute
    if (0 === strpos($name, 'get')) {
        $property = lcfirst(substr($name, 3));
        if (property_exists($this, $property)) {
            return $this->$property;
        } else {
            return new Exception("Attribuate $property does not exist");
        }
    } elseif (0 === strpos($name, 'set')) {
        $property = lcfirst(substr($name, 3));
        if (property_exists($this, $property)) {
            $this->$property = $args[0];
            return $this;
        } else {
            throw new Exception("Cannot set attribute '{$property}', it does not exist");
        }
    }
    return new Exception("Method $name does not exist");
}
 }

class Car extends databaseObject {
    protected $color;
}
</code>```

offcourse you will probably want an already created database abstraction layer something like ORM/Doctrine

Body:
there are many ways to do this, one i did was:

create a table

create a class with the same name

create in both the same attributes/column names

create a mapper or a parent class for your car class and create functions to load in all objects. (with static class)

create a standard getters and setters or use magic __call method

so you can do Car::Find() for example, to return al cars.

my code:

//Code for parent class:
abstract class databaseObject {
public static function getClassName(){
    return get_called_class();
}

public static function find(){
    mysql_query("SELECT * FROM ".static::getClassName().";");
    $cars = array();
    while($row = mysql_fetch_assoc())
    {
        $car = new Car();
        $car->setAttributes($row);
        $cars[] = $car;
    }
    return $cars;

}

public function setAttributes(array $values) {
    foreach ($values as $attribute => $value) {
        if ($this->{$attribute . 'Exists'}()) {
            $this->{'set' . ucfirst($attribute)}($value);
        }
    }
    return $this;
}

    //this function gets called when a function of an object gets called which does not exist
    public function __call($name, array $args) {
    // get attribute
    if (0 === strpos($name, 'get')) {
        $property = lcfirst(substr($name, 3));
        if (property_exists($this, $property)) {
            return $this->$property;
        } else {
            return new Exception("Attribuate $property does not exist");
        }
    } elseif (0 === strpos($name, 'set')) {
        $property = lcfirst(substr($name, 3));
        if (property_exists($this, $property)) {
            $this->$property = $args[0];
            return $this;
        } else {
            throw new Exception("Cannot set attribute '{$property}', it does not exist");
        }
    }
    return new Exception("Method $name does not exist");
}
 }

class Car extends databaseObject {
    protected $color;
}

offcourse you will probably want an already created database abstraction layer something like ORM/Doctrine


问:
Best practice to sort then reverse, or write "backwards" comparator?
I wrote a comparator for a custom class of mine and when I ran my code I realised the output of my list of these objects was in the reverse order as to what I wanted. It was "ascending" as opposed to "descending". This was because I stuck to the spec of compare where a return value of less than 0 means the other object is less than this and so on.

To fix this I called the reverse method on my list, but I could've also changed the compare method so that it returns greater than 0 where the other object is less than this.

What is seen as the standard for this case and why?

答:
Use comparator with correct order for your application. Sorting and then reversing means that you are doing the sorting AND going through list again to reverse it.

When you are creating comparator, you are defining new ordering and YOU are difining what value is lesser and what higher. Eg. in reverse ordering of natural numbers, 10 is less than 9 even though in the usual ascending order 10 is greater than 9.


问:
Naming the project containing only interfaces
I've extracted interfaces from my repository classes, like ICustomerRepository, IProductRepository and so on. The project which contains the repositories is named X.DataAccessLayer. Should I call the project with the interfaces X.DataAccessLayerInterfaces, or what is better?

And I definitely have to keep the interfaces in a separate project (I have 2 projects with implementations of these interfaces).

答:
Use whatever name you can think of that correctly describes the contents and does not feel too long.

Personally, X.DataAccessLayerInterfaces feels too long for me, so I would probably opt for X.DataAccessInterfaces, but otherwise there is nothing wrong with it.


答:
The naming pattern also depends on your other projects. Depending on the contents of your implementation projects it could be something like this:

X.DataAccessLayer

X.DataAccessLayer.Sql

X.DataAccessLayer.Oracle

PS: I would drop 'Layer' as well, unless you have a mix of independent libraries and actual layers.

Title: Naming the project containing only interfaces

Body:
I've extracted interfaces from my repository classes, like ICustomerRepository, IProductRepository and so on. The project which contains the repositories is named X.DataAccessLayer. Should I call the project with the interfaces X.DataAccessLayerInterfaces, or what is better?

And I definitely have to keep the interfaces in a separate project (I have 2 projects with implementations of these interfaces).


答:
But there are some things unclear to me. Let's say I have a database with all kinds of cars. What is the best way to create the object "car"? A SQL-query instead the class?

SQL queries and classes are two completely independent concepts and they are not interchangeable.
You can't create objects out of SQL queries, but you can use an SQL query to retrieve the values for the properties of an object. There are two ways to go about this:

The class knows about the database and retrieves the values itself when you create a new object.

The class does not know about the database and relies on external code to provide the relevant values. These can come from a database or from elsewhere.

If you code it all yourself, the second way is easier, because you can split it up in more functions, which makes it easier to understand what each function does.
There are also lots of frameworks available that provide an ORM (Object Relational Model) component which does most of the hard work for you. There it depends on the framework architecture if the ORM component is based on the first or the second way.

And the other question is: how can I output a list of all cars? Do I need to create a object called "Garage" with has only one method within that selects all the cars from the database? Or does this kind of method belong in the "Car" object?

Although some ORM implementations do provide such methods as part of the "Car" class, they do not really belong there.
On the other hand, creating a "Garage" class just to provide a list of cars would also be overkill.

The pragmatic way is to have a method in the class that handles the database interaction for "Car" to retrieve a list of cars and if that happens to be "Car" itself, the so be it. IMO, it is more important to have all the code that deals with retrieving cars from the database close together than the purity of the solution. This method returns the cars as a list, array, hash or whatever collection type your language provides you.


问:
Write then optimise or write optimised
Do you write your code then optimise it? Or do you write an optimised code from the beginning.

I always believe in writing optimised since I really dont like to rewrite code, But please share your thoughts.

答:
Are you suggesting to do premature optimization?

The code is fast when it matches the performance non-functional requirements. Until those requirements are fulfilled, you don't have to care about performance: there are much more important things to care about, like the quality of your code, the architecture, etc.

Once the non-functional performance requirement is broken by your code, it means that it's slower than what is acceptable/desirable. At this point, you should:

Profile your code (instead of guessing where the bottleneck is, since we always get it wrong),

Optimize it until the test corresponding to the requirement passes again.

Title: Write then optimise or write optimised


答:
If you already have written a comparator, it's of course best to modify it so that the standard sort (into "ascending" order) does what you want.

The second best thing is to use whatever switches or tricks are available in your language's standard sorting methods. Such as this in Java:

```<code>Arrays.sort(array, Collections.reverseOrder());
</code>```

The third option, reversing an already sorted list, isn't a categorically bad solution. In some cases it's the simplest possible solution, and easiest to comprehend. The efficiency overhead of reversing an array/list is negligible in majority of cases.

Title: Best practice to sort then reverse, or write "backwards" comparator?

Body:
I wrote a comparator for a custom class of mine and when I ran my code I realised the output of my list of these objects was in the reverse order as to what I wanted. It was "ascending" as opposed to "descending". This was because I stuck to the spec of compare where a return value of less than 0 means the other object is less than this and so on.

To fix this I called the reverse method on my list, but I could've also changed the compare method so that it returns greater than 0 where the other object is less than this.

What is seen as the standard for this case and why?

Body:
If you already have written a comparator, it's of course best to modify it so that the standard sort (into "ascending" order) does what you want.

The second best thing is to use whatever switches or tricks are available in your language's standard sorting methods. Such as this in Java:

Arrays.sort(array, Collections.reverseOrder());

The third option, reversing an already sorted list, isn't a categorically bad solution. In some cases it's the simplest possible solution, and easiest to comprehend. The efficiency overhead of reversing an array/list is negligible in majority of cases.