问:
How to structure classes in a large codebase
One of the most touted rules of OOP is to keep classes small. This means that in a significantly sized project there are bound to be thousands of classes.

Logically it seems to make sense to combine related classes into various "subsystems" (or various levels of subsystem). My understanding of Demeter's law here is that a class in subsystem X shouldn't directly talk to a class in subsystem Y; instead subsystem Y should provide a façade to abstract the details of individual classes within it. However, in a complex application that façade must by definition be a large class. with many methods, even though it doesn't really do much.

So should I be using façade classes (presumably at several levels) to maintain a hierarchical structure of subsystems, or should I treat each class as a separate entity and use it directly?

答:
That sounds like a nightmare to maintain.  It just creates even more classes to maintain.

If your language supports packages, namespaces or the like, use them.  Use the language, or develop package naming conventions, to hide subsystem internal stuff from external subsystems.

But there's no reason that a class in one package shouldn't talk to a class in another if that's the right thing to do.


答:
So should I be using façade classes (presumably at several levels) to maintain a hierarchical structure of subsystems, or should I treat each class as a separate entity and use it directly?

Your focus should generally be on coupling.

For some classes (basic dtos, utilities that are invariant), just using them directly is fine. No need to implement an abstraction that provides no benefit.

But for the majority of your code, you will want to introduce decoupling abstractions (interfaces, messages, events) so that you can change the underlying implementation without breaking the contract between that code and its consumers.

That general pattern holds as you move from functions and classes to subsystems and modules. Some are going to be core functionality that would require wholesale changes if you stop using it. But most are going to want to supply some contract (a library API, web API, protocol, message queues, data buses, etc.) that abstracts away their implementation so that you can change the implementation without breaking the contract between the code and its consumers.

How to do that and where to do that depends mightily on what problems you're facing, and is well beyond what any answer here can provide.

ContentLicense: CC BY-SA 3.0

Title: How to structure classes in a large codebase

Body:
One of the most touted rules of OOP is to keep classes small. This means that in a significantly sized project there are bound to be thousands of classes.

Logically it seems to make sense to combine related classes into various "subsystems" (or various levels of subsystem). My understanding of Demeter's law here is that a class in subsystem X shouldn't directly talk to a class in subsystem Y; instead subsystem Y should provide a façade to abstract the details of individual classes within it. However, in a complex application that façade must by definition be a large class. with many methods, even though it doesn't really do much.

So should I be using façade classes (presumably at several levels) to maintain a hierarchical structure of subsystems, or should I treat each class as a separate entity and use it directly?


问:
Do licenses matter if there's nobody around to enforce them?
Suppose that the original creators can't (or won't) enforce a license on their software/code, but that work is still popular.

I guess if you want to visualize it, I'll throw out a convoluted hypothetical:

Imagine a very small group of developers that released a code project under an open-source license. The repository was hosted on their servers. However, everybody on the immediate development team passed away in a tragic accident or something. Their servers shut down after this happened. The project had a fairly large user base, and so others began to host the last revision on their own servers for others to download.

(Yes, I have an active imagination)

Does abiding by the license simply become a matter of morality by its users, or can there still exist a legal penalty when there is no one user or group to enforce it? Could anything be done if an unscrupulous user decided to branch off the project and use it under a different license?

I am not looking for legal advice -- I am simply curious about how software licenses work. I tend to think of strange situations and wonder what would happen in those scenarios.

答:
In the case you describe, intellectual property owners are the direct descendant(s) of the deceased developers.

Intellectual property owners will usually sue unauthorized parties:

If there is a strategic reason to do it (usually for big corporations)

If the other party is able to pay a judgement/settlement

As a matter of principle

To annoy or destroy them

Pick one or more reason!

My lawyer always told me:

if you leave other party without being sued you train them to do it again.

I think it's pretty good advice.

ContentLicense: CC BY-SA 2.5


问:
Can domain models in the database be a sustainable solution?
I just started at a new job as a database developer for a medium-small sized, company based on Microsoft-technology. I noticed early on how much practices deviate from what I've been taught at school regarding best practices, design patterns, testing and project management.

What is bugging me the most is how our main database developer (henceforth called "John") keeps the model schema in the database! We do this by having 3 "magic" tables; one for database-schemas, one for tables and one for columns.

Inserting a record into the "Tables"-table generates (through a database trigger), the actual, corresponding table. Inserting a row into the "Rows"-table updates the referenced table with that row.
These are in turn read by his homemade C#-program to generate C# models, which  are used by the frontend-developers for controllers and outwards.

Apart from this, most of the development is done according to the ASP.NET MVC framework.

I see a couple of flaws with this approach:

We need him to maintain the ORM, and he rarely has the time to do so (job security is good!)

The The triggers for the "Tables" and "Rows" table are flawed. They don't support table updates, nor Check-constraints or more "advanced" features. While we could surely improve them, I am not yet sure if this is the way to go.

Keeping the programmatic logic in the database feels weird and restrictive (although it is possible to extend his models through C#).

His C# Model-generator has to be run manually by one of 3 people (among which I am one), and is not yet mature enough to be included into an automated build process.

Several people have suggested phasing in a true and tested product like Entity Framework, but he dismisses it, claming that keeping the business logic in the code-layer is only suitable for small-scale applications and bootstrap projects for startups.

This post is leading towards something that could look like a opinionated discussion, but that is not my intention. I just want some clarification regarding our architectural approach.

Can keeping the domain models in the database be a sustainable solution for a company in growth?

答:
You're describing an Inner Platform.

The problem with inner platforms is that you reinvent all of the mechanisms of a platform or technology (in this case, a relational database) that have been honed and perfected over decades of evolution and effort, but re-inventing it poorly.  You're bypassing all of the optimizations that are available to those who choose a more conventional design, and trading initial simplicity and elegance for future complexity and hardship.

That said, if the end product of this process is real tables and real classes modelling real business domain objects, I don't see much harm in this approach, apart from the immaturity of the tools.  Stack Exchange actually uses their own, homegrown ORM, and that seems to have worked out for them.  So I know that these kinds of "cottage" approaches can work.

Note that most ORM's that take the "table-first" approach simply look at the table structure in the database to create the classes.  The "table" and "row" tables that your friend has created is merely metadata that already exists in the system tables of most modern relational database systems.

Further Reading

The "Vision" project, a cautionary tale about inner platform effect

(You can skip the preamble and start reading at the subheading "Introducing Vision")

ContentLicense: CC BY-SA 4.0


问:
What techniques are used in solving code golf problems?

"Regular" golf vs. code golf:

Both are competitions.  Both have a well-defined set of rules, which I'll leave out for simplicity.  Both have well-defined goals; in short, "use fewer hits/characters than your competitors."

To win matches, athletic golfers rely on

equipment

Some situations call for a sand wedge; others, a 9-iron.

techniques

The drive works better when your feet are about shoulder width apart and your arms are relaxed.

and strategies

Sure, you could take that direct shortcut to the hole... but do you really want to risk the water hazard or sand bunker when those trees are in the way and the wind is so strong?  It might be better to go around the long way.

What do code golfers have that's analagous to athletic golfers' equipment, techniques and strategies?

Sample answer to get this started: use the right club!  Choose GolfScript instead of C#.

答:
And as always: Know your library!

For most problems, there essential functions are already in the shipped libs. Of course you have to choose a non-verbose language for this or the imports of the needed functions will get longer than a short inline definition.


问:
Ruby: if variable vs if variable.nil?
I'm new to Ruby and I was surprised when I found out that all objects are true apart from nil and false. Even 0 is true.

A nice thing about that property of the language is that you can write:

```<code>if !variable
  # do stuff when variable is nil
end
</code>```

My colleagues, who are more seasoned Ruby developers, insist I should choose that instead of using .nil? like so:

```<code>if variable.nil?
  # do stuff when variable is nil
end
</code>```

However I believe that the latter is a better option for two reasons:
1. I think it's more object oriented, especially in a language like Ruby where everything is an object and message exchange.
2. It is more readable, in my subject opinion, even if it is less compact.

Am I making a "newbie" mistake here?

答:
Write what you mean. Mean what you write.

Lets take a different test.  .vowel?

```<code>if char == 'a'
   # do stuff
end
</code>```

vs

```<code>if char.vowel?
   # do stuff
end
</code>```

Now, its obvious that these do not do the same thing.  But if you're only expecting char to be a or b it will work.  But it will confuse the next developer - the second block will be entered into for the conditions where char is [eiou] also.  But for a, it will work correctly.

Yes, it is the case that nil and false are the only falsy values in Ruby. However, if you are testing for nil by testing for nil || false, this isn't what you mean.

It means that the next developer (who happens to be a crazy axe murder who knows your home address) will read the code, and wonder why false should go in there too.

Write the code that conveys exactly what you mean.

Title: Ruby: if variable vs if variable.nil?

Body:
Write what you mean. Mean what you write.

Lets take a different test.  .vowel?

if char == 'a'
   # do stuff
end

vs

if char.vowel?
   # do stuff
end

Now, its obvious that these do not do the same thing.  But if you're only expecting char to be a or b it will work.  But it will confuse the next developer - the second block will be entered into for the conditions where char is [eiou] also.  But for a, it will work correctly.

Yes, it is the case that nil and false are the only falsy values in Ruby. However, if you are testing for nil by testing for nil || false, this isn't what you mean.

It means that the next developer (who happens to be a crazy axe murder who knows your home address) will read the code, and wonder why false should go in there too.

Write the code that conveys exactly what you mean.


问:
How to abbreviate "Local" for a time variable, like UTC
In a database I work on, most of the datetimes I store are converted to and from UTC so all of my datetime columns end in UTC such as CanceledUTC.

I have a situation where I need to store a "local" time and want to signify that it is a local time in the column name.

Is there a convention for signifying local datetime variable names?

I know that storing "local" datetimes is a bad practice so I'm also considering storing it as a string, but that's not the question here.

答:
Nothing.

The name of the column should be CancelledTime or CancelledAt, and the column should have type TIMESTAMP. It will be stored timezone-agnostically, but automatically have the timezone of the session taken into consideration when values are inserted and retrieved.

If that is not possible for some reason, then fine make it a DATETIME … but give it a COMMENT line that indicates the field values are local time representations. This really seems like a bad idea, though: local time when? Insert before daylight savings, retrieve after daylight savings → you're hosed.

Certainly, though, information about the data representation doesn't belong in the field name. What the data is belongs in the field name. And your data is (presumably) "the time at which a thing was cancelled".


问:
Sort a list while putting together or after?
I have to read through an extremely large amount of network data from various log files, and compile relevant information about that data to perform statistical analysis on it (the top communicators, top ip addresses that send on average the largest packets, average packet size, etc.) I decided to make a matrix where each index in the outer array corresponds to a sorted list of ips in incremental order.

To get an idea of my data set, I have a log file that is generated each day which has information regarding all the communication that occurred within a network that day. I have been generating log files since the middle of May and each log file has about 5 million lines each, so the more efficient this program is, the better.

My question is the following:

When I am compiling data from all the log files into this matrix, should I sort my outer array layer by IPs while I'm still putting together the data, or do I just append the new IPs to the end of the file as I find them and then sort the list afterwards? Is there a better option here that I haven't thought of? which way would be the most efficient? I am going to be using python 2.7, if that makes a difference. Also, due to restrictions on what I can do, I cannot install any new modules to the machine this code will run on, so unless I can create a database with python natively, that isn't  an available option to me.

答:
Insertion sort works best when you are inserting a new value into something that is already sorted. So what I would do is use Quicksort to sort the original dataset that you have, then when additional log entries come in, add them one by one into the already sorted set.

With Quicksort being O(n*logn) and Insertion Sort being O(n) when used with an already sorted set, the total time for everything will be O(a * log(a) + b), where a is the size of the original data set and b is the additional logs you place in afterwards.


问:
How to document GUI screens transitions of a complex application
There is an application based on multiple screen model with pretty complex net of transitions between these screens.

It has some similarities to a web page or Football Manager like games. Its main properties are:

It has screen stack and it has back/history like function.

Events cause screen transitions.

Some of screens can work in different contexts (the source screen and external conditions influence what transitions are possible).

Loops are possible

Due to a lack of better idea I have started with a state diagram and PlantUML and it worked good until the scale started to become a problem. In the mean time I catched many bugs very often related to screen transitions. The application development is probably already suffering from this complexity and lack of this kind of documentation.

After two weeks of pretty intensive analysis and map drawing the map is totally in progress and it becomes harder and harder to maintain it even when I have a fresh knowledge about it.

What approach should I adopt to produce a useful GUI map of this application? How do people manage such things in a time efficient way?

答:
What approach should I adopt to produce a useful GUI map of this application?
    How do people manage such things in a time efficient way?

Quick Short Answer

State Transitions Charts are a good idea.

Represent each different screen as a single transition, very general, not too much detail, first. Add detail later.

Long Boring Extended Answer

I have work in several applications, similar to your use case.

And, configuration or setup "wizards", are a good example.

Like many developers, I ended using a state transition approach like you.

Remember U.M.L. is not the only way to model State Transitions, altought is a very good tool, and is today's standard

Sometimes, using a square with a label indicating some screen, for each screen, and arrow with labels indicating parameters that indicate transitions are enough.

As, I previously mention, State Diagrams are OK.

I read your question, and several stuff got my attention.

[1] Not sure, but, I think you are modeling screen too much detailed, model each screen very generic, first. You may add more detailed specifications, later.

[2] As you mention, you are using the same screen several times, with several parameters, as if it was a different screen or object.

Is not a bad idea, but, you could also get confused with too many settings.

Model each screen instance or ocurrence, as a different screen, with generic properties first.

[3] Are you using the right tool for modeling ?

A lot of people, on this UML days, jump straight to use software.

Many developers, start with a chalk-blackboard, or a marker-whiteboard, and, later, use some software, for modeling.

I have tried several software, both commercial, and open source.

For many reasons, I ended, using OpenOffice / LibreOffice Draw application.

Many UML software sometimes, have a lot of features on some modules, and lack others.

You are using a tool to compile a programming language into a diagram. Not bad idea, for small projects.

But, for very large projects, your mind may be doing extra work, and making you harder to think.

I suggest to switch to do visual diagrams or chart, directly, maybe with a whiteboard, a notebook, or a visual designer, like Umbrello, Libre Office Draw, or others.


问:
How to design class model for specific products, some of which may contain groups of specific product models
Class Design Question

I am trying to figure out a good way to design my class system.

I have a class Product to compute various product specifications.  I have two product model groups, each containing several model numbers:  {10, 20, 30} and {50, 60, 70}.  They share some similar features (i.e. the way weight is computed) but have different product add-on computations (i.e. some features depend on product length and some do not, depending on the model group)

The class model I currently have is main Product for all models (actually originally for 50, 60, 70 only), and a specific model Product10 was added on later and works for model 10 only.   Now, a new addition brought on models 20, and 30, which are similar to model 10.  Instead of adding them as separate classes, nearly identical to 10, I thought it was time to redesign.

Problem

In my current implementation, class Product10 is feeding off the main Product class (responsible for "most models") and Product10 is being the odd one out.  Maybe it is fine, but now I am getting more model numbers similar to Product10 and I am seeking a better way to structure my code.

Currently I see that there are quite a few ways to design this.

create a class for each model (may be wasteful)

create a "god class" that contains code for all models (class may be bloated)

create subgroups for models, i.e. one class that covers a set of models like {10, 20, 30} or {50, 60, 70}

something else.

What I seek

I seek a good way to use OO design for my specific situation...  Namely,

I think it is a good idea to have a generic class of some sort

I am not sure whether I should create a class for to represent "a set of similar models" or whether to treat models separately

My goal is to create an appropriate class based on model number.

What could be a good class decomposition?

答:
I think it is a good idea to have a generic class of some sort
    I am not sure whether I should create a class for to represent "a set of similar models"
    or whether to treat models separately
    My goal is to create an appropriate class based on model number.
    What could be a good class decomposition?

Quick Short Answer

"God Class" is a good idea, that is already used by others.
Sometimes, "A class for represent a set of similar models" applies,
sometimes "model number" applies.

Long Extended Boring Answer

Contrary to what many people do, one way to design a clas hierarchy,
is not to have any hierarchy at all, and start with several independent classes.

Check which features does the classes share, as properties,
what operations does, and how operations are done.

Another, thing to consider, is that some values,
that are shared by several classes,
maybe computed, and some not.

That is a way to detect fields from properties.

Figure 1, shows a U.M.L. class diagram,
with 3 non related classes.

```<code>..............................
..+------------------------+..
..|  None: Model10Class    |..
..+------------------------+..
..| [+] string: ModelName; |..
..| [+] float:  Weight;    |..
..| [+] FSize:  Size;      |..
..| [+] ColorType: Color;  |..
..| [+] ...                |..
..+------------------------+..
..| [+] void:   Function1; |..
..| [+] ...                |..
..+------------------------+..
..............................
..+------------------------+..
..|  None: Model20Class    |..
..+------------------------+..
..| [+] string: ModelName; |..
..| [+] float:  Weight;    |..
..| [+] FSize:  Size;      |..
..| [+] ColorType: Color;  |..
..| [+] ...                |..
..+------------------------+..
..| [+] void:   Function1; |..
..| [+] void:   Function2; |..
..| [+] ...                |..
..+------------------------+..
..............................
..+------------------------+..
..|  None: Model30Class    |..
..+------------------------+..
..| [+] string: ModelName; |..
..| [+] float:  Weight;    |..
..| [+] FSize:  Size;      |..
..| [+] ColorType: Color;  |..
..| [+] ...                |..
..+------------------------+..
..| [+] void:   Function1; |..
..| [+] void:   Function2; |..
..| [+] void:   Function3; |..
..| [+] ...                |..
..+------------------------+..
..............................
</code>```

Since, "ModelName", "Weight", "Size",
and "Function1" are shared by all classes,
lets generate a new base class with those members,
and, subclass the previous classes from it.

The "..." means maybe there are, or not, other members,
shared or not by other classes.

Figure 2, shows a U.M.L. class diagram,
where a base class was extracted from the 3 classes.

```<code>..+------------------------+..
..|   None: ProductClass   |..
..+------------------------+..
..| [+] string: ModelName; |..
..| [+] float:  Weight;    |..
..| [+] FSize:  Size;      |..
..| [+] ColorType: Color;  |..
..+------------------------+..
..| [+] void:   Function1; |..
..+------------------------+..
..............................
..+------------------------+..
..|  None: Model10Class    |..
..+------------------------+..
..| [+] ...                |..
..+------------------------+..
..| [+] ...                |..
..+------------------------+..
..............................
..+------------------------+..
..|  None: Model20Class    |..
..+------------------------+..
..| [+] ...                |..
..+------------------------+..
..| [+] ...                |..
..| [+] void:   Function2; |..
..+------------------------+..
..................................
..+----------------------------+..
..| Model20Class: Model30Class |..
..+----------------------------+..
..| [+] ...                    |..
..+----------------------------+..
..| [+] ...                    |..
..| [+] void:   Function3;     |..
..+----------------------------+..
..................................
</code>```

Note, that "Model30" also has the same members than "Model20".

[under construction]

...

Body:
I think it is a good idea to have a generic class of some sort
    I am not sure whether I should create a class for to represent "a set of similar models"
    or whether to treat models separately
    My goal is to create an appropriate class based on model number.
    What could be a good class decomposition?

Quick Short Answer

"God Class" is a good idea, that is already used by others.
Sometimes, "A class for represent a set of similar models" applies,
sometimes "model number" applies.

Long Extended Boring Answer

Contrary to what many people do, one way to design a clas hierarchy,
is not to have any hierarchy at all, and start with several independent classes.

Check which features does the classes share, as properties,
what operations does, and how operations are done.

Another, thing to consider, is that some values,
that are shared by several classes,
maybe computed, and some not.

That is a way to detect fields from properties.

Figure 1, shows a U.M.L. class diagram,
with 3 non related classes.

..............................
..+------------------------+..
..|  None: Model10Class    |..
..+------------------------+..
..| [+] string: ModelName; |..
..| [+] float:  Weight;    |..
..| [+] FSize:  Size;      |..
..| [+] ColorType: Color;  |..
..| [+] ...                |..
..+------------------------+..
..| [+] void:   Function1; |..
..| [+] ...                |..
..+------------------------+..
..............................
..+------------------------+..
..|  None: Model20Class    |..
..+------------------------+..
..| [+] string: ModelName; |..
..| [+] float:  Weight;    |..
..| [+] FSize:  Size;      |..
..| [+] ColorType: Color;  |..
..| [+] ...                |..
..+------------------------+..
..| [+] void:   Function1; |..
..| [+] void:   Function2; |..
..| [+] ...                |..
..+------------------------+..
..............................
..+------------------------+..
..|  None: Model30Class    |..
..+------------------------+..
..| [+] string: ModelName; |..
..| [+] float:  Weight;    |..
..| [+] FSize:  Size;      |..
..| [+] ColorType: Color;  |..
..| [+] ...                |..
..+------------------------+..
..| [+] void:   Function1; |..
..| [+] void:   Function2; |..
..| [+] void:   Function3; |..
..| [+] ...                |..
..+------------------------+..
..............................

Since, "ModelName", "Weight", "Size",
and "Function1" are shared by all classes,
lets generate a new base class with those members,
and, subclass the previous classes from it.

The "..." means maybe there are, or not, other members,
shared or not by other classes.

Figure 2, shows a U.M.L. class diagram,
where a base class was extracted from the 3 classes.

..+------------------------+..
..|   None: ProductClass   |..
..+------------------------+..
..| [+] string: ModelName; |..
..| [+] float:  Weight;    |..
..| [+] FSize:  Size;      |..
..| [+] ColorType: Color;  |..
..+------------------------+..
..| [+] void:   Function1; |..
..+------------------------+..
..............................
..+------------------------+..
..|  None: Model10Class    |..
..+------------------------+..
..| [+] ...                |..
..+------------------------+..
..| [+] ...                |..
..+------------------------+..
..............................
..+------------------------+..
..|  None: Model20Class    |..
..+------------------------+..
..| [+] ...                |..
..+------------------------+..
..| [+] ...                |..
..| [+] void:   Function2; |..
..+------------------------+..
..................................
..+----------------------------+..
..| Model20Class: Model30Class |..
..+----------------------------+..
..| [+] ...                    |..
..+----------------------------+..
..| [+] ...                    |..
..| [+] void:   Function3;     |..
..+----------------------------+..
..................................

Note, that "Model30" also has the same members than "Model20".

[under construction]

...


问:
How to structure a chain of method calls
To keep it simpler for any client of my class, I have put a sequence of private method calls within one public method.

The client then calls this method and all the methods within run to complete the action. E.g:

```<code> public void DoRejection(string comments, string rejectionType)
    {
        GetPartstoReject();
        UpdateRejectedPartsStatus(rejectionType);
        RemoveInitiatingRejectionPart();
        ClearRejectedPartsData();
        CreateNewOpenPart();
        SaveRejectionComments(rejectionType, comments);
    }
</code>```

The downside I can see to this is it is harder to unit test as each private method won't be tested in isolation (following the best practice of only unit testing public methods).

How can this be better designed to enhance testability but still make it simple for a client to call?

答:
You have a problem.  You see a symptom of it in the difficulty in testing the methods behind DoRejection(), but that is only a symptom of the problem, not the problem itself.

The underlying problem is that you have a method that hides sequential coupling.

A co-worker of mine (a few employers ago) had a saying:

If you use the word 'and' when describing what the method does, you need to break this method into smaller parts.

Another way of saying this is "You've violated the single responsibility principle for this method."  It is doing too many things.  The method does not simply "do a rejection", but it rather:

updates the part status

removes the rejected part

clears the rejected part data

creates a new part

commits the rejection with comments

This are far too many things that are going on behind the scene. If this is part of a transaction, expose the transaction.  The reason you are having difficulty testing the parts in isolation is because they are not in isolation. The state of removing the rejected part data requires that the respected part be removed.

A classic approach to this, as part of exposing the methods, is to impose a design by contract.  Check the preconditions, and if they are not met, raise an error.

You could also impose the sequence by returning an object that wraps the underlying class and only presents the appropriate next states.

This would be especially useful if you wanted to be able to update multiple parts but only do this as one commit.

There are other problems that creep into this that have corresponding code smells.  Methods that take no arguments (and return no values), especially when sequential coupling is in play, are acting on the object state as a pseudo-global value.  There are methods that indicate that there are side effects that the next method depends on. This raises some very serious questions about the underlying design and has a very strong code smell to them.

Its hard to say exactly where the problem is from this small sample of code, but it is fairly clear that there is a significant problem with the design foundations upon which this code is based.


问:
How does having too many instance variables lead to duplicate code?
According to Refactoring to Patterns:

When a class is trying to do too much, it often shows up as too many
  instance variables. When a class has too many instance variables,
  duplicated code cannot be far behind.

How does having too many instance variables lead to duplicate code?

答:
Too many instance variables means too much state. Too much state leads to duplicated code that is only slightly different for each of the states.

This is classic single concrete class doing too many things that should be sub-classes or compositions.

Find a few classes that have too many instance variables, you will see they maintain way too much state and have lots of duplicated code paths that are only slightly specialized for each case, but so convoluted that they can not be broken apart into reusable methods. This is one of the biggests sources of side effects as well.

There is at least one exception to this that does not fall into this category and is an easy way to remediate this. Immutableobjects do not have this problem, because they are a fixed state, there is not any chances for convoluted state management or side effects.


答:
Having too many instance variables is not directly related to duplicate code, or vice versa. This statement, in this generality, is false. One can throw two separate classes with no duplicate code into one class - that produces a new class with unseparated responsibilities and too many instance variables, but still no duplicate code.

But when you find a class with too many responsibilites in real world legacy code, chances are high the programmer who wrote it did not care for clean code or SOLID principles (at least, not at the time when he wrote that code), so its not unlikely you will find other code smells like duplicate code in there.

For example, the "copy-paste reuse" anti-pattern is often applied by copying an old method and making some slight modifications to it, without proper refactoring. Sometimes, to make this work, one has to duplicate a member variable and modify that variable a little bit, too. This might result in a class with too many instance variables (more precise: too many very similar looking instance variables). In such a situation, the similar instance variables maybe an indicator for repeated code elsewhere in the class. However, as you noted, this is an artificial example, and I would not conclude a general rule from it.

Body:
According to Refactoring to Patterns:

When a class is trying to do too much, it often shows up as too many
  instance variables. When a class has too many instance variables,
  duplicated code cannot be far behind.

How does having too many instance variables lead to duplicate code?


问:
Can I fully automate Docker deployment of a .Net CoreCLR on a CI Server without installing Visual Studio?
I'm experimenting with the deployment of ASP.Net 5 CoreCLR apps to Linux Docker containers. Literally all the articles, posts, etc. I found involve using the Visual Studio GUI. On publish a PowerShell script gets created, which I believe I could re-use on a CI server. But this script itself seems to depend on an installed VS14 including the Docker extension:

```<code>function Ensure-DockerCommand {
    [cmdletbinding()]
    param()
    process {
        if (! (Get-Command docker -errorAction SilentlyContinue))
        {
            $vsInstallPath = (Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0" -Name InstallDir | select -ExpandProperty InstallDir)
            if ([string]::IsNullOrEmpty($env:ProgramW6432)) {
                $vsKeyPath = "HKLM:\SOFTWARE\Microsoft\VisualStudio\14.0"
            }
            else {
                $vsKeyPath = "HKLM:\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0"
            }

            $vsInstallPath = (Get-ItemProperty $vsKeyPath -Name InstallDir | select -ExpandProperty InstallDir)
            $dockerExtensionPath = Join-Path $vsInstallPath "Extensions\Microsoft\Windows Azure Tools\Docker"
            $env:Path = "$dockerExtensionPath;" + $env:Path
        }
    }
}
</code>```

Has anybody managed to do this without installing Visual Studio on a build server?

Or do you think this question is premature, because support for this is just not available yet. I can't find any relevant documentation.

答:
You definitely don't need Visual Studio installed. You don't even need DNVM or DNX installed or run in a Windows environment. You do however need the Docker client and access to a Docker host.

Here are some instructions on how to build and run ASP.Net 5 Docker images:
Link

The gist of it is that you create a Dockerfile in the root of your project:

```<code>FROM microsoft/aspnet

COPY . /app
WORKDIR /app
RUN ["dnu", "restore"]

EXPOSE 5004
ENTRYPOINT ["dnx", "-p", "project.json", "kestrel"]
</code>```

And then simply issue the Docker build command:

```<code>docker build -t myapp .
</code>```

And then you run it:

```<code>docker run -t -d -p 80:5004 myapp
</code>```

The default ASP.Net image uses the Mono runtime, but if you want to use the CoreCLR runtime you can simply specify a tag in the FROM statement:

```<code>FROM microsoft/aspnet:1.0.0-beta8-coreclr
</code>```

See the aspnet-docker repository for updated information on what tags are available: https://github.com/aspnet/aspnet-docker

Body:
You definitely don't need Visual Studio installed. You don't even need DNVM or DNX installed or run in a Windows environment. You do however need the Docker client and access to a Docker host.

Here are some instructions on how to build and run ASP.Net 5 Docker images:
Link

The gist of it is that you create a Dockerfile in the root of your project:

FROM microsoft/aspnet

COPY . /app
WORKDIR /app
RUN ["dnu", "restore"]

EXPOSE 5004
ENTRYPOINT ["dnx", "-p", "project.json", "kestrel"]

And then simply issue the Docker build command:

docker build -t myapp .

And then you run it:

docker run -t -d -p 80:5004 myapp

The default ASP.Net image uses the Mono runtime, but if you want to use the CoreCLR runtime you can simply specify a tag in the FROM statement:

FROM microsoft/aspnet:1.0.0-beta8-coreclr

See the aspnet-docker repository for updated information on what tags are available: https://github.com/aspnet/aspnet-docker


答:
The statement you cite is meant to be seen in a specific context.

According to my experience, I cannot confirm that "many instance variables in general indicate duplicated code". Also, note that this belongs to the "code smells", and there are allegedly contradicting smells. Have a look here:

http://c2.com/cgi/wiki?CodeSmell

Amusingly, you will find "too many instance variables" is as good a code smell as "too few instance variables".

But there are problems with instance variables, be it too few or too many:

Every instance variable may mean some kind of status of the object. Stati always need a careful treatment. You must ensure that you have covered all possible combinations of stati in order to avoid unexpected behavior. You must always clearly now: which status does my object have right now? From this angle, a lot of instance variables may indicated that the class has become unmaintainable. It may also indicate that a class does too many jobs, as it needs so many stati.

Every instance variable requires you to keep oversight, which methods alter the variable in what way. So, suddenly, you don't know any longer all the cooks that are cooking. One of them, programmed tiredly at late night, will spoil your soup. Again: too many of such variables will lead to code difficult to penetrate.

The other side: too few instance variables may cause that many methods must handle their information with too much work and with too much parameters. You feel this, if you are giving to many of your methods a certain equal parameter, and all methods do somehow a very similar thing with this parameter. In that situation, your code will start to bloat. You will end up scrolling many screens up and down in order to get some simple things together. Here, a refactoring may help: introduce one instance variable and one clear entrance to it. Then, free all the methods.

Last but not least: If many instance variables of a class have their setter and getter each, then it may indicate that other classes don't use this first class the right way. There is a discussion about "Why getters and setters are evil". The idea in short is, if a class Rectangleoffers some getX(), and dozens of other classes use rectangle.getX(), then you are writing code that is not robust against the "ripple effect" (how far around is a code change influencing other code). Simply ask what happens if you change the type from int to double? According to this discussion, many of the rectangle.getX() calls should in fact better be calls like rectanlge.calculateThisThingForMe(). So, very indirectly, duplicated code could emerge from many instance variables, as many classes around use many getters and setters doing very similar things, i.e. copied things, that should better be moved inside the class.

Many or few instance variables remains a permanent trade off, altering both ways while the software is growing.

Title: How does having too many instance variables lead to duplicate code?


问:
Why Garbage Collection if smart pointers are there
These days, so many languages are garbage collected. It is even available for C++ by third parties. But C++ has RAII and smart pointers. So what's the point of using garbage collection? Is it doing something extra?

And in other languages like C#, if all the references are treated as smart pointers(keeping RAII aside), by specification and by implementation, will there still be any need of garbage collectors? If no, then why is this not so?

答:
Garbage collection basically just means that your allocated objects are automatically released at some point after they're not reachable any more.

More accurately, they're released when they become unreachable for the program, as circularly referenced objects would never get released otherwise.

Smart pointers just refer to any structure that behaves like an ordinary pointer but has some extra functionality attached. These include but are not limited to deallocation, but also copy-on-write, bound checks, ...

Now, as you have stated, smart pointers can be used to implement a form of garbage collection.

But the train of thought goes the following way:

Garbage collection is a cool thing to have, as it's convenient and I have to take care of fewer things

Therefore: I want garbage collection in my language

Now, how can get GC into my language?

Of course, you can design it like this from start. C# was designed to be garbage collected, so just new your object and it'll be released when the references fall out of scope. How this is done is up to the compiler.

But in C++, there was no garbage collection intended. If we allocate some pointer int* p = new int; and it falls out of scope, p itself is removed from the stack, but nobody takes care of the allocated memory.

Now the only thing you have from start are deterministic destructors. When an object leaves the scope it has been created in, its destructor is called. In combination with templates and operator overloading, you can design a wrapper object that behaves like a pointer, but uses destructor functionality to clean up resources attached to it (RAII). You call this one a smart pointer.

This is all highly C++ specific: Operator overloading, templates, destructors, ... In this particular language situation, you have developed smart pointers to provide you with the GC you want.

But if you design a language with GC from start, this is merely an implementation detail. You just say object will be cleaned up and the compiler will do this for you.

Smart pointers like in C++ wouldn't probably be even possible in languages like C#'s, which have no deterministic destruction at all (C# works around this by providing syntactic sugar for calling a .Dispose() on certain objects). Unreferenced resources will finally be reclaimed by the GC, but it undefined when exactly this will happen.

And this, in turn, can allow the GC to do its work more efficient. Being built in deeper into the language than smart pointers, which are set on top of it, the .NET GC can e.g. delay memory operations and perform them in blocks to make them cheaper or even move memory around for increasing efficiency based on how often objects are accessed.


答:
Simply put: poor separation of concerns within code, leads to code that is not modular, leads to poor reuse, leads to duplicated code.

If you never try to repeat functionality, you won't get duplicated code, and many instance variables, will not be a problem.

If you do try to repeat functionality, then monolithic code, which isn't modular, cannot be reused. It does too much and can only do what it does. To do something similar, but not the same, it's "easier" to cut and paste, rather than to break up the monolithic code. Experiences programmers know that duplicated code is the road to hell.

So whilst many instance variable itself isn't the root cause of the problem it is a strong "smell" that the problem is coming.

The language "cannot be far behind" is weaker than saying "must surely follow" so the author is not claiming it must happen but will eventually happen; if you need to reuse functionality but cannot as the code isn't modular.


答:
Inserting everything takes no comparisons, sorting it afterwards is in O(n*log(n)) so inserting and then sorting is in O(n * log(n))

Inserting one element into a sorted list so as to maintain a sorted list is logarithmic in the size of the list, so inserting n elements into that list is in O(n * log(n)) since the size of the list grows as you keep inserting elements.

It therefore has similar complexity in terms of comparisons, but inserting an element in python is much more costly than appending (linear with the size of the list instead of constant). The most efficient is therefore to append everything and then sort.

Here is a sample code to check the performance of processing 10000 random numbers :

```<code>import random
import timeit
import bisect

def append_then_sort(data):
    result = []

    for element in data:
        result.append(element)

    result.sort()
    return result

def insert_sorted(data):
    result = []

    for element in data:
        bisect.insort_left(result, element)

    return result

if __name__ == '__main__':
    numbers = [random.randint(0, 3000000) for _ in xrange(10000)]
    print('Append then sort:')
    print(timeit.timeit('append_then_sort(numbers)', setup='from __main__ import append_then_sort, numbers', number=10))
    print('Insert sorted:')
    print(timeit.timeit('insert_sorted(numbers)', setup='from __main__ import insert_sorted, numbers', number=10))
</code>```

And the results on my machine :

```<code>Append then sort:
0.0509831905365
Insert sorted:
0.27309513092
</code>```

You might also be interested in looking into the sqlite3 module which is part of the standard python library so should be available on your system. I'm not sure of how well sqlite handles large databases however...

Title: Sort a list while putting together or after?

Body:
I have to read through an extremely large amount of network data from various log files, and compile relevant information about that data to perform statistical analysis on it (the top communicators, top ip addresses that send on average the largest packets, average packet size, etc.) I decided to make a matrix where each index in the outer array corresponds to a sorted list of ips in incremental order.

To get an idea of my data set, I have a log file that is generated each day which has information regarding all the communication that occurred within a network that day. I have been generating log files since the middle of May and each log file has about 5 million lines each, so the more efficient this program is, the better.

My question is the following:

When I am compiling data from all the log files into this matrix, should I sort my outer array layer by IPs while I'm still putting together the data, or do I just append the new IPs to the end of the file as I find them and then sort the list afterwards? Is there a better option here that I haven't thought of? which way would be the most efficient? I am going to be using python 2.7, if that makes a difference. Also, due to restrictions on what I can do, I cannot install any new modules to the machine this code will run on, so unless I can create a database with python natively, that isn't  an available option to me.

Body:
Inserting everything takes no comparisons, sorting it afterwards is in O(n*log(n)) so inserting and then sorting is in O(n * log(n))

Inserting one element into a sorted list so as to maintain a sorted list is logarithmic in the size of the list, so inserting n elements into that list is in O(n * log(n)) since the size of the list grows as you keep inserting elements.

It therefore has similar complexity in terms of comparisons, but inserting an element in python is much more costly than appending (linear with the size of the list instead of constant). The most efficient is therefore to append everything and then sort.

Here is a sample code to check the performance of processing 10000 random numbers :

import random
import timeit
import bisect

def append_then_sort(data):
    result = []

    for element in data:
        result.append(element)

    result.sort()
    return result

def insert_sorted(data):
    result = []

    for element in data:
        bisect.insort_left(result, element)

    return result

if __name__ == '__main__':
    numbers = [random.randint(0, 3000000) for _ in xrange(10000)]
    print('Append then sort:')
    print(timeit.timeit('append_then_sort(numbers)', setup='from __main__ import append_then_sort, numbers', number=10))
    print('Insert sorted:')
    print(timeit.timeit('insert_sorted(numbers)', setup='from __main__ import insert_sorted, numbers', number=10))

And the results on my machine :

Append then sort:
0.0509831905365
Insert sorted:
0.27309513092

You might also be interested in looking into the sqlite3 module which is part of the standard python library so should be available on your system. I'm not sure of how well sqlite handles large databases however...


问:
How are head first books?
I have never read any of them but I find their style interesting and unique.  I am not sure if they are worth giving money/time?</p>

答: I've never used them, but my brother swears by them. He thinks the balance of learning by explanation and learning by example is just right. </p>

Title: How are head first books?


问:
What are the advantages of a 'traditional' 'backend' architecture for a standard CRUD app?
In the past few years, 'client-side' web applications have become popular. A common approach nowadays is to have the backend as thin as possible, mostly exposing an API for the client-side Javascript app to consume.

What I'm interested in is not the advantages of this approach, as this seems to be the preffered approach today and its pros have been discussed on this site.

I'm interested in the advantages of the more traditional, backend-based approach. Where the templating and routing of pages happens on the backend, and the frontend logic is thin.

Please note, that this question refers to standard 'CRUD' applications, not to specialized video-editing software or programs executing intense algorithms (this kind of computation obviously needs to happen on the backend).

I'm referring to the advantages of a backend architecture for your 'typical web app'.

答:
The benefit appears every time you hit the constraint of the client-side execution. Consider three cases:

A video processing application. What would be the constraint? Right, the CPU and memory constraints of a browser running on a client machine. You'll rapidly notice that many actions are either practically impossible to run, or take hours instead of seconds.

Anything which uses gigabytes of data. A search over billions of records in the database could take milliseconds when done by the server. If done by the client, it will take seconds to hours, depending on the internet speed.

A smart algorithm that you want to hide from your competitors. Anyone can read JavaScript. By moving the logic to the server side, you make it difficult to impossible to reverse engineer.

Another benefit of having the logic on server-side is, of course, the fact that you can control exactly the run time environment. You can chose the operating system, the programming language, even the underlying hardware. In client-side scripting world, you don't have this freedom. Your code can end up running on an ancient PC with Windows XP and IE7, or a tablet, or a smartphone, or a device used by a person with vision disability using text-to-speech and speech-to-text interfaces.


问:
How to handle it when a commit in-progress suddenly appears to depend on another that isn't there yet?
I'm inexperienced with Git but I try my best to get used to it, and so far I'm just using it for projects I work on alone.

When I code there's some top-down approach naturally (as I can't know the future), and there's a reoccurring theme:

I do some work.

I find out that to get my work into something "commitable" I need to do other work.

The other work deserves it's own commit.

By something commitable I mean something that compiles or something that isn't a total mess.

And by something that deserves it's own commit I'm referring to that I learned that commits should do just one thing.

The way I resolve it is cumbersome. If the other work is in another file I make a new branch, commit there, and merge. If the work is in the same file.. ugh.. I make a local copy and reset the file to it's state in HEAD, make the needed commit and then begin to restore my work from the copy. How should I actually handle that? I don't imagine this is the way, is it? I don't assume so because it must come up somewhat often to everyone (who don't know the future too, at least). Or maybe it seems my workflow is likely to be flawed?

答:
There are multiple ways to solve this.

If you want to do the changes for the first commit without interferring with your current changes, you might want to use git stash. This will put all your open changes away, allowing you to restore them later. Use git status to see that they are not present anymore. Now create the first commit as you are used to. Next you can use git stash pop to restore your original changes and create the second commit, doing your primary work.

Another way would be to do all required changes and then create two commits, both containing a part of your work. To do so you could use the index (also known as the staging area) provided by git. This is a special area you can use to prepare commits. Assuming you have changed multiple files, you can add each of them to the index using git add. When doing git commit only the files added to the index will be committed. git status will show you which parts of your changes will be committed and which won't. For example it will look this way after changing files a.txt, b.txt and c.txt and afterwards doing git add a.txt:

```<code>On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   a.txt

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   b.txt
        modified:   c.txt
</code>```

When you are doing git commit in this state, only the changes to a.txt will be added to your commit.

Additional you can review the exact changes to be committed using git diff --cached, which will show you a diff of all changes which are going to be committed.

If one file contains changes for both commits, you can also add only parts of it to the index by using "git add --patch b.txt". git will provide you an interactive mode which asks you for each change in the given file if it should be added to the index. This might get harder if you have changes in lines next to each other, which need to be splitted in the two commits, however there are ways to solve that too.

If you want to learn more about the staging area you might want to read this:
http://gitready.com/beginner/2009/01/18/the-staging-area.html

You also might want to read more about interactive adding here:
http://nuclearsquid.com/writings/git-add/

Body:
There are multiple ways to solve this.

If you want to do the changes for the first commit without interferring with your current changes, you might want to use git stash. This will put all your open changes away, allowing you to restore them later. Use git status to see that they are not present anymore. Now create the first commit as you are used to. Next you can use git stash pop to restore your original changes and create the second commit, doing your primary work.

Another way would be to do all required changes and then create two commits, both containing a part of your work. To do so you could use the index (also known as the staging area) provided by git. This is a special area you can use to prepare commits. Assuming you have changed multiple files, you can add each of them to the index using git add. When doing git commit only the files added to the index will be committed. git status will show you which parts of your changes will be committed and which won't. For example it will look this way after changing files a.txt, b.txt and c.txt and afterwards doing git add a.txt:

On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   a.txt

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   b.txt
        modified:   c.txt

When you are doing git commit in this state, only the changes to a.txt will be added to your commit.

Additional you can review the exact changes to be committed using git diff --cached, which will show you a diff of all changes which are going to be committed.

If one file contains changes for both commits, you can also add only parts of it to the index by using "git add --patch b.txt". git will provide you an interactive mode which asks you for each change in the given file if it should be added to the index. This might get harder if you have changes in lines next to each other, which need to be splitted in the two commits, however there are ways to solve that too.

If you want to learn more about the staging area you might want to read this:
http://gitready.com/beginner/2009/01/18/the-staging-area.html

You also might want to read more about interactive adding here:
http://nuclearsquid.com/writings/git-add/


答:
There are tasks which can only be done on a server, and some which can only be done on a client. In other cases, there are some reasonably clear advantages of implementing something on back-end over front-end:

Better caching options, e.g. Varnish and similar technologies

Often, speed - as benchmarks show, typical Java/C# code is still faster than JavaScript. However, SPA wins in cases when a bottleneck is the networking vs calculations

Simpler development for one platform vs. developing for 8+ different browsers, and hence simpler maintenance

"Hiding logic" and cheating prevention. For example, if you're building an online game, some parts you may want to be done on a server to prevent cheating/hacking by modifying a game logic on a client. Also, if you want to hide some algorithm from your users, you do the same

Often, lack of some features in browsers, or inefficiency of such features. For example, building a report on big amount of data using various data aggregation functions can be done efficiently in SQL, but not in JavaScript

Title: What are the advantages of a 'traditional' 'backend' architecture for a standard CRUD app?

Body:
In the past few years, 'client-side' web applications have become popular. A common approach nowadays is to have the backend as thin as possible, mostly exposing an API for the client-side Javascript app to consume.

What I'm interested in is not the advantages of this approach, as this seems to be the preffered approach today and its pros have been discussed on this site.

I'm interested in the advantages of the more traditional, backend-based approach. Where the templating and routing of pages happens on the backend, and the frontend logic is thin.

Please note, that this question refers to standard 'CRUD' applications, not to specialized video-editing software or programs executing intense algorithms (this kind of computation obviously needs to happen on the backend).

I'm referring to the advantages of a backend architecture for your 'typical web app'.


问:
Ambiguity in method overloading
The book I am reading on Java states something confusing and unacceptable.

Learning About Ambiguity

When you overload methods, you risk creating an ambiguous situation - one which the compiler cannot determine which method to use. For example, consider the following overloaded computeBalance() method declarations:

```<code>public static void computeBalance(double deposit)
public static void computeBalance(double withdrawal)
</code>```

If you declare a double variable named myDeposit and make a method call such as computeBalance(myDeposit);, you will have created an ambiguous situation. Both methods are exact matches for your call.  You might argue that a call using a variable named myDeposit "seems" like it should go to the version of the method with the parameter named deposit, but Java makes no assumptions based on variable names.  Each version of computeBalance() could accept a double, and Java does not presume which one you intend to use.

This violates the rules for overloading a method. How can a method be overloaded with the same parameter list? Isn't it impossible or am I not getting something? I have tried and compiled such a code, it returns the following error (which makes sense):

```<code>method computeBalance() is already defined in class XXX
</code>```

答:
I agree with your assessment that this is poor, wrong and/or misleading text.

As you have pointed out, the compiler will complain based on these declarations alone: no call to computeBalance is required.  These declarations taken together are in error, there is no (legal) overloading going on here.

The idea from the text that

You might argue that a call using a variable named myDeposit seems like it should go to the version of the  method with the parameter named deposit ...

is an odd suggestion to say the least.  The author appears to be evoking a hypothetical situation (variable name matching (to resolve erroneously declared overloads)) that isn't very apropos of how these languages work, but then goes on to say they don't work like that.  Silly if you ask me.

For what it's worth, there are much better examples of ambiguous overloads that could be presented.

Two methods with the same name each taking one parameter of a different (class) type.  Then you call that method name passing null.  The compiler will not know which of the overloads to invoke: you'd have to cast null to one of those types.

Title: Ambiguity in method overloading


问:
What are the drawbacks of sending XML to browsers and let them apply XSLT?
Context

Working as a freelance developer, I often made websites completely based on XSLT. In other words, on every request, an XML file is generated, containing everything we need to know about the page content: the name of the user currently logged in, the top menu entries, if this menu is dynamic/configurable, the text to display in a specific area of the page, etc. Then XSL process (caches, etc.) it to HTML/XHTML page to send to the browser.

It has a good point to make it easier to create small-scale websites, especially with PHP. It is a sort of template engine, but which I prefer to other template engines because it's much more powerful than most of template engines, and because I know it better and like it. It is also possible, when need, to give an access to raw XML data on demand for an automated access, without the need to create separate APIs.

Of course, it will fail completely on any medium-scale or large-scale website, since, even with good caching techniques, XSL still degrades overall website performance and requires more CPU serverside.

Question

Modern browsers have the ability to take an XML file and to transform it with an associated XSL file declared in XML like <?xml-stylesheet href="demo.xslt" type="text/xsl"?>. Firefox 3 can do it. Internet Explorer 8 can do it too.

It means that it is possible to migrate XSL processing from the server to the client side for 50% of users (according on browser statistics on several websites where I may want to implement this). It means that those 50% of users will receive only the XML file at each request, thus reducing their and server's bandwidth (XML file being much shorter than its processed HTML analog), and reducing server's CPU usage.

What are the drawbacks of this technique?

I thought about several ones, but it doesn't apply in this situation:

Difficult implementation and the need to choose, based on the browser request, when to send raw XML and when to transform it to HTML instead. Obviously, the system will not be much more difficult then the actual one. The only change to make is to add XSL file link to every XML, and to add a browser check.

More IO and bandwidth usage, since the XSLT file will be downloaded by the browsers, instead of being cached by the server. I don't think it will be a problem, since XSLT file will be cached by the browsers (like images, or CSS, or JavaScript files are cached actually).

Possibly some problems on client side, like maybe problems when saving a page in some browsers.

Difficulty to debug code: it is impossible to obtain an HTML source the browser is actually using, since the only displayed source is the downloaded XML. On the other hand, I rarely go look at HTML code on client side, and in most cases, it is unusable directly (whitespace being removed).

答:
Sending compact XML and having a cached XSLT on client may even save your bandwidth.

You leave out any browsers that don't support XSLT, like smartphones. But you should create a speialized version for these anyway.


问:
Are the paradigms of ReactJS and Redux worthwhile for things other than web-development?
I'm a bit fascinated by the current paradigms shift libraries like ReactJs and Redux have caused in web development. Apart from computer science classes, I wasn't much affected by functional programming, immutability and so on, and I've yet to develop something in a purely functional language.

While there are a lot of projects that offer a bridge between the more traditional frameworks/languages and React, they all are concerned about web development. I've googled a bit around, but I've not found anything related to applying the new methods to other areas in development (besides React Native), especially in languages that are not considered as purely functional.

Would applying their methods be a worthwhile endeavour in other areas and languages like Java, C# or Python? Do such question stem from a fundamental misunderstanding on my part?

答:
React is using a functional approach for creating interfaces: given some state, it produces rendered page fragments using only pure functions. Aside from technical details (like its virtual DOM), there's nothing special about that. In languages like Haskell it's the most natural way to do that, and it's just about that time when guys from JS community (including myself) finally start understanding, using and appreciating the beauty of functional programming

Redux, as described in it's documentation, leverages CQRS and event sourcing architectural patterns to perform state mutations in a predictable and manageable way.

In both cases, their basis ideas existed long before those frameworks were created. Applied to web development, these ideas produce very interesting results, like hot reloading, time-travelling debuggers, etc. So these ideas are not new, but their applications are.

As for your question: yes, you can use these paradigms/patterns in other languages and frameworks.

FP as a paradigm is obviously used in many languages

You can do event sourcing and CQRS in Java, C#, etc., because these are patterns, so they are not specific to some language or framework


问:
Why don't style-guides include longer explanations why something should be done in a particular way?
When I read coding style guides, such as the AirBnB Javascript Style Guide I just realized that these often do not provide deeper explanations why something should be done in a particular way.

At most there are brief statements, rarely links e.g. "It won't work in IE8. More info."

Why is that that so? At least a list of references or a link to an annotated version would be more helpful, e.g. to new employees that must work with such a style guide.

Are there notable counterexamples, for any language? (Cannot read them all)

I'd consider these style guides as "living documents", and over time I would expect them to grow into more verbose versions with many links, conserving lessons learned  and documenting how to avoid obscure edge-cases.

It's okay to start with a bare-bones document. That's easier to read. but shouldn't evolve these documents, a longer version indicating a more "mature" style-guide?

答:
First, a style guide is neither a tutorial, nor a text book for learning best practices. If you want comprehensive explanations, you need to read a book like "Code Complete", or something of similar size. But that is nothing you read in one or two hours.

Moreover, lots of details in style guides are opinionated, and some rules are just there to impose consistency within a team. There is often nothing like a "deeper explanation", sometimes its just "the majority of our devs voted for function names starting with upper case letters, that's why we picked this style".


答:
Where I work, the used/defined code style guides were the result (essence) of former discussions among developers. Usually nobody is interested in reproducing longer discussions, but interested in documenting their outcome. Typically those guidelines are intended for the new staff. Usually you do not create a new styleguide, when you hired a new team member - since discussions are time consuming - and do not lead that much into new insights.

If you need an in depth knowledge why a particular rule is created/used you must ask the writers themselves or I fear you must research this for yourself why a particular rule was created.

Title: Why don't style-guides include longer explanations why something should be done in a particular way?

Body:
When I read coding style guides, such as the AirBnB Javascript Style Guide I just realized that these often do not provide deeper explanations why something should be done in a particular way.

At most there are brief statements, rarely links e.g. "It won't work in IE8. More info."

Why is that that so? At least a list of references or a link to an annotated version would be more helpful, e.g. to new employees that must work with such a style guide.

Are there notable counterexamples, for any language? (Cannot read them all)

I'd consider these style guides as "living documents", and over time I would expect them to grow into more verbose versions with many links, conserving lessons learned  and documenting how to avoid obscure edge-cases.

It's okay to start with a bare-bones document. That's easier to read. but shouldn't evolve these documents, a longer version indicating a more "mature" style-guide?


答:
They are great, you can definitely start a new topic with those books without any pre-knowledge on those topics, But, If you are already familier about those topics, then sometimes, you will feel a slow learning. Simple, for beginners, those are great!

I've read, Head First SQL, Head First Servlet and JSP, Head First EJB(3) without any prior knowledge on those topics, I've a nice explanation from there.

Title: How are head first books?

Body: I have never read any of them but I find their style interesting and unique.  I am not sure if they are worth giving money/time?</p>


问:
Android Service vs Simple class with thread for network access
I am in quite a dilemma about how to solve my problem regarding network access. I checked this question but it does not really gives a solution for my problem.

All of my REST based requests are routed through my own HttpRequestExecutor class that will execute each request asynchronously and results will be sent back via handler passed to it per request.

Some of these requests are originating from UI and needs to end there as well for example Sign in request. In most cases user has to wait till it finishes. I would like to write some high level and specialized class for each of such use case as it may do some business level processing before and/or after request is executed. The result will be handed down to the originating Activity.

This could be done either using a Service or simple Java class both using thread. I am not sure which way to go.

A simple Java class would be straight forward and simple solution but I feel Service may be the correct way to do it. What I am really concerned about using Service is the boiler plate code that goes into using it i.e. binder or messaging to communicate with Activity.

For this problem which is the correct way to solve? Also does Service provide some extra advantages in this case?

答:
Your question is similar to: Android Design - Service vs Thread for Networking.  I have been looking for some guidance on this, and I'm drawing some points from the accepted answer there.

Put in the work for the Service. It de-couples the functionality from the UI and can be used in future Apps. Use your simple Java class as the internals. The interface of a Service makes the code more easily re-usable and more easily extensible.


问:
How to model hashtags with nodejs and mongodb
Existing architecture: nodejs server with mongodb backend.

I have strings coming in describing images that can have #hashtags in them.

I wish to extract the hashtags from the strings, store the hashtags and associate the image with that hashtag.

So e.g. an image is uploaded with 'having fun at #bandcamp #nyc'

#bandcamp and #nyc are extracted.

If they don't exist as hashtags already, they're created and the image is associated with them both.

If they do exist, that's recognised and the image is associated with both.

So it will be possible to build a mongo find query that gets all images for a hashtag or multiple hashtags.

I'm new to nosql, I understand that in relational I'd have:

table hashtags

table images

table imageshashtags

with a many to many relationship. An image can have many hash tags, and a hashtag can have many images.

What sort of approach is suitable with mongo?
From reading q&a like this: https://stackoverflow.com/questions/8455685/how-to-implement-post-tags-in-mongo

I see that I can implement a sub document in the image document with the tags. Is that efficient for searching and retrieving?

I could then use http://cookbook.mongodb.org/patterns/count_tags/ - map reduce?

So end up with:

images collection withwith tags subdocument
tags collection

images document with tags subdocument with tags extracted and added to it when the image is created, and new tag added to the collection if it's not already present (i.e. tags must be unique)

also create the tag in the tags collection, and run map reduce.

Is that sound? Am I understanding things correctly and is my approach sensible?

答:
Store hashtags in an array within a document.

That's the benefit of having documents: you can simply nest them. And, in this particular case, it's trivial:

```<code>{
    "_id": 123,
    "file": "c43a5f46-kitten.png",
    "description": "My kitten :3 #kittens #cute"
    "hashtags": ["kittens", "cute", "cat", "animals"]
}
</code>```

(I added some "synonymous" tags, this can be done automatically by looking up some other document.)

This is the most natural solution for document-oriented database:

Searching documents by hashtags is trivial if you just add an index, as well as inserting, updating, and deleting hashtags on random documents is also trivial

Massive inserting, updating, and deleting is a bit tricky, because you'd probably want to split such operations in multiple "batches", but still it's manageable and not hard to implement

Complex aggregations can be done with the standard aggregation pipeline or map-reduce

On the other hand, if you go with relational style, you'll be in a big trouble when you reinvent a SQL JOIN within your application code. This is one of the most common anti-patterns of using MongoDB (and such). Here's a very typical pseudocode:

```<code>for (HashTag tag: mongodb.hashtags.find()) {
   for (Image img: mongodb.images.find(
           new Document("_id", new tag.getImageId()))) {
       // ...
   }
}
</code>```

This is inefficient, not scalable, and you are simply reinventing a wheel. Using this, you'll probably end up with complexity of O(N*M) because of loops within your code. If you'd choose SQL with foreign keys instead, you'd have something like O(N*log(M)) or even O(N+M).

There are no tables (relations) and foreign keys in MongoDB. Do not invent them, please. Use SQL instead, if you need. In fact, I highly suggest using SQL instead of MongoDB, unless your data really consists of documents.

Typical examples of documents are configurations, forms, and maybe user sessions. Those typically don't fit well into tables because of "random" structure.

Body:
Store hashtags in an array within a document.

That's the benefit of having documents: you can simply nest them. And, in this particular case, it's trivial:

{
    "_id": 123,
    "file": "c43a5f46-kitten.png",
    "description": "My kitten :3 #kittens #cute"
    "hashtags": ["kittens", "cute", "cat", "animals"]
}

(I added some "synonymous" tags, this can be done automatically by looking up some other document.)

This is the most natural solution for document-oriented database:

Searching documents by hashtags is trivial if you just add an index, as well as inserting, updating, and deleting hashtags on random documents is also trivial

Massive inserting, updating, and deleting is a bit tricky, because you'd probably want to split such operations in multiple "batches", but still it's manageable and not hard to implement

Complex aggregations can be done with the standard aggregation pipeline or map-reduce

On the other hand, if you go with relational style, you'll be in a big trouble when you reinvent a SQL JOIN within your application code. This is one of the most common anti-patterns of using MongoDB (and such). Here's a very typical pseudocode:

for (HashTag tag: mongodb.hashtags.find()) {
   for (Image img: mongodb.images.find(
           new Document("_id", new tag.getImageId()))) {
       // ...
   }
}

This is inefficient, not scalable, and you are simply reinventing a wheel. Using this, you'll probably end up with complexity of O(N*M) because of loops within your code. If you'd choose SQL with foreign keys instead, you'd have something like O(N*log(M)) or even O(N+M).

There are no tables (relations) and foreign keys in MongoDB. Do not invent them, please. Use SQL instead, if you need. In fact, I highly suggest using SQL instead of MongoDB, unless your data really consists of documents.

Typical examples of documents are configurations, forms, and maybe user sessions. Those typically don't fit well into tables because of "random" structure.


问:
Where should I log in the user based on http session: service or controller?
I know that best practice is to let everything about authentication/authorization to the service layer.

Controller should not be aware of that.

But how to let a service (from service layer so) to check for http session if I do not pass in the http request?

In this particular case, when login needs some http request context, should the controller be master of the authentication and then pass the retrieved user as parameter of the service like this (in Java)? :

```<code>public interface SomeService {
     void aService(User user, ...);
}
</code>```

Other example would be the use the JWT mechanism.

Should the validation of the token be triggered by the controller or by the service, assuming in this later case that we pass the token in parameter of the service?

答:
In ASP.NET MVC, there are attributes that you can apply to the Controller methods that divert calls to an Unauthorized controller if the user isn't authenticated.  This makes sense to me, since you want to catch intrusion attempts very early in the process.  If the user isn't authenticated, the controller method doesn't even execute.

Once the user has been authenticated, authorization can take place in several ways.  You can have role-based authentication that lets users perform some actions but not others.  Roles and role assignments are typically kept in database tables that are driven by the user account that is logged in; you can even impersonate a user for support purposes.


答:
If you use a GUI for Git, like SourceTree by Atlassian, or git gui, you can commit parts of files and leave other parts uncommitted. In fact, you can commit individual lines of code.

I do this frequently when I fall down rabbit holes like you describe. This is a great way to make that sensible commit or commits as a precursor to the main commit.

You can do this from the command line, but it's kind of clumsy.

When you can commit at the Git patch level and individual lines, you don't need to create new branches, stash, commit, stash, and merge. Just keep working and don't break the flow. You've got a good thing going.

Title: How to handle it when a commit in-progress suddenly appears to depend on another that isn't there yet?

Body:
I'm inexperienced with Git but I try my best to get used to it, and so far I'm just using it for projects I work on alone.

When I code there's some top-down approach naturally (as I can't know the future), and there's a reoccurring theme:

I do some work.

I find out that to get my work into something "commitable" I need to do other work.

The other work deserves it's own commit.

By something commitable I mean something that compiles or something that isn't a total mess.

And by something that deserves it's own commit I'm referring to that I learned that commits should do just one thing.

The way I resolve it is cumbersome. If the other work is in another file I make a new branch, commit there, and merge. If the work is in the same file.. ugh.. I make a local copy and reset the file to it's state in HEAD, make the needed commit and then begin to restore my work from the copy. How should I actually handle that? I don't imagine this is the way, is it? I don't assume so because it must come up somewhat often to everyone (who don't know the future too, at least). Or maybe it seems my workflow is likely to be flawed?


问:
Ruby: if variable vs if variable.nil?
I'm new to Ruby and I was surprised when I found out that all objects are true apart from nil and false. Even 0 is true.

A nice thing about that property of the language is that you can write:

```<code>if !variable
  # do stuff when variable is nil
end
</code>```

My colleagues, who are more seasoned Ruby developers, insist I should choose that instead of using .nil? like so:

```<code>if variable.nil?
  # do stuff when variable is nil
end
</code>```

However I believe that the latter is a better option for two reasons:
1. I think it's more object oriented, especially in a language like Ruby where everything is an object and message exchange.
2. It is more readable, in my subject opinion, even if it is less compact.

Am I making a "newbie" mistake here?

答: Not only is if variable.nil? read more like natural language, it also guards against a programmer accidentally assigning it a false value and falling into your if statement, since Ruby is a loosely typed language.

Title: Ruby: if variable vs if variable.nil?


问:
expressjs: is it bad practice to use req.hostname for querying a db?
I'm building a nodejs app I would like to make available under various settings by my customers.
I want my customers to build their websites on top of my app, so:

 - the app can be configured in a way that domains "A.com" and "B.com" use the configuration "X" of the app, while "C.com" uses "Y", etc.

 - I'm thinking about using kubernetes and dockers containers to isolate version "X", "Y" etc. of my app
 - I'm also thinking about using nginx for reverse-proxy

Each domain will have its distinct documents in a mongodb collection. Because I need a way to retrieve the right data, I'm giving each domain a unique token matching their documents. All the tokens are also saved in mongodb and will be retrieved on my (nodejs) server's start or updated on the fly. The tokens will be saved on a "app.locals" variable:

 - I'm thinking about having a middleware that will grap the domain from every request (req.hostname) and get the corresponding token

```<code>// set locals
app.locals.domainTokens = {};
</code>```

after retrieving and assigning the tokens, "domainTokens" will look like:

```<code>app.locals.domainToken = {
    "Acom" : "token_1",
    "Bcom" " "token_2"   // and so on
}

// the middleware
function grabToken(req, res, next) {
    var tokens = app.locals.domainToken,
        host = req.hostname;
    req.params.token = host ? tokens[host] : undefined;
    next();
}
</code>```

When new customers register, tokens will be assigned on the fly for their domain (containers talk to each other, right?).

So basically, when a request is made for "A.com", my middleware sets the "token" so that the mongodb documents related to "A.com" can be found and sent back to client running version "X" of my app (nginx).

What do you think about this approach ? is it unsafe? a bad practice? do you have a better suggestion to implement it?

Am I better off using one container per domain ? (I would have to monitor hundreds of nodejs instances instead of 3 or 4)

Also, is it possible to dynamically configure a Nginx server?

答:
I have a very similar issue with deploying our own API.  I think this solution becomes unwieldy fairly quick as your code now has deployment specific information in it.  It is tempting to have the code auto-configure itself like this but I think it makes it harder than it needs to be.

In my case I choose to separate out similar information into a configuration file.  This has several benefits:

It is more inline with most other software that people are used to installing and configuring.

Someone can administer the installation without touching (or having access) to the code (and also in your case the database).

It will be much easier to script deployments / setup new environments.


问:
Is there an alternative to instanceof when filtering a Java stream by class?
I have an unexpected situation in a project in which all types extending one class are packed into a Java collection; but only a specific extension of that class contains an additional method. Let's call it "also()"; and let me be clear that no other extension has it. Right before performing one task on every item in that collection, I need to call also() on every item that implements it.

The easiest way forward is this:

```<code>stuff.stream().filter(item -> item instanceof SpecificItem)
            .forEach(item -> ((SpecificItem)item).also()));
stuff.stream().forEach(item -> item.method());
</code>```

It works fine, but I'm not comfortable with the "instanceof" in there. That's generally a marker of bad code smell. It is very possible that I will refactor this class just to get rid of it. Before I do something that dramatic, though, I thought I would check with the community and see if someone with more experience with either Streams or Collections had a simpler solution.

As an example (certainly nonexclusive), is it possible to get a view of a collection that filters entries by class?

答:
I'd suggest tossing in a .map call to do the cast for you.  Then your later code can use the 'real thing'.

Before:

```<code>stuff.stream().filter(item -> item instanceof SpecificItem)
            .forEach(item -> ((SpecificItem)item).also()));
</code>```

After:

```<code>stuff.stream().filter(item -> item instanceof SpecificItem)
            .map(item -> (SpecificItem)item)
            .forEach(specificItem -> specificItem.also()));
</code>```

This isn't perfect, but seems to clean things up a little.

Body:
I'd suggest tossing in a .map call to do the cast for you.  Then your later code can use the 'real thing'.

Before:

stuff.stream().filter(item -> item instanceof SpecificItem)
            .forEach(item -> ((SpecificItem)item).also()));

After:

stuff.stream().filter(item -> item instanceof SpecificItem)
            .map(item -> (SpecificItem)item)
            .forEach(specificItem -> specificItem.also()));

This isn't perfect, but seems to clean things up a little.


答: The primary problem used to be that only a few browsers supported this well, so it was not worth the trouble essentially creating a new platform to support.   Additionally older versions of IE did not support this well, and if I recall correctly at least one IE had a different XSLT dialect giving all sorts of fun problems.</p>

Title: What are the drawbacks of sending XML to browsers and let them apply XSLT?

Body:
Context

Working as a freelance developer, I often made websites completely based on XSLT. In other words, on every request, an XML file is generated, containing everything we need to know about the page content: the name of the user currently logged in, the top menu entries, if this menu is dynamic/configurable, the text to display in a specific area of the page, etc. Then XSL process (caches, etc.) it to HTML/XHTML page to send to the browser.

It has a good point to make it easier to create small-scale websites, especially with PHP. It is a sort of template engine, but which I prefer to other template engines because it's much more powerful than most of template engines, and because I know it better and like it. It is also possible, when need, to give an access to raw XML data on demand for an automated access, without the need to create separate APIs.

Of course, it will fail completely on any medium-scale or large-scale website, since, even with good caching techniques, XSL still degrades overall website performance and requires more CPU serverside.

Question

Modern browsers have the ability to take an XML file and to transform it with an associated XSL file declared in XML like <?xml-stylesheet href="demo.xslt" type="text/xsl"?>. Firefox 3 can do it. Internet Explorer 8 can do it too.

It means that it is possible to migrate XSL processing from the server to the client side for 50% of users (according on browser statistics on several websites where I may want to implement this). It means that those 50% of users will receive only the XML file at each request, thus reducing their and server's bandwidth (XML file being much shorter than its processed HTML analog), and reducing server's CPU usage.

What are the drawbacks of this technique?

I thought about several ones, but it doesn't apply in this situation:

Difficult implementation and the need to choose, based on the browser request, when to send raw XML and when to transform it to HTML instead. Obviously, the system will not be much more difficult then the actual one. The only change to make is to add XSL file link to every XML, and to add a browser check.

More IO and bandwidth usage, since the XSLT file will be downloaded by the browsers, instead of being cached by the server. I don't think it will be a problem, since XSLT file will be cached by the browsers (like images, or CSS, or JavaScript files are cached actually).

Possibly some problems on client side, like maybe problems when saving a page in some browsers.

Difficulty to debug code: it is impossible to obtain an HTML source the browser is actually using, since the only displayed source is the downloaded XML. On the other hand, I rarely go look at HTML code on client side, and in most cases, it is unusable directly (whitespace being removed).


问:
ID in class diagram
As far as i know, we do not add an attribute like id to the classes in the class diagram. right?

But when we create a database, or when we want to call an instance, we need its id, so why do not we have this attribute in our diagrams?

答: You don't have the ID in your class diagram because it is not actually relevant to your class itself. It will be relevant for your database so it will be present in a database diagram. Having a different storage strategy (for example, an XML file per order) means that you will not have a primary key because a primary key is an artefact of your persistance mechanism.

Title: ID in class diagram


问:
In MVC should a model handle validation?
I am trying to re-architect a web application I developed to use the MVC pattern, but I'm not sure if validation should be handled in the model or not. For example, I'm setting up one of my models like this:

```<code>class AM_Products extends AM_Object
{
    public function save( $new_data = array() )
    {
        // Save code
    }
}
</code>```

First Question: So I'm wondering if my save method should call a validation function on $new_data or assume that the data has already been validated?

Also, if it were to offer validation, I'm thinking some of the model code to define data types would look like this:

```<code>class AM_Products extends AM_Object
{
    protected function init() // Called by __construct in AM_Object
    {
        // This would match up to the database column `age`
        register_property( 'age', 'Age', array( 'type' => 'int', 'min' => 10, 'max' => 30 ) );
    }
}
</code>```

Second Question: Every child class of AM_Object would run register_property for each column in the database of that specific object. I'm not sure if this is a good way of doing it or not.

Third Question: If validation should be handled by the model, should it return an error message or an error code and have the view use the code to display an appropriate message?

答:
I do not completely agree with "back2dos": My recommendation is to always use a separate form/validation layer, that the controller can use to validate input data before it's sent to the model.

From a theoretical standpoint, model validation operates on trusted data (internal system state) and should ideally be repeatable at any point in time while input validation explicitly operates once on data that comes from untrusted sources (depending on the use case and user privileges).

This separation makes it possible to build reusable models, controllers and forms that can be loosely coupled through dependency injection. Think of input validation as whitelist validation (“accept known good”) and model validation as blacklist validation (“reject known bad”). Whitelist validation is more secure while blacklist validation prevents your model layer from being overly constrained to very specific use cases.

Invalid model data should always cause an exception to be thrown (otherwise the application can continue running without noticing the mistake) while invalid input values coming from external sources are not unexpected, but rather common (unless you got users that never make mistakes).

See also: https://lastzero.net/2015/11/why-im-using-a-separate-layer-for-input-data-validation/


问:
I'm graduating as a CS major from a bad CS program. How can I catch up? How can I get over it?
I transferred to Computer Science my Freshman year so never really got a chance to look at schools for CS in particular. I breezed through with a 3.9 and never really felt challenged. I did three internships at startups, and all of my employers seemed to really like me so I think I'm ok at programming.

However, I'm becoming more insecure with computer science and myself than I've ever been. I've been talking to students who went to top schools and I feel overwhelmed by what I never learned. I've been a big fish in a small pond for the last four years and I'm scared I wasted my time.

I don't want to be an ok developer. I want to be a great developer.

I know I can program. I'm really into self teaching myself. I can read Cracking the Coding Interview and do pretty well. I took the Machine Learning course on Coursera. I did nand2tetris.org. I'm almost done with reading Learn You a Haskell.

But I'll never take a class like CMU's 251 class where I have someone breathing down my neck to make sure my proofs are right. I'll never be up late hanging out in a CS lounge with a ton of people way smarter than me hacking away. I'm getting borderline obsessive with "catching up". I'm trying to read CLRS (a pretty in-depth algorithms book), and it's half for fun, but it's also because I'm scared that I'll be in the industry for 30 years and there will be MIT grads that have a better "base" of knowledge than me.

Is this irrational? Is this a common issue that people "get over"?

答:
First things first, MIT/Columbia/Berkely/Stanford/etc. graduates will always have the upper hand upon graduation. That's just the way it is. Keep in mind that those schools also cost way more than normal schools. They have access to the top instructors and materials, as well as some of the smartest students around, and a great alumni association for networking.

The good news about this is, after you have a few jobs a few years out of college, this begins to matter less and less. As long as you can code, you can have the same jobs as people from top schools have. I went to a normal school and many people I know work at organizations that no doubt have people from Ivy League colleges at them (most of them got the jobs 2-3 years out of college).

Feeling behind in the software industry is something that you learn to deal with over time. As long as you learn relevant things quickly enough to apply them at your job, you will be fine. Personally, I have a long commute, so I listen to podcasts to/from work in addition to reading books. You can still be a great developer if you practice at what you do and keep at it.

Life is a marathon, not a sprint. Just because someone may start off further than you doesn't mean they will tire throughout the race. You may end up passing them before the end.

Continuing that thought, don't look at everything as a competition. If you really wanted to get serious, you will always compare yourself to the Mark Zuckerburgs, Larry Paiges, and Melissa Meyers of the world. Be happy with what you have and always try your best.