问:
Designing exceptions for conversion failures
Suppose there are some methods to convert from "X" to "Y" and vice versa; the conversion may fail in some cases, and exceptions are used to signal conversion errors in those cases.

Which would be the best option for defining exception classes in this context?

A single XYConversionException class, with an attribute (e.g. an
enum) specifying the direction of the conversion (e.g.
ConversionFromXToY, ConversionFromYToX).

A XYConversionException class, with two derived classes
ConversionFromXToYException and ConversionFromYToXException.

ConversionFromXToYException and ConversionFromYToXException classes
without a common base class.

答:
What language? Many languages already have well defined Exception classes. You would just derive from those and add the details.

For something trivial like this, a single ConversionException should be enough, details can go into the class.

As a Ruby programmer I would even consider to just use the default exception class and put the details into the message part it provides under some circumstances.


答:
The foremost reason for having different exception types is to be able to catch them selectively.

So the question you should ask yourself is: Will you ever have a piece of code where conversion might fail and you only want to catch conversion errors in one direction and not the other? If so, having two distinct exception classes is the best way to go. If you want to be able to catch both in the same clause, then you need a common super class as well.

If you do find it hard to anticipate how the exceptions are caught, then stick to YAGNI and go with the first option. You can always add the subclasses later if you ever actually need them.

Apart from that, I think you should ask yourself whether exceptions are the right way to signal conversion failure, because in fact failure is an expected option. In fact a lot of APIs merely use sentinel values for that.

Another nice way to propagate errors would be to wrap return information of any call that can fail like this (in pseudo-code):

```<code> class Outcome<Result, Error> {
      const Bool success;
      const Result result;
      const Error error;
      Result sure() {
           if (success) return result;
           else throw error;
      }
 }

 Outcome<X, { value: Y, message: String }> convertYToX(Y y) {
     if (suitable(y)) return Outcome{ success: true, result: convert(y) };
     else return Outcome{ success: false, error: { }};
 }
</code>```

And then either do:

```<code> handleX(convertXToY(myY).sure());//will throw an exception if an error occurred
</code>```

Or inspect the result yourself:

```<code> var o = convertXToY(myY);
 if (o.success)
     handleX(o.result);
 else {
     log('error occured during conversion:');
     log(o.error.message);
     log('using default');
     handleX(defaultX);
 }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Designing exceptions for conversion failures

Body:
Suppose there are some methods to convert from "X" to "Y" and vice versa; the conversion may fail in some cases, and exceptions are used to signal conversion errors in those cases.

Which would be the best option for defining exception classes in this context?

A single XYConversionException class, with an attribute (e.g. an
enum) specifying the direction of the conversion (e.g.
ConversionFromXToY, ConversionFromYToX).

A XYConversionException class, with two derived classes
ConversionFromXToYException and ConversionFromYToXException.

ConversionFromXToYException and ConversionFromYToXException classes
without a common base class.

Body:
The foremost reason for having different exception types is to be able to catch them selectively.

So the question you should ask yourself is: Will you ever have a piece of code where conversion might fail and you only want to catch conversion errors in one direction and not the other? If so, having two distinct exception classes is the best way to go. If you want to be able to catch both in the same clause, then you need a common super class as well.

If you do find it hard to anticipate how the exceptions are caught, then stick to YAGNI and go with the first option. You can always add the subclasses later if you ever actually need them.

Apart from that, I think you should ask yourself whether exceptions are the right way to signal conversion failure, because in fact failure is an expected option. In fact a lot of APIs merely use sentinel values for that.

Another nice way to propagate errors would be to wrap return information of any call that can fail like this (in pseudo-code):

 class Outcome<Result, Error> {
      const Bool success;
      const Result result;
      const Error error;
      Result sure() {
           if (success) return result;
           else throw error;
      }
 }

 Outcome<X, { value: Y, message: String }> convertYToX(Y y) {
     if (suitable(y)) return Outcome{ success: true, result: convert(y) };
     else return Outcome{ success: false, error: { }};
 }

And then either do:

 handleX(convertXToY(myY).sure());//will throw an exception if an error occurred

Or inspect the result yourself:

 var o = convertXToY(myY);
 if (o.success)
     handleX(o.result);
 else {
     log('error occured during conversion:');
     log(o.error.message);
     log('using default');
     handleX(defaultX);
 }


问:
Do poor writers make poor programmers?
I'm reading Coders at Work by Peter Seibel, and many a time it has been mentioned that programmers who can't write generally make poor programmers - it's been claimed by Douglas Crockford, Joshua Bloch, Joe Armstrong, Dijkstra (and I've only read half the book).

What's your view of this? Is an inability to express yourself in writing in a natural language such as English a hindrance of writing good code?

答:
I think if we examine the question, we obtain the answer directly:

Is an inability to express yourself in
  writing in a natural language such as
  English a hindrance of writing good
  code?

What does it actually mean to write good code?

Programs must be written for people to
  read, and only incidentally for
  machines to execute.

  - Abelson & Sussman, Structure and Interpretation of Computer Programs

It means to express yourself clearly, concisely, correctly and elegantly writing in a programming language.

The only difference between expressing yourself skillfully in English or a programming language is that English is far more forgiving.

ContentLicense: CC BY-SA 2.5

Title: Do poor writers make poor programmers?


答:
Don't over-think it,

My suggestions:

Regarding the signature of the constructor, all over the Java API, classes that extend Exception, uses one or more of the following constructors:

```<code>1. PrintException()  // Construct a print exception with no detail message.
2. PrintException(Exception e) // Construct a print exception chaining the supplied exception.
3. PrintException(String s) // Construct a print exception with the given detail message.
4. PrintException(String s, Exception e) // Construct a print exception with the given detail message and chained exception.
</code>```

I really think that one or two of this constructors will suffice for you, probably 1 and 3.

Regarding whether or not you should have separate exceptions for X->Y and Y->X, I strongly advice not to do so, because you will end up writing exceptions for Z->X, X->Z, P->Q, Q->P, Q->X, Q->Y and a lot of permutations. You shoul ask what is the added value of this.

Body:
Don't over-think it,

My suggestions:

Regarding the signature of the constructor, all over the Java API, classes that extend Exception, uses one or more of the following constructors:

1. PrintException()  // Construct a print exception with no detail message.
2. PrintException(Exception e) // Construct a print exception chaining the supplied exception.
3. PrintException(String s) // Construct a print exception with the given detail message.
4. PrintException(String s, Exception e) // Construct a print exception with the given detail message and chained exception.

I really think that one or two of this constructors will suffice for you, probably 1 and 3.

Regarding whether or not you should have separate exceptions for X->Y and Y->X, I strongly advice not to do so, because you will end up writing exceptions for Z->X, X->Z, P->Q, Q->P, Q->X, Q->Y and a lot of permutations. You shoul ask what is the added value of this.


问:
Equal Gifts Algorithm Problem
Problem Link - http://opc.iarcs.org.in/index.php/problems/EQGIFTS

It is Lavanya's birthday and several families have been invited for the birthday party. As is customary, all of them have brought gifts for Lavanya as well as her brother Nikhil. Since their friends are all of the erudite kind, everyone has brought a pair of books. Unfortunately, the gift givers did not clearly indicate which book in the pair is for Lavanya and which one is for Nikhil. Now it is up to their father to divide up these books between them.

He has decided that from each of these pairs, one book will go to Lavanya and one to Nikhil. Moreover, since Nikhil is quite a keen observer of the value of gifts, the books have to be divided in such a manner that the total value of the books for Lavanya is as close as possible to total value of the books for Nikhil. Since Lavanya and Nikhil are kids, no book that has been gifted will have a value higher than 300 Rupees...

For the problem, I couldn't think of anything except recursion. The code I wrote is given below. But the problem is that the code is time-inefficient and gives TLE (Time Limit Exceeded) for 9 out of 10 test cases! What would be a better approach to the problem?

Code -

```<code>#include<cstdio>
#include<climits>
#include<algorithm>
using namespace std;

int n,g[150][2];

int diff(int a,int b,int f) {
    ++f;
    if(f==n) {
               if(a>b) {
                       return a-b;
               }
               else {
                    return b-a;
               }
    }
    return min(diff(a+g[f][0],b+g[f][1],f),diff(a+g[f][1],b+g[f][0],f));
}

int main() {
    int i;
    scanf("%d",&n);
    for(i=0;i<n;++i) {
                     scanf("%d%d",&g[i][0],&g[i][1]);
    }
    printf("%d",diff(g[0][0],g[0][1],0));
}
</code>```

Note - It is just a practice question, & is not part of a competition.

答:
Just winging this off the top of my head before morning status meeting:

```<code>Sort books descending by value
Give first book to Lavanya
while books remain
    while Nikhil's values < Lavanya's values
        Give first book to Nikhil
    while Lavanya's values < Nikhil's values
        Give first book to Lavanya
</code>```

Will that do it?

Title: Equal Gifts Algorithm Problem

Body:
Just winging this off the top of my head before morning status meeting:

Sort books descending by value
Give first book to Lavanya
while books remain
    while Nikhil's values < Lavanya's values
        Give first book to Nikhil
    while Lavanya's values < Nikhil's values
        Give first book to Lavanya

Will that do it?


问:
Performance impact of not implementing relationships at the database level?
Let's imagine a data model with customers and invoices. There is a 1 to n relationship between a customer and its invoices. We uses an ORM (like Hibernate).

One can explicitely implement the 1-n relationship (using JPA for example) or not. If not, then one must do a bit more work to fetch invoices.

However, it is much easier to maintain, improve and develop the data model of applications where relationships between objects are not explicitely implemented in the database.

My question is, has anyone noticed a significant performance impact when not implementing the relationships in the database?

答:
When I implement a relationship like that, there are 2 parts to it:

The "foreign key"

The "index"

The foreign key is a constraint which says that the CustomerId in the Invoice table must exist in the Customer table.  This (probably) doesn't give you any performance improvement (in fact there's a performance hit to do the check), but it's there to catch errors and make absolutely sure that the data is consistent.  Weird things can happen.  I don't suggest skipping this.

The index is when you index the Invoice table by the CustomerId column.  I know that in SQL Server you have to specify this separately from the foreign key.  The index will give you a performance improvement, if you ever look up invoices for a given customer.  However, maintaining the index takes time and space, so there's a tradeoff.


答:
That depends on what you mean by "good code".

If you mean code that just works, there is hardly any relation between being able to communicate with humans and being able to communicate with computers.

If you mean code that works, is maintainable, and clearly expresses the intention of the code, there is absolutely a relation between writing good code and writing in a language solely intended for humans.

Although you wouldn't need all the different skills required to be a good writer for writing understandable code, there are still some of the elements that have to be there, as both will be read by humans. In some ways it's even harder to write good code, as it should describe the intention with the code, while not using constructs that would perform badly while executed by the computer.

Title: Do poor writers make poor programmers?

Body:
I'm reading Coders at Work by Peter Seibel, and many a time it has been mentioned that programmers who can't write generally make poor programmers - it's been claimed by Douglas Crockford, Joshua Bloch, Joe Armstrong, Dijkstra (and I've only read half the book).

What's your view of this? Is an inability to express yourself in writing in a natural language such as English a hindrance of writing good code?


问:
Is modern C++ replacing C#? Is Microsoft pushing developers to adopt C++?
I hear about modern C++ popularity and some talks about migrating back to C++ from C# or other C-like languages.

I know about C++11 features but I would like to hear your experiences, especially from developers who migrated from C# to C++.

More importantly, does Microsoft push developers to use C++? If yes, why?

答:
I know about C++11 features but I would like to hear your experiences

The thought that people would prefer C++ over C# (or pretty much any other post 1990  [non-php] alterative) for general purpose programming is laughable. C++11 adds some good missing bits, but it's still nailing legs to a dog.

C++ has some good niches, and it's still the best option on some platforms with limited compiler support. But no, modern C++ is nowhere close to replacing anything except perhaps antiquated, broken C++.


答:
Yes, your suspicions are correct. Microsoft is pushing C++ to come back and become more popular.

I can't find it now, but a while ago I saw a presentation by one of Microsoft big guys and the whole thing was geared towards developers and was about roll out of Windows 8 and especially WinRT (the replacement for .NET framework as well as Win32 API).

He had a timeline that he explained how various pressures were affecting what technology was popular at certain times. So at first people wanted speed so they all coded in C/C++ (two separate languages). As the hardware got faster, the focus moved away from speed of execution and more towards speed of development, so higher level languages became much more popular.

However, now the focus is becoming more towards mobile and ARM-based computers (Windows 8 is first Windows release to be compiled for ARM) and many believe they will become much more popular and for some will completely replace the desktop. So the focus (at least in Microsoft's eyes) is back on C++ because now we care about battery life.  Higher level code = more instructions = more juice required.

To support this transition back to C++, they've introduced a completely new Windows 8 programming API, called WinRT (last I checked, that was the name anyway). This API follows the theme of .NET Framework in the scope of functionality it provides but it will be available to anyone coding in C++ (via COM interfaces), in C# or even in Javascript for those that wish to write HTML 5/Javascript apps.  They are also bringing XAML (technology used in WPF, their newest UI framework) to be available in C++ as well.

So to me that kind of indicates that there's definitely more focus on C++ at Microsoft than there was in the past.

UPDATE #1:

Since I just got a 'nice answer' badge for this, I thought maybe I should come back and a) clarify few things and b) make the fact-checking police happy because as we all know on technology forums anything inaccurate could result in wars that last for years.

WinRT is not a replacement for .NET framework, but it is yet another alternative that MS Windows developers now have and MS is strongly pushing people to go in that direction.  It appears (please hold your flames if this is not 100% accurate) that WinRT was primarily targeted for Modern UI apps although regular desktop apps should be able to take advantage of it as well.  Having said this, MS is strongly pushing for people to switch to writing a) modern UI apps and b) start using WinRT so as the balance shifts percentage of people using .NET framework will most likely go down.

C++ will NEVER replace higher level languages such as C# or python.  Just like those languages will NEVER replace C++.  This was probably the most controversial part of OP's question. But it is all about the balance and the facts are that:

C++ community (with MS being large part of it) is pushing for a strong comeback to position C++ as a good language for low-powered devices, whose market share has been going up like crazy lately. If you do not believe me, search for "GoingNative" series of talks that began last year.

With all the effort and influence from Microsoft, C++ usage will definitely go up, while C# might drop some what. This is what MS is pushing for and as I said in the comments above, when MS puts their capital behind an idea, they do shift large portion of the industry. I will probably get a response from some guy who will argue, "what industry, I've always been on Linux" and to that my only response is, wake up! Yes, there are other OSs out there but majority of desktop market, both consumer and business at the moment is Windows and any serious developer who wishes to maximize the value of his time would be very silly not to target that chunk of the desktop market.

So in conclusion: Yes, MS is pushing for C++ to come back so most likely its popularity will increase.  No, C++ will never replace C#.

Update #2:

I don't know why but technical community tends to see things in very absolute black/white terms when the reality is full of shades of gray.  This is a response to several new comments that were added to this post:

.NET framework will not go away any time soon (or ever). Just about every technology that windows had since 90's is still around in some form or fashion.  So for those that are so attached to .NET framework: a) don't worry about it disappearing and b) stop arguing in its favor as if your life depended on it, your API is safe.

WinRT does reimplement a lot of functionality that in the past was provided by Win32 and .NET framework APIs. People who want that functionality will have a choice if they want to use WinRT, .NET framework, or continue with Win32 API (that's not dead either).  If WinRT doesn't support easy creation of web applications today, there's a very good chance it will support them in the future.

The position that Microsoft announced is that WinRT is a large framework which gave Microsoft a chance to start with a clean slate and built an API using lessons learned in Win32 API and .NET framework itself. I did try looking for that video, and still can't find it, but one of the things the speaker mentioned is that there are certain areas of .NET framework which could have been defined better/simpler/cleaner and WinRT exposes that same functionality in that new cleaner interface.

Title: Is modern C++ replacing C#? Is Microsoft pushing developers to adopt C++?

Body:
I hear about modern C++ popularity and some talks about migrating back to C++ from C# or other C-like languages.

I know about C++11 features but I would like to hear your experiences, especially from developers who migrated from C# to C++.

More importantly, does Microsoft push developers to use C++? If yes, why?


问:
How can you get constructive criticism for your code?
My team rarely does code review, mainly because we don't have enough time and people lack the energy and will to do so. But I would really like to know what people think about my code when they read it. This way, I have a better understanding how other people think and tailor my code accordingly so it's easier to read.

So my question is, how can I get constructive criticism for my code? My intent is to understand how people think so I can write more readable code.

答: Do you have good tools for code reviews? We had a similar problem in my group. I took some time to install a Reviewboard server, and participation in code reviews jumped. I have found that people like to comment on code when it is made easy.</p>


答: No fancy tools, in my opinion, could replace sitting with a senior developer or architect and walk through the code (or their code, and see what they did first hand). That said, I've found that unit testing code forces you to think in a reusable way, it also forces you to incorporate patterns that could make your code more readable (with the added benefit of better tested code).</p>

Title: How can you get constructive criticism for your code?

Body:
My team rarely does code review, mainly because we don't have enough time and people lack the energy and will to do so. But I would really like to know what people think about my code when they read it. This way, I have a better understanding how other people think and tailor my code accordingly so it's easier to read.

So my question is, how can I get constructive criticism for my code? My intent is to understand how people think so I can write more readable code.


答: You should really consider taking time to do code reviews, because in my experience it is worth the effort regarding the quality of your code. If code review is no option at your team and you want to understand how people think, maybe pair programming is an option for you. You get immediate feedback on what you're typing - something like an instant review.</p>


问:
Relationship DAO, Servlet, JSP and POJO
I want to implement a JSP, POJO, DAO and Servlet in my J2EE program. However, I don't fully understand how the relationship between these elements should be. Is the following (MVC) setup the right way to do it?

Main class creates servlet(controller)

Servlet has a DAO defined in its class

DAO has a POJO defined in its class

Servlet communicates with the view (JSP page)

Please give your feedback.

答:
IMHO there's multiple issues here:

1 . To me the MVC pattern, like the Quantum Theory has multiple interpretations

AFAICS: there's two major ways to do MVC:

one where the controller actively tells the view to update once he (the controller) has updated the model

one where the view "sees" the model updates and updates itself in turn without any exterior help

In a simple Servlet and JSP setup you're pretty much in the first interpretation of the MVC pattern, where the servlet does whatever (more on this in a minute) and then creates the model, followed by telling the JSP view to update itself so that the new model shows up in the view.

I'm stating all this because if you want to go about the 2nd MVC interpretation as stated here, you'll usually have to use a lot of JavaScript in the View to enable it to listen for your model changes and update itself.

At any rate, no matter which one you chose the 2nd major issue is:

2 . Establishing how these components will match up to the Model, View and Controller entities:

one way to go about it is to have the Servlet as Controller. This means you'll (usually) have multliple servlets, each controlling one or more views. The views in turn are JSP pages. Now, the controller servlet should only deal with creating the model (not deal with presentation stuff) and the JSP view should only care about using the model for presentation (not adding to the model-construction work the servlet controller has already done). This tipically means having a Servlet with one or more DAO (or other business service components) instances, which will be used to fetch the model data, and once that's done, he'll place it where the JSP view can reach it (usually in request or session scope) and reload the view. The JSP in it's turn only knows that when it's loaded it's supposed to find the model data at some place, and present it in a certain way.

a somewhat better way to do this is to have non-servlet components (classes) for the controller. These controllers are notified by one or more "facade" servlets depending on the HTTP Request content (URL, parameters, etc, there's usually some kind of mapping between various combinations of HTTP Request elements and corresponding controller intances). In this way the controller really deals only with creating the model and notifying the view, it doesn't deal with the low level HTTP stuff.

Finally, as a side note, you should know that a Servlet, in order to be instantiated, must be deployed in a Java EE Web Server (like Tomcat), there's no "main" method (not one that you have to write anyway) where you manually instantiate them.

3 . About the Facade Servlet and separate (non-servlet) controllers

The idea here is to separate the low level transport/communications stuff from your MVC implementation. The MVC doesn't really specify anything about such things, and indeed there's no obvious place for them in a MVC implementation. On the other hand your Servlet does do HTTP, that's how it works. So taking all these into account it's good to NOT make the Servlet into a MVC controller, but rather have it only deal with incoming HTTP requests and then dumbly just pass them on to the appropriate controller, effectively acting as a Facade for all those controllers back there.

In practice what you can do is decide upon a system which will map an HTTP Request to a controller:

you decide what part of the HTTP request is taken into account to identify a controller. Typically it will be the request URL such that when an incoming request for "/mySite/listProducts" comes in, the Facade servlet will extract the relevant information from the request and pass it to the corresponding controller, then wait for said controller to prepare the model and display the view

you decide how to actually implement this mapping. You can just make a flat file stating things such as the URL pattern and the corresponding Controller class or instance, something like this:

/mySite/listProducts myProject.controllers.ProductsListController
/mySite/productDetails/* myProject.controllers.ProductDetails

In the above example, I've chosen a wider URL pattern for the second controller, because the specific URL demanding for Product Details might contain at the end of the path some kind of identifier for the specific product it wants details on, something like /mySite/productDetails/pinkFedoraHat and I want any and all such requests to go to the ProductDetails controller

Then when the app starts, the Facade Servlet is configured with this file, and then instanciates and delegates to the needed controller.

a second mapping you might need to do is between controller and view. You may want one controller to redirect to multiple views, depending on how it was addressed. You can do this similarly by making an URL pattern to JSP map. However this is really optional.

Also, as this is a pretty obvious pattern, there are already implementations of it in various Java frameworks: Strust2, Spring MVC, (these 2 are for the first type of MVC, the controllers-nudges-view-to-update type), Ember JS (this is a JavaScript library and gives you the view-is-smart-enough-to-update-itself-upon-model-update variant). What I recommend is that you first try to implement some simple examples without these frameworks, so you can get a good idea of how this works, and then use one of these for more involved projects as the boilerplate code to implements this can get pretty unwieldy when doing it all by hand

Title: Relationship DAO, Servlet, JSP and POJO


问:
Why Does F# Contain Both Modules and Namespaces?
I've been assuming that F# includes the module keyword in addition to the namespace keyword due to backwards compatibility with OCaml.  Is this the only reason for the inclusion of the module keyword or are there other reasons module was included?</p>

答:
Namespaces are well defined in the .Net universe, and they don't include the things that make up a module, except inside something very much like a module.

Given that they were designing a language to run on the CLR, making it incompatible with other languages would not have made sense.

On a slightly different tangent, namespaces and modules do NOT overlap -- in particular, you can't define another namespace inside a module, and defining another namespace is the sole purpose of namespaces.  They may bear a superficial simularity, but they are distinct concepts.


问:
How do you use blank lines in your code?
There has been a few remarks about white space already in discussion about curly braces placements.

I myself tend to sprinkle my code with blank lines in an attempt to segregate things that go together in "logical" groups and hopefully make it easier for the next person to come by to read the code I just produced.

In fact, I would say I structure my code like I write: I make paragraphs, no longer than a few lines (definitely shorter than 10), and try to make each paragraph self-contained.

For example:

in a class, I will group methods that go together, while separating them by a blank line from the next group.

if I need to write a comment I'll usually put a blank line before the comment

in a method, I make one paragraph per step of the process

All in all, I rarely have more than 4/5 lines clustered together, meaning a very sparse code.

I don't consider all this white space a waste because I actually use it to structure the code (as I use the indentation in fact), and therefore I feel it worth the screen estate it takes.

For example:

```<code>for (int i = 0; i < 10; ++i)
{
    if (i % 3 == 0) continue;

    array[i] += 2;
}
</code>```

I consider than the two statements have clear distinct purposes and thus deserve to be separated to make it obvious.

So, how do you actually use (or not) blank lines in code ?

答:
Always

Whitespace is crucial to clean readable code. A blank line (or two) help visually separate out logical blocks of code.

For example, from Steve McConnell's Code Complete, Second Edition chapter on Layout and Style:

Subjects scored 20 to 30 percent higher on a test of comprehension when programs had a two-to-four-spaces indentation scheme than they did when programs had no indentation at all. The same study found that it was important to neither under-emphasize nor over emphasize a program’s logical structure. The lowest comprehension scores were achieved on programs that were not indented at all. The second lowest were achieved on programs that used six-space indentation. The study concluded that two-to-four-space indentation was optimal. Interestingly, many subjects in the experiment felt that the six-space indentation was easier to use than the smaller indentations, even though their scores were lower. That’s probably because six space indentation looks pleasing. But regardless of how pretty it looks, six-space indentation turns out to be less readable. This is an example of a collision be tween aesthetic appeal and readability.


问:
File system implementation in MongoDB with GridFS
I am working on two projects that will both implement a Webdav server backed by a MongoDB GridFS. In each case, there is the potential for the system to store tens of millions of files spread across thousands of hierarchical directories.

I can come up with two different ways of storing the directory structure:

As a "true" hierarchical file system, with directories containing the IDs (_id) of subdirectories and regular files. The paths will be separated by slashes (/) as in a POSIX-compliant file system.

The path /a/b/c will be represented as a directory a containing a directory b containing a file c.

As a flat file system, where file names include the slashes.

The path /a/b/c will be stored as a single file with the name /a/b/c

What are the advantages and disadvantages of each, with respect to a "real" folder-based file system?

答: Have you looked at http://www.mongodb.org/display/DOCS/Trees+in+MongoDB ? It looks like you're between "Child Links" and "Materialized Paths". Based on the commentary it seems that your second idea is a much better fit for Mongo. Storing each subdirectory _id is a little too relational and implies linking and joins which are not things that Mongo excels at.


问:
I need some help creating a non-binary tree (or some other data structure that will better solve my problem)
I have about ten lists of numbers and some strings. Each list has about <= 30K lines. Each line on a list has a distinct number.

I need to build an efficient way of finding all the lines in each list that has the same 'control' number (or key for dB guys) and comparing what is in their string parts. I am writing this in Java.

Let me give an actual example of what I am trying to do..... I have ten lists each containing about 30K records. Each record looks like 901234(key)- 1.0987(float)-kadfnfj(Description String)-01/01/01(date) and all lists have similar records some keys may be available in some lists but not guaranteed!.. I want to find a way to search through all lists for one particular key and compare the attendant float value. Due to the size of the lists, i am worried about the memory usage and due to the number of records, I am worried about the efficiency of the data structure used.

I have thought about using trees but my brain cells are about burnt now. I need some help.

答: The ideal method for accessing a given key would be direct access where you use the key to give you the address. In Java you don't have direct memory addresses however you do get indexed arrays so you could use the array index as the memory address. This should be far faster than any traversal method.</p>


问:
How can I port msvc++ code with non-dependent names in templates to Linux?
I can deal with porting platform dependent functions. I have a problem that the compilers I tried on Linux (clang and g++) do not accept the following code, while the msvc++ compiler does:

```<code>template <class T>
class Base {
protected:
    T Value;
};

template <class T>
class Derived : public Base<T> {
public:
    void setValue(const T& inValue){
        Value = inValue;
    }
};

int main(int argc, char const *argv[])
{
    Derived<int> tmp;
    tmp.setValue(0);
    return 0;
}
</code>```

g++ error:

```<code>main.cpp: In member function ‘void Derived<T>::setValue(const T&)’:
main.cpp:11:3: error: ‘Value’ was not declared in this scope
</code>```

I believe this due to the use of a non-dependent name (Value) in the second class. More information.

The problem is that I have a very large code base, in which this type of code is used very often. I understand that it is wrong when looking at the standard. However it is very convenient not having to write this-> or Base<T>:: in front of every use of Value. Even writing using Base<T>::Value; at the start of the derived class is problematic when you use ~20 members of the base class.

So my question is: are there compilers for Linux that allow this kind of code (with or without extra compiler switches)? Or are there small modifications that will allow this code to compile on Linux?

答: I also posted this question on SO. From the few comments here and the answers there I reach the same conclusion: I have to fix my code. Adding my own answer so I can mark this question as accepted/resolved.</p>


答:
Answer is quite big. but here it is

As you are following MVC design pattern.So, I'll describe in

View =  jsp, html, javascript exists

Controller =  servlet

Model= Dao

Basically in servlet calling your DAO to get data from DB.
But throughout the application there are many Variables so for that you need bean. i.e
POJO

Lets go by hierarchy of project that you will create in eclipse.

Here u can see in source folder where we have "test" folder which is main package and under that different we have sub packages.

Here we can put servlet's in controller. your POJO is in bean. DAO has dao class.
And util has different class of custom utility like custom date, password encryption.

and finally you will have webcontent folder will have jsp pages.

Now flow would be first user input from jsp page. would be

JSP==>Servlet(Here you can set parameter to POJO send instance to DAO)==>DAO==>DB

And last but not least is web.xml which is deployment descriptor and which used by container or web server to handle request.

Lets start........

Title: Relationship DAO, Servlet, JSP and POJO

Body:
I want to implement a JSP, POJO, DAO and Servlet in my J2EE program. However, I don't fully understand how the relationship between these elements should be. Is the following (MVC) setup the right way to do it?

Main class creates servlet(controller)

Servlet has a DAO defined in its class

DAO has a POJO defined in its class

Servlet communicates with the view (JSP page)

Please give your feedback.


答:
In MVC pattern,

Servlet is the controller(C)

JSP page is view (V)

POJOs and DAOs are Model (M)

A user sees the jsp page and interacts with it. When a user submits a request(clicks a button), jsp sends it to the servlet you have defined.

Servlet which is a controller may create a POJO, store data sent by the user in it and passes it on to the DAO.

DAO queries the database and sends it back to the servlet and the servlet passes the data back to jSP again.

Title: Relationship DAO, Servlet, JSP and POJO

OwnerDisplayName: javaStudent


问:
iOS app with a lot of text
I just asked a question on StackOverflow, but I'm thinking that a part of it belongs here, as questions about design pattern are welcomed by the faq.

Here is my situation. I have developed almost completely a native iOS app. The last section I need to implement is all the rules of a sport, so that's a lot of text. It has one main level of sections, divided in subsections, containing a lot of structured text (paragraphs, a few pictures, bulleted/numbered lists, tables). I have absolutely no problem with coding, I'm just looking for advice to improve and make the best design pattern possible for my app.

My first shot (the last one so far) was a UITableViewController containing the sections, sending the user to another UITableViewController with the subsections of the selected section, and then one strange last UITableViewController where the cells contain UITextViews, sections header help structure the content, etc.

What I would like is your advice on how to improve the structure of this section. I'm perfectly ready to destroy/rebuild the whole thing, I'm really lost in my design here.. As I said on SO, I've began to implement a UIWebView in a UIViewController, showing a html page with JQuery Mobile to display the content, and it's fine. My question is more about the 2 views taking the user to that content. I used UITableViewControllers because that's what seemed the most appropriate for a structured hierarchy like this one. But that doesn't seem like the best solution in term of user experience..

What structure / "view-flow" / kind of presentation would you try to implement in my situation?

As always, any help would be greatly appreciated!

Just so you can understand better the hierarchy, with a simple example :

```<code>                          -----> Section 1   -----> SubSection 1.1   -----> Content
                          |                  -----> SubSection 1.2   -----> Content
                          |                  -----> SubSection 1.3   -----> Content
                          |
                          |
                          |
UINavigationController  -------> Section 2   -----> SubSection 2.1   -----> Content
                          |                  -----> SubSection 2.2   -----> Content
                          |                  -----> SubSection 2.3   -----> Content
                          |                  -----> SubSection 2.4   -----> Content
                          |                  -----> SubSection 2.5   -----> Content
                          |
                          -----> Section 3   -----> SubSection 3.1   -----> Content
                                             -----> SubSection 3.2   -----> Content

                      |------------------|   |--------------------|  |-------------|
                  1 UITableViewController   3 UITableViewControllers  10 UIViewControllers
                         (3 rows)              (with different         with a UIWebView
                                                number of rows)
</code>```

答:
The simplest way to achieve this is to write the documentation as a set of HTML files, include them as resources, and display them with a UIWebView.  Use links to create the hierarchy; that's what they're for.

If you want to use the navigation controller's hierarchy as a way of presenting a back button, intercept all link clicks and push a new view onto the stack that contains a UIWebView.  Tell it to load the destination of the previous view's link.  Here's a Stack Overflow question about intercepting web view link clicks:

https://stackoverflow.com/questions/8437305/ios-uiwebview-intercept-link-click

This approach reduces your 14 (!) view controllers down to 1, and makes maintenance a matter of editing HTML files rather than a whole mess of views and view controllers.

Title: iOS app with a lot of text


答:
Yes for clarity.

Just like I did in this answer.

Title: How do you use blank lines in your code?

Body:
There has been a few remarks about white space already in discussion about curly braces placements.

I myself tend to sprinkle my code with blank lines in an attempt to segregate things that go together in "logical" groups and hopefully make it easier for the next person to come by to read the code I just produced.

In fact, I would say I structure my code like I write: I make paragraphs, no longer than a few lines (definitely shorter than 10), and try to make each paragraph self-contained.

For example:

in a class, I will group methods that go together, while separating them by a blank line from the next group.

if I need to write a comment I'll usually put a blank line before the comment

in a method, I make one paragraph per step of the process

All in all, I rarely have more than 4/5 lines clustered together, meaning a very sparse code.

I don't consider all this white space a waste because I actually use it to structure the code (as I use the indentation in fact), and therefore I feel it worth the screen estate it takes.

For example:

```<code>for (int i = 0; i < 10; ++i)
{
    if (i % 3 == 0) continue;

    array[i] += 2;
}
</code>```

I consider than the two statements have clear distinct purposes and thus deserve to be separated to make it obvious.

So, how do you actually use (or not) blank lines in code ?


问:
When should you call yourself a senior developer?

Possible Duplicate:

  Whats the difference between Entry Level/Jr/Sr developers?

I'm curious what senior developer means because apparently the definition doesn't mean what I thought it would. I keep seeing these teens at 22-23 years old who call themselves senior X developer or senior Y developer. To me, a senior must have 10 years or so experience in programming to call himself 'senior'. I've seen a lot of these teens here (hence the question). Am I wrong? Why?

答: Age is just a number; a young kid is getting smarter and _insert number years-experienced programmer is just getting old... Nowadays, a kiddo can write cleaner, better, faster codes in a smart way. An old pal can just get jealous.


答:
Ideally a database would be used.  You let the database handle the look up of the value quickly.  If you have a small, light database (mysql and similar) accessible, use it.

Failing having a table that you can wrangle from a DBA for doing this, there are other database solutions.  The one that I am most familiar with is BDB (Berkeley DataBase).

Using the sleepycat licensed version, this is free.  BDB stores its data on disk and you don't store its entirety in memory at once.

The trickiest part in this design would be the data that is stored for each key (to an extent, thats the problem for anything).

If you are willing to spend disk space, a consideration would be to use the filesystem itself as a database.  For the data 901234(key)- 1.0987(float)-kadfnfj(Description String)-01/01/01(date), you would write a file in the directory .../9/0/1/2/3/4/901234/ with the information you are storing. Accessing the filesystem is not bad and also makes it trivial for other applications to access the data.

For that matter, if you are familiar with other "scripting" languages (perl, python, etc...) these may be more suited to the task (working with strings and the file system) of simply breaking up the large files into their component lines.

Title: I need some help creating a non-binary tree (or some other data structure that will better solve my problem)

Body:
I have about ten lists of numbers and some strings. Each list has about <= 30K lines. Each line on a list has a distinct number.

I need to build an efficient way of finding all the lines in each list that has the same 'control' number (or key for dB guys) and comparing what is in their string parts. I am writing this in Java.

Let me give an actual example of what I am trying to do..... I have ten lists each containing about 30K records. Each record looks like 901234(key)- 1.0987(float)-kadfnfj(Description String)-01/01/01(date) and all lists have similar records some keys may be available in some lists but not guaranteed!.. I want to find a way to search through all lists for one particular key and compare the attendant float value. Due to the size of the lists, i am worried about the memory usage and due to the number of records, I am worried about the efficiency of the data structure used.

I have thought about using trees but my brain cells are about burnt now. I need some help.


答:
First, write something that works. You can just split the line to hold the key and the float and put it in Map; separate Map for each 30K-list. So you will have a few Maps from integer keys to float values. Or something that simple.

If it will work, measure if it is too slow, and then try to find better data structures/algortihms. I'd say for 30K records, a Map holding data in memory would be sufficient enough.


问:
In GSL, why do some functions take a "workspace" argument?
In certain functions in GSL (GNU Scientific Library), some functions take a "workspace" environment as an argument.  For example, gsl_poly_dd_taylor from this page.  Why?  Wouldn't it be easier for the function to allocate its own memory, or at least the same difficulty?  I suppose that this allows the caller to specify where the function works, but I don't see how it helps.

答: Efficiency. GSL is designed to be both time and memory efficient and it makes more sense to pass around the same workspace than have each and every function allocate and free its own.</p>


答:
There appears to be some confusion about my comment on Ben's answer, so here's my solution standalone:

```<code>#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <stdlib.h>
using namespace std;

typedef pair<int, int> BookPair;
typedef vector<BookPair*> BookList;

void readBookList(BookList &books)
{
    int n, a, b;
    cin >> n;
    for (int i = 0; i < n; ++i)
    {
        cin >> a >> b;
        int cheapBook = min(a, b);
        int expensiveBook = max(a, b);
        BookPair *bookPair = new BookPair(cheapBook, expensiveBook);
        books.push_back(bookPair);
    }
}

bool diffsort(BookPair *p1, BookPair *p2)
{
    return abs(p1->first - p1->second) > abs(p2->first - p2->second);
}

void allocate(BookList &books)
{
    int lavanya = 0;
    int nikhil = 0;

    for (BookList::iterator it = books.begin(); it != books.end(); ++it)
    {
        int cheapBook     = (*it)->first;
        int expensiveBook = (*it)->second;

        if (lavanya < nikhil)
        {
            lavanya += expensiveBook;
            nikhil += cheapBook;
        }
        else
        {
            nikhil += expensiveBook;
            lavanya += cheapBook;
        }
    }

    cout << abs(lavanya - nikhil) << endl;
}

int main(int argc, char* argv[])
{
    BookList books;

    readBookList(books);
    sort(books.begin(), books.end(), diffsort);
    allocate(books);

    return 0;
}
</code>```

Basically, you sort the pairs of books by the difference in price between them, largest difference first.  (1, 3) would go before (300, 300).  Then you allocate the books one pair at a time, giving the cheapest book to the child whose previous pile costs the most.

You sort by the difference instead of the absolute value of the book, because the difference is what you're trying to equalize.  This avoids problems with sets such as (1, 201) (150, 300), (150,300).  The fairest allocation is for one child to get both 300 rupee books and the 1 rupee book.  This gives them only 100 more rupees than the other child.

If you sort instead by largest absolute value, each child will get one 300 rupee book, but one child will end up with 200 more rupees than the other child.

Title: Equal Gifts Algorithm Problem

Body:
Problem Link - http://opc.iarcs.org.in/index.php/problems/EQGIFTS

It is Lavanya's birthday and several families have been invited for the birthday party. As is customary, all of them have brought gifts for Lavanya as well as her brother Nikhil. Since their friends are all of the erudite kind, everyone has brought a pair of books. Unfortunately, the gift givers did not clearly indicate which book in the pair is for Lavanya and which one is for Nikhil. Now it is up to their father to divide up these books between them.

He has decided that from each of these pairs, one book will go to Lavanya and one to Nikhil. Moreover, since Nikhil is quite a keen observer of the value of gifts, the books have to be divided in such a manner that the total value of the books for Lavanya is as close as possible to total value of the books for Nikhil. Since Lavanya and Nikhil are kids, no book that has been gifted will have a value higher than 300 Rupees...

For the problem, I couldn't think of anything except recursion. The code I wrote is given below. But the problem is that the code is time-inefficient and gives TLE (Time Limit Exceeded) for 9 out of 10 test cases! What would be a better approach to the problem?

Code -

```<code>#include<cstdio>
#include<climits>
#include<algorithm>
using namespace std;

int n,g[150][2];

int diff(int a,int b,int f) {
    ++f;
    if(f==n) {
               if(a>b) {
                       return a-b;
               }
               else {
                    return b-a;
               }
    }
    return min(diff(a+g[f][0],b+g[f][1],f),diff(a+g[f][1],b+g[f][0],f));
}

int main() {
    int i;
    scanf("%d",&n);
    for(i=0;i<n;++i) {
                     scanf("%d%d",&g[i][0],&g[i][1]);
    }
    printf("%d",diff(g[0][0],g[0][1],0));
}
</code>```

Note - It is just a practice question, & is not part of a competition.

Body:
There appears to be some confusion about my comment on Ben's answer, so here's my solution standalone:

#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <stdlib.h>
using namespace std;

typedef pair<int, int> BookPair;
typedef vector<BookPair*> BookList;

void readBookList(BookList &books)
{
    int n, a, b;
    cin >> n;
    for (int i = 0; i < n; ++i)
    {
        cin >> a >> b;
        int cheapBook = min(a, b);
        int expensiveBook = max(a, b);
        BookPair *bookPair = new BookPair(cheapBook, expensiveBook);
        books.push_back(bookPair);
    }
}

bool diffsort(BookPair *p1, BookPair *p2)
{
    return abs(p1->first - p1->second) > abs(p2->first - p2->second);
}

void allocate(BookList &books)
{
    int lavanya = 0;
    int nikhil = 0;

    for (BookList::iterator it = books.begin(); it != books.end(); ++it)
    {
        int cheapBook     = (*it)->first;
        int expensiveBook = (*it)->second;

        if (lavanya < nikhil)
        {
            lavanya += expensiveBook;
            nikhil += cheapBook;
        }
        else
        {
            nikhil += expensiveBook;
            lavanya += cheapBook;
        }
    }

    cout << abs(lavanya - nikhil) << endl;
}

int main(int argc, char* argv[])
{
    BookList books;

    readBookList(books);
    sort(books.begin(), books.end(), diffsort);
    allocate(books);

    return 0;
}

Basically, you sort the pairs of books by the difference in price between them, largest difference first.  (1, 3) would go before (300, 300).  Then you allocate the books one pair at a time, giving the cheapest book to the child whose previous pile costs the most.

You sort by the difference instead of the absolute value of the book, because the difference is what you're trying to equalize.  This avoids problems with sets such as (1, 201) (150, 300), (150,300).  The fairest allocation is for one child to get both 300 rupee books and the 1 rupee book.  This gives them only 100 more rupees than the other child.

If you sort instead by largest absolute value, each child will get one 300 rupee book, but one child will end up with 200 more rupees than the other child.


问:
How to solve cyclic dependencies in a visitor pattern
When programming at work we now and then face a problem with visitors and module/project dependencies.

Say you have a class A in a module X. And there are subclasses B and C in module Y. That means that module Y is dependent on module X. If we want to implement a visitor pattern to the class hierarchy, thus introducing an interface with the handle Operations and an abstract accept method in A, we get a dependency from module Y to module X, which we cannot allow for architectural reasons.

What we do is, use a direct comparison of the types (i.e. instanceof, since we program in Java), which is not satisfying.

My question(s) would be: Do you encounter this kind of problem in your daily work (or do we make poor architectural choices) and if so, how is your approach to solve this?

Here is a minimal example in Java to illustrate my point. Package a has ClassA and the Visitor-Interface over the ClassA Hierarchy:

```<code>package pkg.a;
public abstract ClassA extends ClassA {
    public abstract void accept(ClassAVisitor visitor);
   /* other methods ... */
}

package pkg.a;
import pkg.b.ClassB;
import pkg.b.ClassC;
public interface ClassAVisitor {
    public abstract void handle(ClassB visitee);
    public abstract void handle(ClassC visitee);
}
</code>```

Package b has the concrete classes that extend from ClassA:

```<code>package pkg.b;
import pkg.a.ClassAVisitor;
public ClassB extends ClassA {
    public void accept(ClassAVisitor visitor) {
        visitor.handle(this);
    }
}

package pkg.b;
import pkg.a.ClassAVisitor;
public ClassC {
    public void accept(ClassAVisitor visitor) {
        visitor.handle(this);
    }
}
</code>```

Package a and b have a cyclic dependency.

答:
This seems pretty simple to me.  You have three ways to avoid the circular dependency.  You can merge A and B into a single package.  You can move the visitor to package B.  You can move the visitor into another package V that depends on A and B.

My choice would be to merge the packages, or not use the visitor pattern.
Otherwise whenever someone creates a new subclass of A, they will have to update the visitor in some other source file far, far away.  It is all too likely that someone will forget to do that.


问:
Supporting early versions of Android
What policy do developers have when it comes to supporting earlier versions of Android? I still support , but this means that I am unable to use features such as the action bar. Over 40% of my users are still running versions below 3.0, so I feel somewhat constrained about this.

The problem is that 3.x was not very successful, so 2.3.x will be with us for some time. But all new devices will now be shipping with 4.x. I am wondering whether 4.x users are more likely to pay for an app, while most 2.3.x users are just looking.

Update: With a little effort, I have found that I am able to implement action bars and Holo themes, and still support Android 2.1. All this without recourse to an external library. The only feature that I am still stuck with is tab bars. These do work with action bars, but not in the approved style. For that I would need fragments, which requires Android 3.0. I only have two tab bars though, so it is not a big deal.

答:
With our app we still support Android back to Version 2.1, but are able to use all the important features of Android 4.0 using the following two components:

ActionBarSherlock

Android Compatibility Library

These two components are both free to use and enable you to use the newly introduced concepts like ActionBar and Fragments in a very easy way. The frameworks make all the work for you to make your app look and run the same on a pre 3.0 and on a 4.0 device! As you have 40% users pre 3.0, it surely is a good idea to make your app available for them. Splitting the apps for pre 3.0 users and 3.0+ users is in my opinion not a good solution, as you have more work to do to maintain both versions.

Title: Supporting early versions of Android


答:
Having worked in places with code reviews and ones without, it has become one of my make-or-break issues in looking at new employment. The time you save avoiding emergencies because the problems didn't surface until you got to prod is much higher than the time you spend in code review. And that doesn't mention how much less stressful it is to find a problem in code review.

You could start small though if the team needs convincing. Since you would like your code reviewed, start there. Ask one or more of your colleagues to meet with you for an hour or so and go over some pieces of code that you feel you would like feedback on. If the feedback is largely negative, don't get defensive. Really take notes and consider making the suggested changes. But do it on something that you haven't sent to prod yet (or frankly you won't make the changes).  You can even do it informally at your desk, just call someone over and say, "hey I'm not sure if I have the best solution here, what do you think?"

Another way to gradually get people to start to see the value of code review is to have a once-a-week session where everyone has to present a piece of code for review (or you rotate through each person but only one a week depending on the complexity of the kind of code that needs review).  Bring doughnuts or bagels the first time! If people feel uncomfortable with telling someone in person or if you think people will be too defensive, have them email the boss and have him consolidate the comments so that the person being reviewed doesn't know who said what about the code. Frankly, I prefer to know in person who said what because my own assessment of their own coding abilities will help me decide how seriously I should take the criticism.

If you can't find someone to code review your work, sit down with yourself and try to explain the code and why you are doing what you are doing as if someone was there. I'm amazed at how often it is the person who built the code who found the problem in the course of explaining what the code was for. It also helps to sit down with your requirements document as a sort of checklist and make sure you aren't missing something required.

ContentLicense: CC BY-SA 4.0


问:
How can I improve my skills while working on actual projects, in the absence of more experienced developers?
I'm the lead developer at a small company, working with C# and ASP.Net. Our team is small, 2-3 people, without much experience in development and design. I don't have the opportunity to learn from more senior developers, there is no one in my team to guide me and help me choose the best approaches, as I take care most of the projects myself.

How can I improve my software development skills while working on actual projects, in the absence of more experienced developers?

答:
There are plenty of sources to learn from aside more experienced colleagues: books, blogs of skillful developers, Stack Exchange, lectures/conferences, etc. Code reviews are also crucial, and CodeReview.SE is a precious resource.

Let's see how it could work on an example.

Example

You're reading a blog post which mentions a term "ETL". You don't know the meaning of it, but from this article, you vaguely understand that it is a sort of process or workflow which moves data from some data support to another.

You go to Wikipedia and other resources and gain a more precise vision of the thing. It's still not very clear when would it be useful to use an ETL. After all, it seems much easier to write an SQL query which will do all the work, rather than spending too much time building a real ETL.

To answer those questions, you borrow a book about the ETLs from your local library. It explains that some extract-transform-load processes are not easily doable with a simple SQL query: not only the extract phase can deal with several, diverse data supports, not just a relational database, but also the transform step can be very complicated for both validating/normalizing the data and mapping it.

You now have a clear vision of what is an ETL, how to use it and especially when you need an ETL and when it is not an appropriate tool. Meanwhile, you've implemented a small ETL as a personal project. This project allows you to discover some points which are not clear enough for you and are not covered by a book. Those points being rather abstract and not related to the source code, you post a question on Programmers.SE.

When you have an opportunity to build one in your company, you start creating it. You have a few issues. Some are related to code; you post questions on Stack Overflow. Others are related to the database; you ask the questions on DBA.SE.

Finally, there is a conference done by a highly skillful developer about how to optimize ETLs. You attend this conference and it gives you precious hints about the enhancements you can do for your project.

You also start following a blog of a developer who was working on different ETLs for years. It's interesting to see the different approaches, and through this blog, you learn about ECCD; you're interested, so you borrow The Data Warehouse ETL Toolkit by Ralph Kimball, the book which talks in detail about the "extract, clean, conform and deliver" process. The same blog also mentions lots of applications intended to create ETLs without programming skills. This is particularly useful for the ETL you've done for your company, since your boss, non-techy person, constantly asks you to do some little changes to what you've done.

Discovering things

IMHO, the difficult part, when you don't have a mentor or a more experienced colleague, is to discover things, and by discover, I mean pass from the state "I've never heard about this thing" to "I've heard about it but don't know very well what it is".

If somebody reviews my code and says that I really should start using some style conventions, with a little curiosity I can find that in programming, there are different styles of writing code, that one should stick with a style for a given language and codebase, and that many languages have tools to enforce a style (like StyleCop for C#).

If nobody tells me about the style, how would I know that such a thing exist?

That's where resources such as blogs or Stack Exchange are handy. Wikipedia wouldn't help (unless you spend days hitting random pages about programming), and books rarely talk about those things.

The same applies as well to patterns and practices or things which are less related to code. For example, I hardly imagine some developer waking up in the morning telling himself that he must learn something about ITIL while he never heart about ITIL before.

Once you discovered a new term, it is pretty easy to learn about it. If you've given a new term "code contracts" and you're a C# developer, you can easily find enough information yourself on MSDN (or, better, in Jon Skeet's book).

Curiosity helps

When I work with interns, I always notice that the best ones are those who were curious outside their lectures. They may know that there is a thing called functional programming even if none of their teachers never mentioned it, and while they may not know any functional language, they are still able to explain in general terms what is FP and how is it different from other paradigms. They may know about Agile, or about Unicode, or about partial-trust/sandbox model, just because they were reading blogs and using Stack Exchange, rather then simply attending their lectures.

Even when they don't have a mentor, they still learn all those things which are not told in college.


答:
I get criticized a lot for writing my code this way. I don't understand why anyone would not do it this way.

Readability it so important when you come back to a project after an extended period of time and I've heard a saying "Always write code if the next guy who is reading it is a Psychopath who knows your location".


答:
I'm in a similar situation: we're a small team and our core development product work is mostly incremental changes on a code base that's a few years old.

A few techniques I'm using to stay up-to-date and improve my skills.

On the Job:

Read: books, blogs, PR materials. I follow a number of RSS feeds. When the O'Reilly deal of the day is on a technology that I haven't heard of, I read through the description of the book. If the technology has much relation to anything I'm working on, I spend five or ten minutes researching it in a little more depth, similar to MainMa's answer. I repeat this with a few different RSS feeds.

Build a training plan with your management that can be supported with company resources (time and/or money)

Contrary to most programmer's tendencies, try to embrace change and new design options. Change for change's sake isn't good, but I believe too often developers avoid using a new design or framework because of change. This is a fine line to walk, and don't rush into binding decisions, but keep an eye out for new ways of doing things. Some changes can have unexpected benefits: moving to DVCS let me experiment on our code base more easily and try new technologies there.

Some people like conferences; I've found that the payoff is small for the time invested.

Outside of work:

I've found that working on my skills outside of day-to-day work is critical. The freedom to experiment, make mistakes and pursue interests keeps me engaged in IT. If I only had my on-the-job projects and needed to limit my learning to what was immediately useful, I would quickly burn out.

Get involved in a non-work project. For me, this is developing a functional website related to a personal interest. I refactor freely, and actively try to experiment with different technologies. Contributing to Open Source will get you exposure to other people's code as well. This will also give you good material to share for interviews with the company that will have more experienced developers.

Code Camp: If there is a code camp in your area attend. Because these aren't during work hours and are free, you feel the freedom to attend any sessions for topics that interest you personally. Compared to typical conferences, these are usually local and cover wide swaths of technology, so I believe there is more concentrated value.

And don't forget to visit SO or Programmers.SE frequently.

Title: How can I improve my skills while working on actual projects, in the absence of more experienced developers?

Body:
I'm the lead developer at a small company, working with C# and ASP.Net. Our team is small, 2-3 people, without much experience in development and design. I don't have the opportunity to learn from more senior developers, there is no one in my team to guide me and help me choose the best approaches, as I take care most of the projects myself.

How can I improve my software development skills while working on actual projects, in the absence of more experienced developers?


问:
Are flag variables an absolute evil?
Are flag variables evil? Are the following kind of variables profoundly immoral and is it wicked to use them?

"boolean or integer variables that you assign a value in certain places then down below you check then in orther to do something or not, like, for example using newItem = true then some lines below if (newItem ) then"

I remember doing a couple of projects where I totally neglected using flags and ended up with better architecture/code; however, it is a common practice in other projects I work at, and when code grows and flags are added, IMHO code-spaghetti also grows.

Would you say there are any cases where using flags is a good practice or even necessary?, or would you agree that using flags in code are... red flags and should be avoided/refactored; me, I just get by with doing functions/methods that check for states in real time instead.

答:
Here's an example when flags are useful.

I have a piece of code which generates passwords (using a cryptographically secure pseudorandom number generator). The caller of the method chooses whether or not the password should contain capital letters, small letters, digits, basic symbols, extended symbols, Greek symbols, Cyrillic ones and unicode.

With flags, calling this method is easy:

var password = this.PasswordGenerator.Generate(
    CharacterSet.Digits | CharacterSet.LowercaseLetters | CharacterSet.UppercaseLetters);
```

<p>and it can even be simplified to:</p>

<pre class="lang-cs prettyprint-override"><code>var password = this.PasswordGenerator.Generate(CharacterSet.LettersAndDigits);
</code>```

Without flags, what would be the method signature?

public byte[] Generate(
    bool uppercaseLetters, bool lowercaseLetters, bool digits, bool basicSymbols,
    bool extendedSymbols, bool greekLetters, bool cyrillicLetters, bool unicode);
```

<p>called like this:</p>

<pre class="lang-cs prettyprint-override"><code>// Very readable, isn't it?
// Tell me just by looking at this code what symbols do I want to be included?
var password = this.PasswordGenerator.Generate(
    true, true, true, false, false, false, false, false);
</code>```

As noted in the comments, another approach would be to use a collection:

var password = this.PasswordGenerator.Generate(
    new []
    {
        CharacterSet.Digits,
        CharacterSet.LowercaseLetters,
        CharacterSet.UppercaseLetters,
    });
```

<p>This is much more readable compared to the set of <code>true</code> and <code>false</code>, but still has two drawbacks:</p>

<p>The major drawback is that in order to allow combined values, like <code>CharacterSet.LettersAndDigits</code> you would be writing something like that in <code>Generate()</code> method:</p>

<pre class="lang-cs prettyprint-override"><code>if (set.Contains(CharacterSet.LowercaseLetters) ||
    set.Contains(CharacterSet.Letters) ||
    set.Contains(CharacterSet.LettersAndDigits) ||
    set.Contains(CharacterSet.Default) ||
    set.Contains(CharacterSet.All))
{
    // The password should contain lowercase letters.
}
</code>```

possibly rewritten like this:

var lowercaseGroups = new []
{
    CharacterSet.LowercaseLetters,
    CharacterSet.Letters,
    CharacterSet.LettersAndDigits,
    CharacterSet.Default,
    CharacterSet.All,
};

if (lowercaseGroups.Any(s => set.Contains(s)))
{
    // The password should contain lowercase letters.
}
```

<p>Compare this with what you have by using flags:</p>

<pre class="lang-cs prettyprint-override"><code>if (set & CharacterSet.LowercaseLetters == CharacterSet.LowercaseLetters)
{
    // The password should contain lowercase letters.
}
</code>```

The second, very minor drawback is that it's not clear how would the method behave if called like this:

var password = this.PasswordGenerator.Generate(
    new []
    {
        CharacterSet.Digits,
        CharacterSet.LettersAndDigits, // So digits are requested two times.
    });
```

Title: Are flag variables an absolute evil?

Body:
Here's an example when flags are useful.

I have a piece of code which generates passwords (using a cryptographically secure pseudorandom number generator). The caller of the method chooses whether or not the password should contain capital letters, small letters, digits, basic symbols, extended symbols, Greek symbols, Cyrillic ones and unicode.

With flags, calling this method is easy:

var password = this.PasswordGenerator.Generate(
    CharacterSet.Digits | CharacterSet.LowercaseLetters | CharacterSet.UppercaseLetters);

and it can even be simplified to:

var password = this.PasswordGenerator.Generate(CharacterSet.LettersAndDigits);

Without flags, what would be the method signature?

public byte[] Generate(
    bool uppercaseLetters, bool lowercaseLetters, bool digits, bool basicSymbols,
    bool extendedSymbols, bool greekLetters, bool cyrillicLetters, bool unicode);

called like this:

// Very readable, isn't it?
// Tell me just by looking at this code what symbols do I want to be included?
var password = this.PasswordGenerator.Generate(
    true, true, true, false, false, false, false, false);

As noted in the comments, another approach would be to use a collection:

var password = this.PasswordGenerator.Generate(
    new []
    {
        CharacterSet.Digits,
        CharacterSet.LowercaseLetters,
        CharacterSet.UppercaseLetters,
    });

This is much more readable compared to the set of true and false, but still has two drawbacks:

The major drawback is that in order to allow combined values, like CharacterSet.LettersAndDigits you would be writing something like that in Generate() method:

if (set.Contains(CharacterSet.LowercaseLetters) ||
    set.Contains(CharacterSet.Letters) ||
    set.Contains(CharacterSet.LettersAndDigits) ||
    set.Contains(CharacterSet.Default) ||
    set.Contains(CharacterSet.All))
{
    // The password should contain lowercase letters.
}

possibly rewritten like this:

var lowercaseGroups = new []
{
    CharacterSet.LowercaseLetters,
    CharacterSet.Letters,
    CharacterSet.LettersAndDigits,
    CharacterSet.Default,
    CharacterSet.All,
};

if (lowercaseGroups.Any(s => set.Contains(s)))
{
    // The password should contain lowercase letters.
}

Compare this with what you have by using flags:

if (set & CharacterSet.LowercaseLetters == CharacterSet.LowercaseLetters)
{
    // The password should contain lowercase letters.
}

The second, very minor drawback is that it's not clear how would the method behave if called like this:

var password = this.PasswordGenerator.Generate(
    new []
    {
        CharacterSet.Digits,
        CharacterSet.LettersAndDigits, // So digits are requested two times.
    });


答:
Usually flags can be completely replaced by some flavor of the strategy pattern, with one strategy implementation for every possible value of the flag. This makes adding new behavior a lot easier.

In performance critical situations the cost of the indirection might surface and make deconstruction into clear flags necessary. That being said I'm having trouble to remember a single case where I actually had to do that.

Title: Are flag variables an absolute evil?

Body:
Are flag variables evil? Are the following kind of variables profoundly immoral and is it wicked to use them?

"boolean or integer variables that you assign a value in certain places then down below you check then in orther to do something or not, like, for example using newItem = true then some lines below if (newItem ) then"

I remember doing a couple of projects where I totally neglected using flags and ended up with better architecture/code; however, it is a common practice in other projects I work at, and when code grows and flags are added, IMHO code-spaghetti also grows.

Would you say there are any cases where using flags is a good practice or even necessary?, or would you agree that using flags in code are... red flags and should be avoided/refactored; me, I just get by with doing functions/methods that check for states in real time instead.


问:
Event Aggregator.. not getting a response, how to determine completion?
I'm rewriting a vehicle tracking application, a google maps based thing..

The users are able to search for a vehicle by typing a few characters of the vehicles "callsign".

My application is based around a sort of "event bus" within Backbone.. when a search occurs I send a message on the bus saying something like "does anyone match this?".. If a marker matches the search term it responds with a sort of "yes, I match!"..

My challenge arises when no-one matches, I get no response.. it feels a little hacky to "wait a little while" and check if a response has been recieved..

The application is based around Backbone.js and using the Event Aggregator pattern described in the answer to this question on Stack Overflow: https://stackoverflow.com/questions/7708195/access-function-in-one-view-from-another-in-backbone-js

Is there a well defined design pattern that might assist me here? Sending a request for a response and not getting any responses?

答:
Could they not all reply with a NoResultFound message?

You know how many domains you have, so if they all reply with NoResultFound, then you'll know what to do.

I guess this depends on the UI that you have. Assuming your UI has a list of search domains, then once the result comes back from each domain, you can display it to the user:

DomainA - Searching...

DomainB - No Results Found

DomainC - Searching...

DomainD - No Results Found

etc


答:
The issue I have seen when maintaining code that makes use of flags is that the number of states grows quickly, and there are almost always unhandled states. One example from my own experience: I was working on some code that had these three flags

```<code>bool capturing, processing, sending;
</code>```

These three created eight states (actually, there were two other flags as well). Not all the possible value combinations were covered by the code, and users were seeing bugs:

```<code>if(capturing && sending){ // we must be processing as well
...
}
</code>```

It turned out there were situations where the assumption in the if statement above was false.

Flags tend to compound over time, and they hide the actual state of a class. That is why they should be avoided.

Title: Are flag variables an absolute evil?

Body:
The issue I have seen when maintaining code that makes use of flags is that the number of states grows quickly, and there are almost always unhandled states. One example from my own experience: I was working on some code that had these three flags

bool capturing, processing, sending;

These three created eight states (actually, there were two other flags as well). Not all the possible value combinations were covered by the code, and users were seeing bugs:

if(capturing && sending){ // we must be processing as well
...
}

It turned out there were situations where the assumption in the if statement above was false.

Flags tend to compound over time, and they hide the actual state of a class. That is why they should be avoided.


答:
I'm assuming we are talking about flags within method signatures.

Using a single flag is bad enough.

It will mean nothing to your colleagues the firs time they see it. They'll have to look at the source code of the method in order to establish what it does. You will probably be in the same position few months down the line, when you forget what your method was all about.

Passing a flag to the method, normally means that your method is responsible for multiple things. Inside the method you are probably doing a simple check on the lines of:

```<code>if (flag)
   DoFlagSet();
else
   DoFlagNotSet();
</code>```

That's a poor separation of concerns and you can normally find a way around it.

I normally have two separate methods:

```<code>public void DoFlagSet()
{
}

public void DoFlagNotSet()
{
}
</code>```

This will make more sense with method names that are applicable to the problem that you are solving.

Passing multiple flags is twice as bad. If you really do need to pass multiple flags, than consider encapsulating them within a class. Even then, you will be still facing the same problem, as your method is likely doing multiple things.

Title: Are flag variables an absolute evil?

Body:
I'm assuming we are talking about flags within method signatures.

Using a single flag is bad enough.

It will mean nothing to your colleagues the firs time they see it. They'll have to look at the source code of the method in order to establish what it does. You will probably be in the same position few months down the line, when you forget what your method was all about.

Passing a flag to the method, normally means that your method is responsible for multiple things. Inside the method you are probably doing a simple check on the lines of:

if (flag)
   DoFlagSet();
else
   DoFlagNotSet();

That's a poor separation of concerns and you can normally find a way around it.

I normally have two separate methods:

public void DoFlagSet()
{
}

public void DoFlagNotSet()
{
}

This will make more sense with method names that are applicable to the problem that you are solving.

Passing multiple flags is twice as bad. If you really do need to pass multiple flags, than consider encapsulating them within a class. Even then, you will be still facing the same problem, as your method is likely doing multiple things.


答:
The answers here will likely be of great help, but I would like to stress something: nothing can replace working with someone better than you (for arbitrary, and personal, definitions of better) for 8 hours a day, 5 days a week. That much is certain.

If you're the type of developer who always wants to get better, always wants to learn, then you will have to go to a different company eventually. That much is inevitable, and should be planned for.

When you find the company that's right for you, you'll find that you can continue to grow within it, than grow out of it.


答:
Flags and most temp variables are a strong smell.  Most likely they could be refactored and replaced with query methods.

Revised:

Flags and temp variables when expressing state, should be refactored to query methods.  The state values (booleans, ints, and other primatives) should almost -always- be hidden as part of the implementation details.

Flags that are used for control, routing, and general program flow may also indicate the opportunity to refactor sections of the control structures into seperate strategies or factories, or whatever might be situationally appropriate, that continue to make use of the query methods.

Title: Are flag variables an absolute evil?


答:
There was a good blog post by Martin Fowler recently. Things that I took away from it are:

It has nothing to do with how long you've been working for somebody. You work for three years and you become a senior developer. What happens after six years? Do you become a senior senior developer?

Senior developers don't look down at you or think that they are better than you. That's very important. Once you let your ego get in your way, you are in trouble.

Senior developers don't pass the blame. They anticipate problems and they address them in a positive manner.

People want to work with senior developers. This is a key for me. I want people to work with me and I want them to enjoy working with me.

Senior developers are not the smartest engineers. They don't work on the most complex problems. Their skill set isn't all about programming. Their communication skills play equally important role.

Senior developers are good at estimating.

Senior developers always care about what they do. They understand that boring tasks must be completed to the same quality as any other, potentially more interesting tasks.

Just to clarify

Skills that I have listed above is what I believe a good senior software engineer should have in addition to fundamental software engineering skills and practices.

Title: When should you call yourself a senior developer?

Body:
Possible Duplicate:

  Whats the difference between Entry Level/Jr/Sr developers?

I'm curious what senior developer means because apparently the definition doesn't mean what I thought it would. I keep seeing these teens at 22-23 years old who call themselves senior X developer or senior Y developer. To me, a senior must have 10 years or so experience in programming to call himself 'senior'. I've seen a lot of these teens here (hence the question). Am I wrong? Why?


答:
Before I get to any suggestions, I have to say that I was in a very similar position just over a year ago.

If you are getting the projects done, but you feel that there is a lot of space to improve, than that's a good thing.

On one occasion I didn't have a technical ability and confidence to complete the project. Often I would buy a book, I would read a fairly technical blog and would find myself "out of my depth". I think the biggest problem for me was the fact that I didn't have exposure to any large enterprise applications. Quite often I would do something well, but I wouldn't have anybody by my side to validate what I've done.

This was demotivating and challenging, so I see where you are coming from. How did I address this issue? I left a company and joined a well established software development house, which has helped me to gain a lot of experience in the past year.

Unless you want to leave the company, I would suggest books that have been written by the pioneers of our industry. I would start with The Pragmatic Programmer by Andrew Hunt. The book contains tons of useful analogies that are very easy to remember. First few chapters of this book have encouraged me to pick up a very different programming language to the one we use at work. I've started to read non-technical literature - I now believe that reading novels and science fiction will make me a better programmer. Writing essays isn't far away from writing clean code. Some writers are good and some are bad. This book made me care about what I write. One of the analogies is called "Broken Windows". You leave a car abandoned on a street for days and nothing happens to it. Once you break a single window, the car will be probably destroyed on the next day. Code is no different. If you see broken or poorly written code, then fix it right away, don't just leave it there because sooner or later it will come back to "haunt" you. Once you start working your way through this book you'll pick up dozens of similar analogies that will make you think about code in a different way.

I would then suggest you move on to Clean Code by Robert C. Martin. This book is more practical as it forces you to read bad and good (clean) code. Author uses code samples from one of the open source projects. You say there is nobody to guide you. There is a perfect opportunity to look at somebody else's code, compare it with your own, and see how you can improve it. To me reading this book was like shadowing somebody working on a project. The book also makes a strong emphasis on the easiest hardest thing - separation of concerns. The author has asked pioneers of our industry what they consider to be a "clean" code. Once you read their answers, you'll be able to compare them to your own opinion on what clean code is all about.

Finally, have you considered working on open source projects? You will be collaborating with other, probably more experienced developers who will be able to review your code and point you in a right direction.

As I've said in my original answer, it won't happen over the night. I've been doing this for few years now and almost every day I find out that I have been doing it wrong.

Good luck!


问:
What are the PHP web server architecture components and the purpose of each one of them?
Given below is an image of a basic PHP web server architecture:

Would someone please explain the several components available and how they interact?

I'm more concerned of how the PHP Core operates and relates to the other components, so feel free to elaborate on this point specifically.

This Diagram was taken from here.

答:
Very roughly:

SAPI transfers (and translates) the data received by the http daemon (but not necessarily only it, see Wikipedia) to the PHP framework

PHP Core is the "basic" functionality provided by the language (e.g. what allows you to use echo $variable)

PHP API is additional functionality you can use to access separate services (e.g. a database) - the exact line between those two is a bit fuzzy (imho)

ZEND is the engine that actually executes the PHP scripts (compiler and runtime environment) - see wikipedia again.


答:
When I hear “Senior Developer” I think of someone who has mastered programming. I think of a person who can design, code and test a system. They can talk to system architecture or component design. They understand and use design patterns.  This person can anticipate the performance bottlenecks, but knows not to pre-optimize. This person will leverage asynchronous programming, queuing, caching, logging, security and persistence when appropriate. When asked they can give a detail explanation of their choice and the pros and cons. In most cases they have mastered object oriented programming and design, this not an absolute other languages such as Javascript, F#, Scheme are powerful and are not object oriented. They are adept in risk management and most important of all they can communicate the before mentioned to their peers.

What is mastery? There is a generally accepted idea, that to master ANY one skill it takes 10,000 hours of repetition for the human body and mind to grasp and internalize a skill. This is written to at length in Malcolm GladWell’s book Outliers.
When the original author talked about mastering a field, he was refering to reach the top of a highly competitive field would take 10,000 hours.

Some examples of in Malcolm GladWell’s Outliers are:

Mozart his first concerto at the young age of 21. Which at first seems young, but he has been writing music since he was 11 years old.

The Beatles were initially shunned. They were told they did not have the mustard and should consider a different line of work. They spend 3 years in Germany playing about 1200 times at different venues, each time being 5 to 8 hours in length. They re-emerged as the Beatles we know and love today.

And lastly, Bill Gates at age 20 dropped out of Harvard to found Microsoft. To some this might seem foolish, but considered at 20 he had spent nearly half of his young life programming. In 1975, only maybe 50 people in the world had the experience he did. His experience gave him the foresight to see the future in Microsoft.

Peter Norvig also discusses the 10,000 hours rule in his essay “Teach Yourself Programming in Ten Years”.

In the book Mastery by George Leonard, great detail is given on how to master a skill. One must practice the skill over and over and over again. The more the repetition, the more you become aware of the differences in each repetition. Only with this insight can you become better.

The software industry’s titles (Junior, Mid-Level and Seniors) are misleading and inconsistent from organization to organization. I’ve worked with companies, who defined a Senior Developer as someone with 5 years or more of experience. There is no mention to the quality of the experience, just that they sat in front of a computer for 5 years. In working with these folks, many of them had not yet grasp object oriented programming -- yet they were considered Senior Developers.

There must be a better more objective way to measure the skill set of a software engineer. John Haugeland posted a computer programmer’s skills matrix. It’s an objective way to measure a programmer’s skill level, which otherwise is left to gut feeling.

When looking at software engineers I see 4 tiers of skills: Luminary, Senior, Mid-Level and Junior.

Luminary (10+ years) is one who has mastered a skill and has set about improving their respective discipline. Some examples include: Ted Neward, Uncle Bob Martin, Donald Knuth, Oren Eini, Peter Norvig, Linus Torvalds. Luminaries change based on your skill-set.

Senior (7 to 10+ years, Level 3)  is one who has spent the last 10,000 hours programing in a specific genre. There is a strong understanding of design patterns, They leverage asynchronous programming, queuing, caching, logging, security and persistence when appropriate.

It’s very possible that a Senior will never reach Luminary. Luminaries are often found speaking and writing. They are actively trying to impact their discipline.

Mid-Level (4 to 6 years, Level 2) is one who understands day to day programming. They work independently and create robust solutions. However they have yet to experience creating or maintaining large or complex systems. In general Mid-Level developers are great with component level development.

Junior (1 to 3 years, Level 1) is one who understands the basics of programming. They either have a degree in software engineering or computer science or they are self taught. Their code is continually reviewed. Guidance is given in regards to algorithms, maintainability and structure.


问:
As a Junior Software Engineer should I say that something has been done wrong if I feel so?
I recently joined a company and it is my first job. When reading the code base, I felt that the code was not well written. It seemed to me that the code had most of the problems mentioned here and also seemed to have an Anemic Domain Model. There are no unit tests and they don't employ any code quality checking tools like findbugs or pmd. The problem I have is that the code is very difficult to understand. Maybe my conclusions are wrong because I am not that experienced. I need advice on whether to communicate the above facts to a superior or not. If I am to communicate, to whom(Tech Lead, Architect, Product Manager) and how? And if I do communicate will they take it badly since I'm a Junior and has no experience?</p>

答:
Don't be afraid to question anything, just don't start pointing fingers.  For all you know, you could be experiencing a sever case of Expert Beginners, and people may have just become set in their ways.  In which case, you could always try to enlighten them.  But, developer egos aren't easy to deal with.

This also may be legacy code that was written before the time of the current developers.  They may be just as disgruntled over it as you are.


问:
Do you have to be good at math to be a good programmer?
It seems that conventional wisdom suggests that good programmers are also good at math. Or that the two are somehow intrinsically linked. Many programming books I have read provide many examples that are solutions to math problems, or are somehow related to math as if these examples are what make sense to most people.

So the question I would like to float is: do you have to be good at math to be a good programmer?

答: Not all maths are about crunching numbers. Anyone who can program is good at math relevant to programming. Remember: Mathematics is the study of patterns!</p>

OwnerDisplayName: Charles Roper


答:
No, flags are not bad or an evil that must be refactored away at all costs.

Consider Java's Pattern.compile(String regex, int flags) call.  This is a traditional bitmask and it works.  Glance at the constants in java and wherever you see a bunch of 2n you know there are flags being there.

In an ideal refactored world, one would instead use an EnumSet where the constants are instead values in an enum and as the documentation reads:

The space and time performance of this class should be good enough to
  allow its use as a high-quality, typesafe alternative to traditional
  int-based "bit flags."

In a perfect world, that Pattern.compile call becomes Pattern.compile(String regex, EnumSet<PatternFlagEnum> flags).

All that said, its still flags.  It is much easier to work with Pattern.compile("foo", Pattern.CASE_INSENSTIVE | Pattern.MULTILINE) than it would be to have Pattern.compile("foo", new PatternFlags().caseInsenstive().multiline()) or some other style of trying to do what flags really are and good for.

Flags are often seen when working with system level things.  When interfacing with something at the operating system level, one is likely to have a flag somewhere - be it the return value of a process, or the permissions of a file, or the flags for opening a socket.  Trying to refactor these instances away in some witch hunt against a perceived code smell will likely end up with worse code than if one used accepted and understood the flag.

The problem occurs when people misuse flags tossing them together and creating a frankenflag set of all sorts of unrelated flags or trying to use them where they aren't flags at all.

Title: Are flag variables an absolute evil?