答:
One of the hardest part about game development, althought less prevalent in 2D game development is creating graphics. So assuming your cousin doesn't need to deal with creating art assests, or happens to be very good at 2D art, then I think the goal is achievable.

I'd suggest you use python along with pygame to get started. I know you had reservations about python, but hear me out. Python is a very simple language. I would argue that the lack of strict typing makes it a far better choice than something like C# to begin with.

Prototype based languages are cool and some people find them very easy to pick up, however I don't think that people really understand the concepts of how objects works in prototype based languages as easily as they can grok the class/object paradigm.

Pygame also has numerous examples that your cousin and you could go over to learn the basics, and is in many ways a very simple framework, not hiding so much from you as to make you have to learn a lot of the framework to do more complicated things.

Perhaps after a game written in pygame, you can move onto writing games that also integrate with a 2d physics engine like box2d, which has excellent python bindings.

As for teaching your cousin python, I'd stray away from getting him to learn the language first, perhaps a crash course in the class/object ideas. Then some basic syntax of the language, before throwing him in the deep end, and having him/her look up the syntax and/or libraries when he/she needs something.

Finally another good thing about python, is that you can easily move onto 3d game engines while keeping your skills with engines like panda3d, or even unity (Boo is very similar to python).

Title: A free game-development language?


问:
Should I learn a programming language before I attend college for Computer Engineering?
I've dipped my toes in C++ programming but I haven't actually delved into it.  I want to know if I actually need to learn it or any other languages before I go to college for Computer Engineering or am I just going to learn it at school anyway?</p>

答: Personally I would recommend it.  This won't apply to all schools, but I went to what is considered a very good engineering school and the introductory programming classes were awful.  Knowing the basics will help you avoid many of the bad practices/incorrect knowledge that might be taught to you.  And as another answer mentioned, you'll coast through those easy intro-to-programming classes while others struggle.  And if you're like me, that gives you more opportunities to help your friends who are struggling with it themselves.</p>

ContentLicense: CC BY-SA 3.0


答:
Yes, for several reasons.

The sooner you start getting experience with the field, the
sooner you'll be able to figure out if this is the field you should
be majoring in. If you don't like programming, then Computer
Engineering is probably not a good field to major in. Even if you are  mostly
interested in designing CPUs, you are going to be doing a LOT of
programming.

Most folks find that the level and amount of work expected from them
in college greatly exceeds what they are used to in secondary
school. Unless you are exceptionally talented, you are going to find
yourself hammered with work. Do yourself a favor: find out which
language is used for teaching the first year course and start
learning it now. Worst case, you'll be a little bored in the class,
but you'll be able to get the work done faster and use the time
saved for your other classes.

Many classes are graded on a curve. The downside of this is that you
will be competing with your fellow classmates for grades. Many of your fellow computer engineering students will have already done a lot of programming, so you may already be behind the curve. This is a good time to start catching up.

The only way to get good at programming is to do a lot of it. The
more time you spend programming in the next few years, the better
you will be at it. The more experience you have, the better the
chance you have at landing internships and jobs.

Title: Should I learn a programming language before I attend college for Computer Engineering?

Body: I've dipped my toes in C++ programming but I haven't actually delved into it.  I want to know if I actually need to learn it or any other languages before I go to college for Computer Engineering or am I just going to learn it at school anyway?</p>


答:
I don't think you need to learn it before you attend college.  However I believe like most things in life, if you are pre-prepared before attending some event etc then you are most likely to better able to make informed decisions about what information to absorb and what information to discard.

More specifically by at least dipping your toes, you may be able to listen to what your lecturers are saying rather than just copying what they say verbatim but not actually absorbing the concepts they are trying to get across, which in my opinion is the most important part of university (not the actually learning syntax part of a language etc).

As for what programming language to learn.  Probably doesn't matter but might be useful to start reading up on the ones you are likely to cover in your first year.

However, the flip side of pre-learning is that when you get to your first few months you might find the lectures boring and elementary.  This then could lead you not attending classes or discarding what the lecturers are trying to get across hence missing some vital piece of information such as realising the way you actually learnt something is not the right way i.e. you learnt a bad habit prior to attending college.

By already delving on these types of sites you are probably already part of the way there to being one step ahead and so help your learning during college.  Either way, what you pre-learn will probably just be the tip of the iceberg.  You will need to carry on this learning curve in and out of college material if you want to carry on the benefits it may provide.


答:
I think you should. Besides the reasons given by others here, I would add that a lot of university professors are not very good at teaching and therefore you cannot rely on them to teach what you are learning very well. You'll understand what they are saying a lot better if you already have a grasp of the basics.

Plus, the ratio of course material to class time is often too high in universities, so even when the professor is a decent teacher, he cannot teach you effectively in the class time available. So any knowledge you gain in advance will help you keep up with the fast pace of the classroom.

IMO C++ is one of the worst languages for beginners. Go ahead and study C++ if you don't find it too difficult, but other languages such as C#, VB, Ruby, or Python are quite a bit easier.


问:
Is hiring a junior developer as a technical trainer a good idea?
So my friend's boss brought in four junior candidates with some work experience, she is one of them. Her manager wants them to be experts on the subject matter of tomcat in a matter of two months in order to justify them as billable to other clients as a technical trainer.

My biggest concern is this, they only have a year to no experience in development but no production support experience. Is it possible to turn these greenhorns into gurus in a short amount of time with the use of text and forums?

Also they don't have a proper sandbox to play with, i.e. any servers. I am helping in my spare time but I don't feel she has enough time to become a SME. What can I do to help her become an expert or what can I say to her that the position may not be a good fit?

答:
If you re-read your question, you will find the answer perfectly clear.

It is a horrible idea but the boss probably doesn't care and just want to scam some poor clients by sending junior employees billed as experts and pocket the difference. Its quite a common occurrence and doesn't usually end well especially for the employee.

If they actually have a proper training tools (sandboxes) and training from existing experts, then the position seems more legit. Then even though it may still not work out and she would lose the job in the end, at least her learns something and is better geared for a real job.

In any case, you should not be doing the training, you can help by generating lead for a real job and your friend should only take this gig if she is in between jobs and need the income, remain active in her job search.

Career management is extremely important for programmers, any job should have long term advancement, resume credibility or real training (mentoring from experts, not reading books yourself). Short term pay is actually secondary.

One year of time well used or wasted when you are junior will define your career trajectory.


答:
As a CS graduate myself (BS, MS, PhD), I would recommend that you get your feet wet as soon as possible. You will have enough other stuff going on in your first year of college. In particular for programming:

Check the website of your target university and look at the
lower-division class catalog or instructor syllabus webpage for
introductory programming classes. Look for the programming language
being taught and see what kind of things are covered in the first
class. Try to read up on that material before you start.

Again, looking at the class syllabus page, look at the previous
programming assignments and see what kind of software programming
tools and environment are being used. Is it vi and gcc (this is what real men
use)? Microsoft Visual Studio? Eclipse? Try to use these tools before you start.

Software programming is just one of the things taught in a CS curriculum. Others are algorithms (e.g. QuickSort), data structures (trees, linked lists, hash tables), and pure theory (NP-completeness and set logic). I would say these are at least as important as whatever programming language you learn.


答: You won't know whether Computer Engineering is really the appropriate degree program for you until you at least find out how hard or easy it is you find programming to be, as well as how good you are at it.  The only way to really know is to try and learn at least one programming language and do lots of coding, ASAP.</p>


答:
Some things you might be interested in learning before going to University (choose among them):

Some more math (I cannot be more specific, because I'm French, and have no idea of the math skills you are expected to have).

Some other programming languages, like Ocaml, Scheme, Haskell, Lua ... They will open your mind to new ways of thinking.

Some algorithmics book

Better English & written skills (and a foreign language is never bad)

Using and coding under GNU/Linux, and free software in general. The ability to study free software (and contribute to it) will learn you a big lot.

Work autonomy, being able to define yourself a work plan, and stick to it

The SICP

I won't recommend focusing in a narrow way on C++; other languages, books, skills will bring you much more. Don't spend all your efforts on C++.

Enjoy your learning.


问:
Is cloudera hadoop certification worth the investment
I am considering investing time to learn Hadoop and it's related technologies. The problem is that my current day job will not be using Hadoop any time soon and even if I learn from books, blogs personal projects I will not have much to backup when I actually need to show that I have Hadoop experience.

So while continuing my job I would like to invest into my own training and I am thinking about Hadoop certification from cloudera. What do you think about it?

Please answer from your perspective (if you took the certification and training course or are in the market for hiring new hadoop developers and what do you look for)

I am sure that there is no shortcut to becoming an expert in Hadoop, but certification and training seems like a jump start.

答:
When someone is asking about the certification question my response is always the following:

What will this certification give you besides personal satisfaction?

In my knowledge there are 2 certifications that had real money associating with having them in IT world:  CCIE and old Citrix Administrator certification.  Both of which had both theoretical and practical components and from people who did take it they were brutal to take.

So you should start by looking at the following:

Are there jobs requiring Hadoop where you live or where you want to work?

Do they pay more then what you are making now?

Are there jobs that require Hadoop certification?

Do the jobs requiring Hadoop certification pay more then the ones that don't?

Once you answer all these questions you will have your answer on whether to pursue certification for Hadoop.

If on the other hand you can do it because someone else is paying for it and it won't take away any time from other more pleasurable activities then I suggest you do it just to get personal satisfaction that you've done it.


答: Honestly, if you have time go for it. IT will make more sense while the teacher is teaching. You will get most out of it than the students who have never programmed.</p>


问:
A free game-development language?
So, I'm trying to teach my much younger cousin a little bit about programming. My initial thought was something like Scratch or Alice, but there were a few downsides to that.

Everyone seems to be really in to game programming and developing video games (because     everyone loves playing video games, and as far as playing video games goes, playing your own can be the most rewarding) - but neither Alice nor Scratch seem to cater to game development

Alice and Scratch seem too childish, while I'm sure my cousin would
enjoy dabbling in it, I think he'd quickly bore of it

I want a language that can be used to develop really cool stuff that
will impress his friends. I remember writing BASIC back in the day
and inviting all my friends over and showing off my creation, and I
just feel like Alice and Scratch just don't appeal in the same way

I want a language that requires my cousin to write code. Now, this
isn't just because I think typing code out is good preparation for
other programming languages, but it's because it gives him an
opportunity to actually practice typing, and maybe get used to some
of the slightly more esoteric characters on the keyboard

Now, that's why I don't want to choose Alice or Scratch.

I also don't want to pick a language like C or Java, or even Python or Ruby for that matter. My cousin has already imparted to me that he enjoys playing video games and wants to make his own, and that he enjoys using computers. In my opinion, even a simple language like Python or Ruby simply takes too long to build cool stuff. Ideally, he'd sit down, spend around a day or two (or maybe even up to a week, but hopefully less than that) and have a working, 2-dimensional game. I'm not saying you can't do it in Python or Ruby, but I'm just saying it would be difficult for a first-time programmer. Plus, I don't want to bog him down with all the computer science stuff, as that can come later. I just want to help him create the spark, and then let him carry on with the rest of the fire.

I've looked at languages like Lua, and while it seems common in game programming, I'm not sure if it's the best pick - but if you guys think otherwise, please let me know.

I've also looked at a language like Blitz and it looks really promising (plus, I tried it out a few years ago, and it was really quite nice). The downside is that I have to pay, something I'm definitively against.

I've looked at SmallBasic, which seems promising and I'll continue looking at. But I haven't done much (in fact, I'm running the installer as I type this, so I'll report my thoughts on it shortly).

UPDATE: I gave SmallBasic a quick try and it seems intriguing, but it also seems quite different compared to some other languages - that's not a bad thing, but it just is an unusual. Out of the things I've looked at, Blitz is still my favorite, but I refuse to go there because of the cost.

But basically, what do you guys think of what I've said so far, and the languages I've looked at and do you know of any other, good alternatives?

UPDATE: Here's what I've chosen to do...

I've realized that while I would love to help my cousin, I can't be with him all the time, and I can't help him every time he needs help. So, I wanted to choose something that has a good documentation, a good community, and a good book he can follow.

Anyways, I've chosen Python and Pygame. Python is a language I'm fairly familiar with, plus I know there is a pretty good (and pretty large) community around Python. Furthermore, I know that the Python documentation is fairly complete and easy to navigate. Pygame also has an excellent documentation and set of tutorials. I'm also having him use/follow Invent Your Own Computer Games with Python, which seems like a very good book, I bought him a hard copy as a Christmas present, plus I know that his monitor isn't huge, and it would be inconvenient to constantly swap back between the text and the editor.

I think it should go well!

EDIT: I don't want to imply that my choice is final or that it is correct. I just think it's the best fit for this situation. I think each person looking to teach someone younger should browse the selection and find the best solution for the individual person, considering things like age, skill level, and interest.

答:
http://news.bbc.co.uk/2/hi/programmes/click_online/9658183.stm

The BBC program Click showed a website where you can create Flash based game without needing to know a programming language.

http://www.stencyl.com/

Title: A free game-development language?


问:
How Much Logic in Getters
My coworkers tell me there should be as little logic as possible in getters and setters.

Yet, I am convinced that a lot of stuff can be hidden in getters and setters to shield users/programmers from implementation details.

An example of what I do:

```<code>public List<Stuff> getStuff()
{
   if (stuff == null || cacheInvalid())
   {
       stuff = getStuffFromDatabase();
   }
   return stuff;
}
</code>```

An example of how work tells me to do things (they quote 'Clean Code' from Uncle Bob):

```<code>public List<Stuff> getStuff()
{
    return stuff;
}

public void loadStuff()
{
    stuff = getStuffFromDatabase();
}
</code>```

How much logic is appropriate in a setter/getter? What's the use of empty getters and setters except a violation of data hiding?

答:
You are right, your colleagues are wrong.

Forget everyone's rules of thumb about what a get method should or should not do.  A class should present an abstraction of something.  Your class has readable stuff.  In Java it is conventional to use 'get' methods to read properties.  Billions of lines of frameworks have been written expecting to read stuff by calling getStuff.  If you name your function fetchStuff or anything other than getStuff, then your class will be incompatible with all those frameworks.

You might point them to Hibernate, where 'getStuff()' can do some very complicated things, and throws a RuntimeException on failure.

Title: How Much Logic in Getters


问:
How to write a command interpreter/parser?
Problem: Run commands in the form of a string.

command example:

/user/files/ list all;
equivalent to:
/user/files/ ls -la;

another one:

post tw fb "HOW DO YOU STOP THE TICKLE MONSTER?;"

equivalent to:
    post -tf "HOW DO YOU STOP THE TICKLE MONSTER?;"

Current solution:

```<code>tokenize string(string, array);

switch(first item in array) {
    case "command":
        if ( argument1 > stuff) {
           // do the actual work;
        }
}
</code>```

The problems I see in this solution are:

No error checking other than nested ifs-else inside each case. The
script becomes very big and hard to mantain.

Commands and responses are hardcoded.

No way of knowing if flags are correct or missing parameters.

Lack of intelligence to suggest "you might wanted to run $command".

And the last thing I can't address is synonyms in different encodings, example:

```<code>case command:
case command_in_hebrew:
    do stuff;
break;
</code>```

The last one might be trivial, but well, what I want to see is the solid fundations of this kind of program.

I'm currently programming this in PHP but might do it in PERL.

答:
There is a nice feature in functional programming that you might be interested to look into.

It's called pattern matching.

Here are two links for some example of pattern matching in Scala and in F#.

I agree with you that using switch structures is a bit tedious, and I particularly enjoyed using patern matching durint the implementation of a compiler in Scala.

In particular, I would recommend you to look into the lambda calculus example of the Scala website.

That's, in my opinion, the smartest way to proceed, but if you have to stick strictly with PHP, then you're stuck with the "old-school" switch.


问:
Best practice modelling an active record entity using Linq-To-SQL as DAL
Currently I'm starting a new system on my company, and we are using a good separation between models, views and controllers, basically using Asp.Net MVC 3 for the user UI, and a C# class library for the model.

The question is about "modelling a model".

We are using Linq-to-SQL as a Data Access Layer, and modelling entities over this DAL. Example:

```<code>    // DAL, an autogenerated .dbml file
    ...
    public System.Data.Linq.Table<TB_USER> TB_USERs {
       get {
          return this.GetTable<TB_USER>();
       }
    }
    ...
</code>```

And we are mapping this table on an entity, like below:

```<code>    public class User {
       // Entity, mirroring a .dbml table
       public static IEnumerable<User> GetAll() {
           var db = new MyDataContext();
           var userList = (from u in db.TB_USERs select u).ToList();
           IEnumerable<User> retorno = lista.ConvertAll(u => (User)u);
           return retorno;
       }

       // Active Record ?
       public static User Save(User user) { ... }
    }
</code>```

Is this kind of modelling correct ? It feels like I'm repeating myself by having 2 entities meaning the same thing (User and TB_USER), but TB_USER is the raw representation of the database table that persists the User entity.

And the GetAll method, a static method created on the entity with the sole purpose of retrieving all of them. That means that if I want to retrieve data using a filter, for example, I have to create another GetDataBy... method.

And what about the Save method ? I know it's supposed to save the state of one User, but what if I have to save some random User object along with other objects to make a transaction ?

Shouldn't this kind of transaction control be in the database ?

答:
I think Christian came up with a good answer to your question. Based on the exchanged comments there may be some things worth explanation in the pattern you try to use.

POCO is it's name. Plain pure objects which have no logic inside. They just concsist of getter/setters you want to expose at the, in your described case, UI. The repository is an additional class which is the place for the logic of data between DAL and presentation. This seen together with the ORM objects, yes there are a lots of classes involved. The ORM classes though, is nothing but the UML designer to take care of. The Repo and poco classes are more interesting because the going to the interface between your ORM and your UI.

I.e. I can have a POCO named Resident, which can have fields that came from several tables (Entity objects) in DAL. I.e. Location for the address and apartment specifications and also User, which helds the name, emailadress and such information. The UI will never know that there exist a user-table-design at all. Sometimes the Pocos can feel like repeating the same object over again (Because they contain same fields to the UI as to the DAL).

Your correct about the GetAll(), Save() methods, they should be in the repo-class. I.e. Save() could be Save(PocoType poco), which inside the method, store the poco object to the corresponding DAL entity fields. GetAll() return the poco object, inside the method there are logic to open DAL, fetch data and transform to the POCO type.

I also, sometimes, use a IEnumerable SomeEntity { get { .. } } which inside the getter open the DAL and transform to PocoType. From UI i have a fully available linq context. like var result = instantiatedType.SomeEntity.Where(u=>u.LoggedIn > DateTime.Now.AddDays(365)) (i tooked this right from head, I may have missed some syntax details).

Ok I hope I added something useful and, at least, correct info :). It's in middle of the night and the Christmas day was arrived!


问:
Why does everybody write to-do comments in capital letters?
I'm doing the same. When there is something "to-do" in my code, I write //TODO .... But I'm curious to know when this started and if there is a reason for writing "to-dos" in all capital letters?

答: I just stands out and is easy to catch... nothing complicated!</p>


答:
I'm curios to know when this started and if there is a reason for
  writing to-dos all capital?

The idea with comments like TODO and FIXME is to make them stick out. You generally don't want to ship code that has such markers in the code -- they mark things to be done before the project can be considered complete. Using ALL CAPS makes them a little easier to spot, provided you don't use ALL CAPS for a lot of other things in your code too.

Title: Why does everybody write to-do comments in capital letters?

Body: I'm doing the same. When there is something "to-do" in my code, I write //TODO .... But I'm curious to know when this started and if there is a reason for writing "to-dos" in all capital letters?


答:
Also, it's great to have a way to easily search for code sections you glossed over and want to get back to.
You can do a case-sensitive search for "TODO" to immediately find what you skipped before.

"todo" (lower-case) could potentially be part of a larger word/function/variable, but "TODO" (upper-case) is probably not going to be.


答:
Yes, but don't start with the most complicated language, there will be plenty of time for that later.

Start with something simple to get your feet wet.  It's much easier to wrap your head around programming concepts when you're not being burdened by the language itself.  Likewise, some languages do things better than others.

Learn Python for dynamic programming, simple object oriented programming techniques, and proper indentation.  Learn javascript + JQuery or Lua to learn about closures.  Learn Java or C# to learn about static typing.  Learn regular expressions for string parsing.  And learn a little SQL since every programmer has to touch a database at some point.  Then Learn PHP so you can identify spaghetti code.

This list may vary, but basically pick a few fun languages and use them to learn concepts.  Subsequently, you'll be learning to be adaptive, rather than stagnating on one language for the rest of your life and angrily trying to defend it on the internet all the time.


问:
C# Design, many properties, complex constructor and equality
I'm still a relative novice with OOP, so I am still trying to understand some of the best practices for how to design "good" objects.  I know this question is probably a rather subjective, which is why I am here rather than on stackoverflow.

I am designing an object that will have 20 separate string properties, none of which are required.  These constraints are fixed and cannot be changed as it is an implementation of an outside data source that I have no control over.

The design problem I am running into is how to effectively construct an instance of the object and be able to compare equality by comparing each field without violating normal best practices.

A 20 argument constructor seems very wrong, especially since every field is a string, and there are cases where many of them will be null.  I could use the optional arguments in C#4 to reduce the number of arguments that are actually called, but since everything is a string, I would have to use named parameters when calling the constructor, and that seems that it would be even uglier.

I have thought about trying to group the properties into smaller classes, but the most logical grouping still has an object with 10 properties, and at least half of the remaining properties have no logical grouping.

I could give each property a public setter, but that would make the object mutable, and thus complicate matters for overriding GetHashCode().  And I really don't need the object to be mutable.  Once it is built, there should never be a reason to change it, but I don't want to rely on that because who knows what someone will try to do with it.

Implementing IEquatable<T> is a possibility for the equality test, but my understanding is it is recommended to also override Equals(object obj) and GetHashCode() when implementing IEquatable so all Equals methods have the same behavior.

Is this an edge case where overriding Equals without overriding GetHashCode should be done?  I don't intend on using this object as a key in a dictionary or as a member of a HashSet, but I can't predict what someone else would try to do in the future.

Or should I just abandon the idea of doing an equality comparison on all of the properties with Equals and implement my own Compare() method?

Or is there a better method for building the object that would allow it to still be immutable without having to pass all of the arguments through a constructor or a method?

EDIT:
In response to Sign's comment, the purpose of the object is ultimately to be able to compare the data from the outside data source to our internal data to ensure it is accurate.  Both data sets contain address information, but they are broken up differently.

The internal data, is generally stored as a typical address (Street, City, State, Postal Code, County, Country), but there are variations when you have a suite/apartment # or a floor in a building.

The external data is broken down even further into smaller pieces.

So this object is supposed to be a common link between the 2 data sources and allow the user to compare like fields for equality.

EDIT #2:
Ultimately, I chose Doc Brown's answer because a modified version of his dictionary idea (with Enums as Keys instead of strings) was the simplest way to go without having a messy constructor and still provide the immutability I was hoping to have.  In the long term, I am going to experiment with some of Oliver's suggestions as some of his edits did have a lot to offer.

答:
Apparently, you are not interested in individual properties; you just want to compare a bunch of fields. Therefore, a dictionary or a list of fieldname/value pairs would seem very appropriate to me. It allows you to do the comparisons in a loop instead of having to treat each field individually. It is also a universal approach as you can apply it to different sets of properties. In addition, it is more flexible as you will not have to change the algorithms if you add new fields.

I would not stick to the immutable approach. Instead, give your class an Add-method and forget the constructor with the endless parameter list.

```<code>public class FieldComparer : IEquatable<FieldComparer>
{
    private Dictionary<string,string> _fieldDict = new Dictionary<string,string>();

    public void Add(string fieldName, string value) {
        fieldDict.Add(fieldName, value);
    }

    // The magic comes here
}
</code>```

EDIT:
As an answer to your concern, I have two suggestions for different approaches:

1

In the class described above, supplement individual properties for fields that you want to handle individually:

```<code>public string LastName {
    get {
        string last_Name;
        _fieldDict.TryGet("LastName", out lastName);
        return lastName;
    }
    set {
        _fieldDict["LastName"] = value;
    }
}
</code>```

2

Use properties in the first place and make them available through an indexer in order to be able to loop through them:

```<code>public string FistName { get; set; }
public string LastName { get; set; }
public string City { get; set; }

public const int PropertyCount = 3;

public string this[int i]
{
    get
    {
        switch (i) {
            case 0:
                return FirstName;
            case 1:
                return LastName;
            case 2:
                return City;
            default:
                throw new ArgumentNullException("Index out of bounds.");
        }
    }
    set
    {
        switch (i) {
            case 0:
                FirstName = value;
                break;
            case 1:
                LastName = value;
                break;
            case 2:
                City = value;
                break;
            default:
                throw new ArgumentNullException("Index out of bounds.");
        }
    }
}
</code>```

(The setter of the indexer might not be necessary for your purpose.)
You can then access the properties like this:

```<code>var comp = new FieldComparer();
comp.FistName = "John";
Console.WriteLine(comp[0]); // -> John
</code>```

EDIT:
The solution #2 has the disadvantage, that we lose the universality of the approach. We could restore it, if we implemented the indexer and PropertyCount from an interface. (We also would have to convert PropertyCount to a read-only property). The Comparison would then happen in a separate class.

```<code>public interface IPropertyIndexer
{
    string this[int i] { get; }
    int PropertyCount { get; }
}
</code>```

Instead, I will show a complete solution using an enumerator instead of an indexer. Both approaches are comparable. The enumerator version using yield return is a bit shorter than the indexer version using a switch statement.

3

```<code>public interface IPropertyEnumerator
{
    IEnumerator<string> AllValues { get; }
}

public class Address : IPropertyEnumerator
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string City { get; set; }

    public IEnumerator<string> AllValues
    {
        get
        {
            yield return FirstName;
            yield return LastName;
            yield return City;
        }
    }
}

public class Customer : IPropertyEnumerator
{
    public string Name { get; set; }
    public string CustNo { get; set; }

    public IEnumerator<string> AllValues
    {
        get
        {
            yield return Name;
            yield return CustNo;
        }
    }
}

public static class PropertyComparer
{
    public static bool Equals<T>(T x, T y)
        where T : IPropertyEnumerator
    {
        var enum1 = x.AllValues;
        var enum2 = y.AllValues;
        while (enum1.MoveNext()) {
            if (!enum2.MoveNext() || enum1.Current != enum2.Current) {
                return false;
            }
        }
        return !enum2.MoveNext(); // true if number of properties equal
    }
}

public class Example
{
    public void Compare()
    {
        var a1 = new Address { FirstName = "John", LastName = "Doe", City = "New York" };
        var a2 = new Address { FirstName = "John", LastName = "Doe", City = "New York" };
        Console.WriteLine(PropertyComparer.Equals(a1, a2));

        var c1 = new Customer { CustNo = "A123", Name = "Miller" };
        var c2 = new Customer { CustNo = "B777", Name = "Stanley" };
        Console.WriteLine(PropertyComparer.Equals(c1, c2));
    }
}
</code>```

Body:
Apparently, you are not interested in individual properties; you just want to compare a bunch of fields. Therefore, a dictionary or a list of fieldname/value pairs would seem very appropriate to me. It allows you to do the comparisons in a loop instead of having to treat each field individually. It is also a universal approach as you can apply it to different sets of properties. In addition, it is more flexible as you will not have to change the algorithms if you add new fields.

I would not stick to the immutable approach. Instead, give your class an Add-method and forget the constructor with the endless parameter list.

public class FieldComparer : IEquatable<FieldComparer>
{
    private Dictionary<string,string> _fieldDict = new Dictionary<string,string>();

    public void Add(string fieldName, string value) {
        fieldDict.Add(fieldName, value);
    }

    // The magic comes here
}

EDIT:
As an answer to your concern, I have two suggestions for different approaches:

1

In the class described above, supplement individual properties for fields that you want to handle individually:

public string LastName {
    get {
        string last_Name;
        _fieldDict.TryGet("LastName", out lastName);
        return lastName;
    }
    set {
        _fieldDict["LastName"] = value;
    }
}

2

Use properties in the first place and make them available through an indexer in order to be able to loop through them:

public string FistName { get; set; }
public string LastName { get; set; }
public string City { get; set; }

public const int PropertyCount = 3;

public string this[int i]
{
    get
    {
        switch (i) {
            case 0:
                return FirstName;
            case 1:
                return LastName;
            case 2:
                return City;
            default:
                throw new ArgumentNullException("Index out of bounds.");
        }
    }
    set
    {
        switch (i) {
            case 0:
                FirstName = value;
                break;
            case 1:
                LastName = value;
                break;
            case 2:
                City = value;
                break;
            default:
                throw new ArgumentNullException("Index out of bounds.");
        }
    }
}

(The setter of the indexer might not be necessary for your purpose.)
You can then access the properties like this:

var comp = new FieldComparer();
comp.FistName = "John";
Console.WriteLine(comp[0]); // -> John

EDIT:
The solution #2 has the disadvantage, that we lose the universality of the approach. We could restore it, if we implemented the indexer and PropertyCount from an interface. (We also would have to convert PropertyCount to a read-only property). The Comparison would then happen in a separate class.

public interface IPropertyIndexer
{
    string this[int i] { get; }
    int PropertyCount { get; }
}

Instead, I will show a complete solution using an enumerator instead of an indexer. Both approaches are comparable. The enumerator version using yield return is a bit shorter than the indexer version using a switch statement.

3

public interface IPropertyEnumerator
{
    IEnumerator<string> AllValues { get; }
}

public class Address : IPropertyEnumerator
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string City { get; set; }

    public IEnumerator<string> AllValues
    {
        get
        {
            yield return FirstName;
            yield return LastName;
            yield return City;
        }
    }
}

public class Customer : IPropertyEnumerator
{
    public string Name { get; set; }
    public string CustNo { get; set; }

    public IEnumerator<string> AllValues
    {
        get
        {
            yield return Name;
            yield return CustNo;
        }
    }
}

public static class PropertyComparer
{
    public static bool Equals<T>(T x, T y)
        where T : IPropertyEnumerator
    {
        var enum1 = x.AllValues;
        var enum2 = y.AllValues;
        while (enum1.MoveNext()) {
            if (!enum2.MoveNext() || enum1.Current != enum2.Current) {
                return false;
            }
        }
        return !enum2.MoveNext(); // true if number of properties equal
    }
}

public class Example
{
    public void Compare()
    {
        var a1 = new Address { FirstName = "John", LastName = "Doe", City = "New York" };
        var a2 = new Address { FirstName = "John", LastName = "Doe", City = "New York" };
        Console.WriteLine(PropertyComparer.Equals(a1, a2));

        var c1 = new Customer { CustNo = "A123", Name = "Miller" };
        var c2 = new Customer { CustNo = "B777", Name = "Stanley" };
        Console.WriteLine(PropertyComparer.Equals(c1, c2));
    }
}


答: If you have to question whether you should learn a programming language in the first place, ask yourself if its really what you want to do. Most computer science first years are already pretty damn good at programming before they even start so you will be competing against those types that naturally tend toward the geek. Either jump into it head first or do something else you love. Don't be on the fence. Love what you do. I don't need or want a vote for this one, just want to talk straight to you.</p>


答:
It would be a very smart move to know some language before entering college.  College instruction in Computer Science is often of a dismal quality, given by TAs who are untrained or who don't speak English.  Introductory courses are not a priority and poor instruction is the rule.  Universities make money off of grant overhead; getting grants is the priority of most college faculty, not teaching undergraduates.  This is a sad rule with few exceptions.

However, the quality of programs in high schools can be poor too.  Many school administrations think training in using Micosoft Word is computer science.  Ah, the nonsense that eminates from the ed schools!

I wish I could be more optimistic. If you have a good compsci program in your high school, latch onto it.  Go beyond the bounds and be aggressive about learning.  If you are fairly enterprising, it's not hard to teach yourself Python and to get some skill at it.  Once you learn it, learning other languages is not to hard. Python's simple grammar makes learning it relatively easy.


答:
If you are a vi user use:

/TODO

It will get you there very fast.


答: Both Eclipse and Visual Studio have Task List features that automatically give you lists of comment lines that have TODO in them.  </p>


答:
Visually ALL CAPS stands out, but isn't very legible.  When reading code they scan as a block of a particular size.  It doesn't really matter what the letters are.  They just stand out and can be seen very quickly.  Once you have been working with the tags for a while, your brain will recognize the word by shape.

From a tools (IDE/Editor) standpoint, case sensitive search will have a very low false positive rate on all caps versions.  In some coding styles there is a small risk that a constant will be matched. Case sensitive whole word search makes false positives even less likely.

Once the tool gets it on screen the format clearly says look HERE.  Once you are focused on the location, the legible part will be the related comment.


答: Definitely!  If you haven't programmed before, learning C++ or C or Java or C# will get you started off right.  All of those languages are Algol based (roughly) - once you've learned one of them, learn Lisp or Haskell.  The terrific paradigm shift between the two families will aid you no matter what your courses entail.  </p>


答:
This looks like a read from cache with lazy loading.  As others have noted, checking and loading may belong in other methods.  Loading may need to be synchronized so you don't get twenty threads all loading at the same time.

It might be appropriate to use a name getCachedStuff() for the getter as it won't have a consistent execution time.

Depending on how the cacheInvalid() routine works, the check for null may not be necessary.  I wouldn't expect the cache to be valid unless stuff had been populated from the database.

Title: How Much Logic in Getters

Body:
My coworkers tell me there should be as little logic as possible in getters and setters.

Yet, I am convinced that a lot of stuff can be hidden in getters and setters to shield users/programmers from implementation details.

An example of what I do:

```<code>public List<Stuff> getStuff()
{
   if (stuff == null || cacheInvalid())
   {
       stuff = getStuffFromDatabase();
   }
   return stuff;
}
</code>```

An example of how work tells me to do things (they quote 'Clean Code' from Uncle Bob):

```<code>public List<Stuff> getStuff()
{
    return stuff;
}

public void loadStuff()
{
    stuff = getStuffFromDatabase();
}
</code>```

How much logic is appropriate in a setter/getter? What's the use of empty getters and setters except a violation of data hiding?


问:
What is an algorithm to find simple cycles?
I have a graph with an Eulerian cycle and no Hamiltonian cycles. I would like to divide this graph into simple cycles.

Edges may not be repeated in simple cycles.

How can this be done?

答:
Follow your Eulerian cycle. Whenever you arrive at a vertex you've been at before, the part between the two visits is a simple cycle. Chop that off and store it in the list of simple cycles, mark all vertices used in that, except the one you are at now, as unvisited. Continue until all edges have been used.

To find a Eulerian cycle, Hierholzer's method is efficient.

OwnerDisplayName: Daniel Fischer


答:
This problem is just as hard as finding a Hamiltonian cycle. I don't think you can use the fact that the graph has an Eulerian Cycle.

You can use the obvious O(n!) algorithm: For each permutation of nodes, go through the list and see if the path you take is a partitioning in simple graphs.

But you can probably do better using dynamic programming.

Title: What is an algorithm to find simple cycles?

Body:
I have a graph with an Eulerian cycle and no Hamiltonian cycles. I would like to divide this graph into simple cycles.

Edges may not be repeated in simple cycles.

How can this be done?

OwnerDisplayName: Thomas Ahle


答:
If you don't already know the Eulerian cycle, use Hierholzer's algorithm.

(Edited to show how to find every simple cycle in the network, not just those contained within the EC. Is this what the questioner wanted?)

Assuming that you actually already know a Eulerian cycle, then simply follow the Eulerian cycle. Every time you visit a node that you have already visited, then you have found a cycle. You should check that it is a simple cycle by making sure  that there are no other repeats within this cycle. For example

```<code>A -> B -> C -> D -> B -> E -> A
</code>```

A ... A is a cycle, and B -> B is a cycle, but only the latter is a simple cycle

Also, two simple cycles could share many nodes and edges with each other. For example,

```<code>A -> X -> B -> Y -> A -> Z -> B
</code>```

A ... A and B ... B are simple cycles which share nodes and edges with each other.

= Finding every simple cycle in the graph =

Every simple cycle will either be contained with the Eulerian Cycle (EC), or will be spread out throughout the EC. For example of what I mean by 'spread out', we can see the simple cycle A -> B -> C -> A within this EC:

```<code>D -> A ==> B -> E -> F -> B ==> C ==> A -> D
</code>```

where I've highlighted some edges by making them longer. Those edges form part of the simple cycle. So, given and EC and the goal to find every simple cycle, it's a question of enumerating all subsets of the edges in the EC.

But you can speed things up considerably with a simple observation. If you decide to include A->B in your candidate simple cycle, then the next edge that you decide to include must begin at B and you can then skip over many of the following edges. This should make it easier to ignore many large parts of the search tree.

In fact, I think this algorithm is pretty much optimum efficiency for finding all simple cycles. Any thoughts?

Body:
If you don't already know the Eulerian cycle, use Hierholzer's algorithm.

(Edited to show how to find every simple cycle in the network, not just those contained within the EC. Is this what the questioner wanted?)

Assuming that you actually already know a Eulerian cycle, then simply follow the Eulerian cycle. Every time you visit a node that you have already visited, then you have found a cycle. You should check that it is a simple cycle by making sure  that there are no other repeats within this cycle. For example

A -> B -> C -> D -> B -> E -> A

A ... A is a cycle, and B -> B is a cycle, but only the latter is a simple cycle

Also, two simple cycles could share many nodes and edges with each other. For example,

A -> X -> B -> Y -> A -> Z -> B

A ... A and B ... B are simple cycles which share nodes and edges with each other.

= Finding every simple cycle in the graph =

Every simple cycle will either be contained with the Eulerian Cycle (EC), or will be spread out throughout the EC. For example of what I mean by 'spread out', we can see the simple cycle A -> B -> C -> A within this EC:

D -> A ==> B -> E -> F -> B ==> C ==> A -> D

where I've highlighted some edges by making them longer. Those edges form part of the simple cycle. So, given and EC and the goal to find every simple cycle, it's a question of enumerating all subsets of the edges in the EC.

But you can speed things up considerably with a simple observation. If you decide to include A->B in your candidate simple cycle, then the next edge that you decide to include must begin at B and you can then skip over many of the following edges. This should make it easier to ignore many large parts of the search tree.

In fact, I think this algorithm is pretty much optimum efficiency for finding all simple cycles. Any thoughts?

OwnerDisplayName: Aaron McDaid


问:
Dependency Injection and Singleton. Are they two entirely different concepts?
I've been hearing about using the dependency injection over Singleton for my colleague. I still can't make out if it they are two orthogonal patterns which can be replaced with one another? Or is DI a method to make the Singleton pattern testable?

Please take a look at the following code snippet.

```<code>    IMathFace obj = Singleton.Instance;

    SingletonConsumer singConsumer = new SingletonConsumer(obj);

    singConsumer.ConsumerAdd(10,20);
</code>```

The SingletonConsumer is accepting a parameter of type IMathFace. Instead of accessing the singleton class internally, SingletonConsumer will get the singleton instance passed by the caller. Is this a good example of consuming singleton class via dependency injection?

答:
Yes, you are right. Instead of accessing the object via the singleton, you are passing a reference to it thus you're using a constructor injection.

What others point out is that these notions are not related. Consuming a singleton instance is nothing special as the object you are injecting to doesn't really care where the injected object comes from.

OwnerDisplayName: logeeks

OwnerDisplayName: Wiktor Zychla


答:
There is one case where the Singleton pattern and DI/IoC intersect- the injection of a Singleton.

Most DI frameworks can be configured to instantiate a single instance of an injected object.  Any consumer object that requests an instance of such an object will get the same single instance.  That instance is by definition a Singleton.  That's about it for the overlap in concept.

Title: Dependency Injection and Singleton. Are they two entirely different concepts?

Body:
I've been hearing about using the dependency injection over Singleton for my colleague. I still can't make out if it they are two orthogonal patterns which can be replaced with one another? Or is DI a method to make the Singleton pattern testable?

Please take a look at the following code snippet.

```<code>    IMathFace obj = Singleton.Instance;

    SingletonConsumer singConsumer = new SingletonConsumer(obj);

    singConsumer.ConsumerAdd(10,20);
</code>```

The SingletonConsumer is accepting a parameter of type IMathFace. Instead of accessing the singleton class internally, SingletonConsumer will get the singleton instance passed by the caller. Is this a good example of consuming singleton class via dependency injection?

OwnerDisplayName: Dave


答:
The confusion here is that two concepts have been conflated: the singleton and the static accessor/gateway to the singleton instance.

As you have rightly identified, your colleague is suggesting that the dependency be injected rather than accessed directly using Singleton.Instance (static gateway).

The reason that this has nothing really to do with the singleton pattern is that the same DI concept applies equally to instantiating a non-singleton object with new Foo(). The dependency would be injected irrespective of whether it is a singleton implementation.

OwnerDisplayName: Jay


答:
I think he meant that you should use dependency injection to inject a single instance of the service, instead of using the classical Singleton implementation with a static accessor MySingleton.Instance.

```<code>public class MySingleton
{
    public static MySingleton Instance{get{...}};
}
</code>```

With the classical singleton implementation all your code depends on that service being a singleton. You basically hardcode that assumption into consuming code whenever you use MySingleton.Instance.

On the other hand with DI you get an instance of the service passed into your constructor, and store it. That there is only a single instance of this service is an implementation detail. You can easily change it to give the consuming code a different instance. That way you have some class/interface which happens to be implemented by a single instance, instead of enforcing that there is only one instance.

This is useful if you for example want a mock implementation of the service for testing, or if different parts of the program need different configurations of that service.

Body:
I think he meant that you should use dependency injection to inject a single instance of the service, instead of using the classical Singleton implementation with a static accessor MySingleton.Instance.

public class MySingleton
{
    public static MySingleton Instance{get{...}};
}

With the classical singleton implementation all your code depends on that service being a singleton. You basically hardcode that assumption into consuming code whenever you use MySingleton.Instance.

On the other hand with DI you get an instance of the service passed into your constructor, and store it. That there is only a single instance of this service is an implementation detail. You can easily change it to give the consuming code a different instance. That way you have some class/interface which happens to be implemented by a single instance, instead of enforcing that there is only one instance.

This is useful if you for example want a mock implementation of the service for testing, or if different parts of the program need different configurations of that service.

OwnerDisplayName: CodeInChaos


问:
Can I brand my open-source application?
Is it possible for the author to register a logo or the name of his/her application when it is open-source because it uses a gpl library (for example)? The application uses the library but it has its own features, that is it's not a modification of the library.
So everyone can see the source code, downloading an "anonymous" non-branded version from Sourceforge, but none can use the logo or the name and so the author can sell it from his/her web-site (for example) to non-expert users, only after payment.
Is he/she obliged to give directly the source code, or it is enough that there is the non-branded version available on Sourceforge or other official repository?</p>

答:
If you are distributing binaries of a GPLed program YOU must make the source code available.  Pointing to a third party site is not enough.

To address the question of trademarks in GPLed code. If the code is GPL then you must distribute the same source (Trademarks and all) used to build the binary.

As an example see Red Hat Enterprise Linux, the source with trademarks is made available by Red Hat.  CentOS and Scientific Linux remove the trademarks when they repackage RHEL.

Title: Can I brand my open-source application?


答:
Generally speaking, the way to protect a logo or a name of a product is to register it as a trademark.  The details of how you register a trademark, and the protections that this gives you will vary depending on your country.  Talk to an IP lawyer for more information ... or check with the agency of your government that is responsible for trademarks.

Open source licenses are based on copyright, and this is generally speaking orthogonal to trademarks and patents.  However, a genuine open source license would allow anyone to remove your branding / logos / etc, and distribute a no-name version or a version with their logo and branding.  (Some open source licenses require some kind of acknowledgement of the origins of the code.)

So basically, what you are wanting to do is possible from a legal perspective (IANAL, etc).

However, it is not clear that this will achieve what you want.  It will allow you to sell your branded version (subject to the conditions of any upstream licensing of course) but it won't prevent someone else from stripping out your brand, etc.  And the chances are that someone will do this ... assuming that your product is worthwhile in the first place.

So really, branding per se doesn't offer you any competitive edge with an open source product.  You should really be focusing on offering value for the customer's money in another area than old-style licensing fees.  For instance, try to make your money on offering support services, customizations, and things like that.  Or by getting sponsorship.

And once your brand has an association in the customer's mind with good value for money ... then the brand starts to have a value.

This is not to say that trademarks are not without value to you.  For a start, they can defend you against some opportunist scum making trouble by trademarking your product's name and using that as leverage to extract money.

Title: Can I brand my open-source application?

Body:
Is it possible for the author to register a logo or the name of his/her application when it is open-source because it uses a gpl library (for example)? The application uses the library but it has its own features, that is it's not a modification of the library.
So everyone can see the source code, downloading an "anonymous" non-branded version from Sourceforge, but none can use the logo or the name and so the author can sell it from his/her web-site (for example) to non-expert users, only after payment.
Is he/she obliged to give directly the source code, or it is enough that there is the non-branded version available on Sourceforge or other official repository?</p>


问:
How to use a switch statement with enum efficiently?
I would like to know how I can use a switch statement with enum values for the following scenarios:

I am making a small program for a flight reservation system. The program is meant to enter certain details about the passenger. The program also restricts the user to choose destinations other than the following 3 destinations. Once destination is chosen, the flight number  is supposed to be automatically assigned.
The user will choose one of three destinations and program will assign an appropriate Flight No for the passenger.

The Flight No will be assigned as below:

```<code>     Destination                    Flight No.
      London                            201
      Frankfurt                         233
      Berlin                            241
</code>```

So let's say I make an enum of destinations, then how can I use switch statement here? This isn't a homework. I am doing it just for the sake of exploring.

答:
Your scenario doesn't sound like an appropriate use for an enumeration. Also, unless the values never change, this should be data driven.

If the values never change, then a key-value pair is more appropriate where the destination is the key and the flight number is the value. This would eliminate any need for a switch statement, as the key can be used to directly and efficiently locate the value.

if you really want to use an enum, then the switch statement in C# would be something like:

```<code>int flightNumber;
Destination selection = // some value collected from user input;

switch( selection )
{
    case Destination.London:
        flightNumber = 201;
    break;

    // etc.
}
</code>```

Body:
Your scenario doesn't sound like an appropriate use for an enumeration. Also, unless the values never change, this should be data driven.

If the values never change, then a key-value pair is more appropriate where the destination is the key and the flight number is the value. This would eliminate any need for a switch statement, as the key can be used to directly and efficiently locate the value.

if you really want to use an enum, then the switch statement in C# would be something like:

int flightNumber;
Destination selection = // some value collected from user input;

switch( selection )
{
    case Destination.London:
        flightNumber = 201;
    break;

    // etc.
}


答: Lua and LÖVE. Lua is one of the simplest languages available. The LÖVE framework is optimized for 2D games. It also has an OpenGL backend, with the performance and other benefits that that brings.</p>

Title: A free game-development language?

Body:
So, I'm trying to teach my much younger cousin a little bit about programming. My initial thought was something like Scratch or Alice, but there were a few downsides to that.

Everyone seems to be really in to game programming and developing video games (because     everyone loves playing video games, and as far as playing video games goes, playing your own can be the most rewarding) - but neither Alice nor Scratch seem to cater to game development

Alice and Scratch seem too childish, while I'm sure my cousin would
enjoy dabbling in it, I think he'd quickly bore of it

I want a language that can be used to develop really cool stuff that
will impress his friends. I remember writing BASIC back in the day
and inviting all my friends over and showing off my creation, and I
just feel like Alice and Scratch just don't appeal in the same way

I want a language that requires my cousin to write code. Now, this
isn't just because I think typing code out is good preparation for
other programming languages, but it's because it gives him an
opportunity to actually practice typing, and maybe get used to some
of the slightly more esoteric characters on the keyboard

Now, that's why I don't want to choose Alice or Scratch.

I also don't want to pick a language like C or Java, or even Python or Ruby for that matter. My cousin has already imparted to me that he enjoys playing video games and wants to make his own, and that he enjoys using computers. In my opinion, even a simple language like Python or Ruby simply takes too long to build cool stuff. Ideally, he'd sit down, spend around a day or two (or maybe even up to a week, but hopefully less than that) and have a working, 2-dimensional game. I'm not saying you can't do it in Python or Ruby, but I'm just saying it would be difficult for a first-time programmer. Plus, I don't want to bog him down with all the computer science stuff, as that can come later. I just want to help him create the spark, and then let him carry on with the rest of the fire.

I've looked at languages like Lua, and while it seems common in game programming, I'm not sure if it's the best pick - but if you guys think otherwise, please let me know.

I've also looked at a language like Blitz and it looks really promising (plus, I tried it out a few years ago, and it was really quite nice). The downside is that I have to pay, something I'm definitively against.

I've looked at SmallBasic, which seems promising and I'll continue looking at. But I haven't done much (in fact, I'm running the installer as I type this, so I'll report my thoughts on it shortly).

UPDATE: I gave SmallBasic a quick try and it seems intriguing, but it also seems quite different compared to some other languages - that's not a bad thing, but it just is an unusual. Out of the things I've looked at, Blitz is still my favorite, but I refuse to go there because of the cost.

But basically, what do you guys think of what I've said so far, and the languages I've looked at and do you know of any other, good alternatives?

UPDATE: Here's what I've chosen to do...

I've realized that while I would love to help my cousin, I can't be with him all the time, and I can't help him every time he needs help. So, I wanted to choose something that has a good documentation, a good community, and a good book he can follow.

Anyways, I've chosen Python and Pygame. Python is a language I'm fairly familiar with, plus I know there is a pretty good (and pretty large) community around Python. Furthermore, I know that the Python documentation is fairly complete and easy to navigate. Pygame also has an excellent documentation and set of tutorials. I'm also having him use/follow Invent Your Own Computer Games with Python, which seems like a very good book, I bought him a hard copy as a Christmas present, plus I know that his monitor isn't huge, and it would be inconvenient to constantly swap back between the text and the editor.

I think it should go well!

EDIT: I don't want to imply that my choice is final or that it is correct. I just think it's the best fit for this situation. I think each person looking to teach someone younger should browse the selection and find the best solution for the individual person, considering things like age, skill level, and interest.


答:
I agree with Tim Medora, it is not a proper idea to use an enum in that case, because it forces you to have hardcode your destinations and your flight numbers.

What I would encourage you to do, is to have a of possible destinations List<string> and a mapping between the destinations and the flight number, e.g Dictionnary<string,int> which you generate dynamically at the start of the program according to the content of the database.

Title: How to use a switch statement with enum efficiently?

Body:
I would like to know how I can use a switch statement with enum values for the following scenarios:

I am making a small program for a flight reservation system. The program is meant to enter certain details about the passenger. The program also restricts the user to choose destinations other than the following 3 destinations. Once destination is chosen, the flight number  is supposed to be automatically assigned.
The user will choose one of three destinations and program will assign an appropriate Flight No for the passenger.

The Flight No will be assigned as below:

```<code>     Destination                    Flight No.
      London                            201
      Frankfurt                         233
      Berlin                            241
</code>```

So let's say I make an enum of destinations, then how can I use switch statement here? This isn't a homework. I am doing it just for the sake of exploring.


问:
How common are "bandage" fixes?
Imagine the following scenario:

You've detected that your (or someone else's) program has a bug - a function produces the wrong result when given a particular input. You examine the code and can't find anything wrong: it just seem to bog out when given this input.

You can now do one of two things: you either examine the code further until you've found the actual cause; or you slap on a bandage by adding an if statement checking if the input is this particular input - if it is, return the expected value.

To me, applying the bandage would be completely unacceptable. If the code is behaving unexpectingly on this input, what other input that you've missed will it react strangely to? It just doesn't seem like a fix at all - you're just shoveling the problem under the rug.

As I wouldn't even consider doing this, I'm surprised at how often the professors and books keep reminding us about how applying "bandage" fixes is not a good idea. So this makes me wonder: just how common are these kinds of "fixes"?

答:
Time

Is the #1 reason in my opinion. Although if the problem is codebase wise I might take more time to investigate it. Often my "bandage" fixes involve CSS or UI tweaks. I've written some pretty nasty inline CSS and JavaScript to deal with them quickly. Going back and fixing it is always an option if you get the time.

ContentLicense: CC BY-SA 2.5

Title: How common are "bandage" fixes?


问:
Encapsulating a single property
If you have a single property that is relevant across a full project, but you should logically have only a single representation of, how would you represent this? In my case, I am developing a simple drawing app where the user can select a colour.  This colour should then be available to all the pen/shape classes in the project.

Would I simple just have a static class with a static property of Color CurrentColor (C#), that each client class could then call, or is there a more effective way?

答:
First of all, it is important to differentiate between the light headed remark "I need it everywhere in my project" and "I need it in all X classes in my project", because the first leads to static getters and singletons, and the latter to proper dependency injection.

Obviously Singletons are an option, but since they pretty much create global variables, you're going to want to prefer explicit atomic dependencies.

So you don't want to tie your whole project to one property (even if it currently seems like a good choice). You want to couple only what requires coupling, by definition.

In your case, one option I'd suggest is to create a ColorSelection class, and a Toolbox class (or something along those lines) that passes the current ColorSelection to a just-selected tool. In other words, the tool's Click handler (in the toolbox) would set the tool's SelectedColor property to the instance defined (and bound) by the toolbox.

In code (very inaccurate, but just so you get the point):

```<code>class ToolBox {
  ColorSelection SelectedColors {get; set;} // This could be bound to the view

  Tool Pen {get; set;}

  public event ToolEventHandler ToolSelected; // handled by the method below

  void ToolSelectedHandler(object sender, ToolEventArgs e) {
    e.Tool.SelectedColors = SelectedColors;
  }
</code>```

Title: Encapsulating a single property

Body:
First of all, it is important to differentiate between the light headed remark "I need it everywhere in my project" and "I need it in all X classes in my project", because the first leads to static getters and singletons, and the latter to proper dependency injection.

Obviously Singletons are an option, but since they pretty much create global variables, you're going to want to prefer explicit atomic dependencies.

So you don't want to tie your whole project to one property (even if it currently seems like a good choice). You want to couple only what requires coupling, by definition.

In your case, one option I'd suggest is to create a ColorSelection class, and a Toolbox class (or something along those lines) that passes the current ColorSelection to a just-selected tool. In other words, the tool's Click handler (in the toolbox) would set the tool's SelectedColor property to the instance defined (and bound) by the toolbox.

In code (very inaccurate, but just so you get the point):

class ToolBox {
  ColorSelection SelectedColors {get; set;} // This could be bound to the view

  Tool Pen {get; set;}

  public event ToolEventHandler ToolSelected; // handled by the method below

  void ToolSelectedHandler(object sender, ToolEventArgs e) {
    e.Tool.SelectedColors = SelectedColors;
  }


答:
There exist very close to absolute zero situations where a decent design may legitimately require the use of a global variable. Global variables are as bad as goto, never use either of those.

Your simple drawing app should have a class representing the "currently selected settings". A reference to this class should be passed at construction time to every single class that may need it. So, for example, the first parameter of the constructor of your pen class should accept a reference to the "currently selected settings" class, so that the pen can fetch the currently selected color from it, or whatever else it may need, like pen thickness, opacity, solidity, step, etc.

The "currently selected settings" class should also have a "Changed" event, to which any currently active tool subscribes, so that if the user changes, say, the current color, the pen (or whatever tool happens to be selected) can take notice and re-fetch the color from it.

Title: Encapsulating a single property

Body:
If you have a single property that is relevant across a full project, but you should logically have only a single representation of, how would you represent this? In my case, I am developing a simple drawing app where the user can select a colour.  This colour should then be available to all the pen/shape classes in the project.

Would I simple just have a static class with a static property of Color CurrentColor (C#), that each client class could then call, or is there a more effective way?


问:
How do you handle time series .Net?
I have been looking for Time Series models over in SO, but I figured this place was the best site to actually ask the question.

I am wondering what is the "best" way to handle Time Series in .Net.

First, I would define a Time Series as a mapping of different DateTime with a single value of type T.

The value can possibly be null.

Several methods should be available so that the series can be manipulated easily. For example, you want to be able to Filter the data (based on criteria on dates and/or on values). You would also like to have an Apply method, which applies a given function to all the values. Ideally, you would be willing to run some of these functions in parallel to increase performance.

Several data structures already implement such features, such as a Dictionary<DateTime,T>, possibly even a SortedDictionary<DateTime,T>. However, these are mutable structures, which can be an issue if there are some closure effects.

Which model would/did you use?

Do you know an existing library already widely used for this matter?

答:
When I implemented a History<T> class (a sorted list of date values associated with some data of type T, allowing for old values to be dropped when new one's come in and a maximum size was reached etc.) I did it as a wrapper class around SortedDictionary<DateTime, T>.

Because this collection implements IEnumerable, you can use LINQ's extension methods to do the filtering, applying a function and so on. If you want to parallelize these operations, there is PLINQ.

If you worry about the structure being mutable, you will just have to make sure that all access to it is synchronized (e.g. via a lock in the wrapper class). If you add elements to the class only once, there shouldn't even be a need for such a lock, as the class "becomes immutable" if your wrapper does not allow it to be modified later on.

Title: How do you handle time series .Net?


问:
Need help understanding reference operator(C++) in specific functions
In the current semester at the university we are working on OOP with C++.

I would like to understand the difference between a pointer and a reference operator.

The differences that I understand are:

1. Cannot change the object that the reference variable is binded to

2. we can use the reference variables to refer to the binded object without having to type the & operator (in contrast with the pointers where we would write *pi = 5;)

Also,does a reference variable contain the address of the object that is binded to?

In example:

```<code>int i;
int &ri = i;
</code>```

Here ri contains the address of i?

And the reason why when overloading ++ operator in this example of enumeration we are using the dereference or reference(*) operators before the name of the function.

答:
Technically speaking, references are not objects and you cannot reason about their contents. However, in reality, as pointers under the hood that's how they're often implemented.

As for the function declaration/definition, they are not operators. They are syntax. int& is a type. It means "I return a reference". Returning an int& isn't any different to returning an int- you return a thing of that type.

Of course, it's double use as syntax and an operator isn't helpful, but there is no operating going on here.


答:
Both your assumptions ("the drawing color is needed everywhere", and "there should only ever be a single instance of the current drawing color") are false. Let me elaborate:

A large part of your codebase is not going to be affected by the current drawing color: think about things like the UI (the parts that are not directly related to selecting the drawing color), image file format handling (loading / saving / converting), lower-level routines like showing file-open / file-save dialogs, etc. etc.

You may want to reuse some drawing-related functions in a different context; even though they have a notion of "current drawing color", you will run into problems soon if the current drawing color is global. Suppose you have a routine that draws a rectangle onto an image; now you want to reuse it to implement an effect filter that also needs to draw rectangles. If your current drawing color is global, you need to store it in a temporary variable, change it, draw your rectangle, and then reset it to the stored value. This is cumbersome and brittle, especially when drawing operations can be asynchronous. Another example would be if you need to handle multiple images (something MDI-ish, say), and you want to keep track of the current drawing color for each image, independently. If your current drawing color is global, you'll be cursing and swearing a lot.

Personally, I'd put all related state variables (current drawing color, current background color, current pattern, etc.) into a DrawingState class (with the usual encapsulation in place) and explicitly pass that to each drawing operation. This way, you reduce the amount of coupling and the number of potential changes to the state, and you increase the unit-testability of the drawing routines. In other words, your code will be cleaner, easier to verify, easier to debug, and easier to modify.

Title: Encapsulating a single property


答:
This is a typical Hash table, isn't it?

It will be much more efficient to use hash table when the number of entries is large, which in your case is very likely.

It is easier to implement the operations on the retrieving, storing and modifying data than your enum-switch implementation.

It's easier to maintain the code. It will be horrible if you have dozens of destinations defined in your enum and switch statements.


问:
How do you know when to stop adding features?
Some time ago I wrote a very small python script that periodically checked an xml feed for new entries, and alerted the user to new entries when present.
I wrote this for myself, so it was essentially a console based program that anyone comfortable with a console interface could have used.

After a while I decided it could be of more use to other people and began to tidy it up, sanitize inputs, remove bugs. It occurred to me that because I'd written the script I knew how to use it efficiently, accurately etc. Others might not, so I started adding a GUI. This started out as a simple menu, and then expanded to a more full GUI with both an interface and options menu. I then added stored user preferences and also storage for previously searched xml feeds to speed up repeat searches.

I added logging to help debug the application in case things go wrong, brought the application up to the latest available stable python codebase for my chosen platform and improved dialog features.

I've bugfixed and commented my code clearly, and yet I still have things I think can be done to improve the app before I make it available to alpha testers. It's a far far cry from my original 20-30 line script. What I anticipated would take me just an hour or two to go from proof of concept to an acceptable use program has taken 10-20 times that. (I'm still a noob, and stuff takes me a long time, but still....)

How do you know when to stop adding/tweaking/fixing stuff and let your baby crawl out in the open?

答:
I'd suggest you timebox it. Give yourself a say week. Create a list of work to complete during that week, and make sure if you have a feature you can't complete you can back it out.

At the end of the week release it. Release early, release often.


问:
What type of applications Silverlight is designed for?
I have 3 years experience in ASP.NET with C# and now I am learning Silverlight with Beginning Silverlight 4 in C# book.

As I have completed my first 4 chapters, I am getting the feeling that Silverlight is just about creating RIA which can also be done with Flash.

What is a scope of Silverlight for a C# programmer?

答: Silverlight is Microsoft's "replacement" for Flash.  It is meant to do what Flash does, although I would say that Microsoft's emphasis is different.  Silverlight is for making browser/device independent applications, especially RIA.  You could do a "dull" business app in Silverlight if you wanted to gain the browser/platform independence that Silverlight offers.  One area where Flash is often used but where Silverlight is (arguably) not intended to be strong is in keyframe-based animations (i.e. cartoons).</p>


问:
In Knuth's MMIX, how can x be an octabyte (64 bits) and M[x] be a byte (8 bits)?
In Knuth's Fascicle 1 on MMIX, the "Memory and Registers" section on page 4 states:

"thus if x is any octabyte, M[x] is a byte of memory."

and

"thus if x is any byte, $x is an octabyte."

How can x be an octabyte (64 bits) and M[x] be a byte (8 bits)? Conversely, how can x be a byte and $x be an octabyte?

答:
MMIX is a notional 64-bit computer, so its address bus has 64 lines and it can be fitted with up to 2^64 memory cells. Each of these cells, however, holds 1 byte (8 bits) and not 64 bits, therefore you have 2^64 bytes (not octobytes) of RAM. (It is customary to measure RAM in bytes and not in double-, quad- or octo-bytes even when the architecture has more than 8 bits. It is also convenient to retrieve individual bytes from memory because many algorithms  require only small numbers in many places. In practice, processor caches obscure this distinction anyway.)

The registers, however, are full 64-bit registers, therefore $x is an octobyte, not just a byte. Again, this is a convention for processor architecture rather than a fixed law, but most architectures that claim to be X-bit (for an impressively large value of X) also sport X-bit registers, so that when you do want to load X bits from memory simultaneously, you can receive them in just one register without spilling.


问:
Building a route creator
Ok, already up front, I'm going to tell you, that this is a bonus task for Data structure course I'm taking. That should take care of all the questions whether or not this is for a homework.

Route creator

I have a task, where a company has to create a route for a given data set. The data set can be input for every operation and in the end, it should print out the optimum route. The conditions are like this:

Streets can only be directed North-South or East-West, effectively making every angle between 2 streets in 90 degrees.

The data set includes streets, junctions and places to pick client and where to drop him off, as well as the starting place for the car.

My problem is, that I'm having trouble thinking of the correct data structure way to do this.
What came up first from the top of my head was a directional graph. In theory, it should fit perfectly

Streets are input up front with numeric identificators

A node represents junction and is represented by the id's of the streets

An edge between 2 nodes represents a piece of street and has length

Places of interest are effectively a sub-class of Junction nodes therefore they have distance from the one node to another.

Best route would then be calculated by finding the shortest path from the starting place of the car to the starting place of the client + shortest path from the starting place of the client to the ending place of the client + shortest path from the ending place of the client to the starting place of the car.

Is my thinking in this matter even remotely correct? I am finding this quite difficult to image with any other data structure than a directed graph, but maybe I'm just limiting my options with this thinking.

答: A directed graph should be the best approach in your case. It is probably true that some more optimal structure could perhaps be devised taking into consideration the given constraint that streets can only be directed North-South or East-West, but I would not even waste any time thinking about this possibility: it would tie your solution to an artificial constraint and it would result in a data structure that would be more hacky and less academic. You might want to take this constraint into account if you are ever asked to draw the map of your domain, but that's all.</p>

Title: Building a route creator


答:
Because “plain ol’” memory addresses address bytes. Notice, though, that if you are addressing more than one byte of memory multiple memory addresses point to the same thing.

To be sure, there are 2^(64) bytes of memory, 2^(63) wydes, 2^(62) tetrabytes, and 2^(61) octabytes. You basically end up with 3 ignored bits when addressing octabytes.

In other words, if f(x) is a function from an address x to its memory cell (think of *x in C), f(x) isn’t bijective; moreover, f(x) is only a binary operation when you’re addressing octabytes (i.e., for x in X f(f(x) is in X too).

You can think of it like pointers to int, double, etc.

Nice to see people reading about MMIX!

Title: In Knuth's MMIX, how can x be an octabyte (64 bits) and M[x] be a byte (8 bits)?

Body:
In Knuth's Fascicle 1 on MMIX, the "Memory and Registers" section on page 4 states:

"thus if x is any octabyte, M[x] is a byte of memory."

and

"thus if x is any byte, $x is an octabyte."

How can x be an octabyte (64 bits) and M[x] be a byte (8 bits)? Conversely, how can x be a byte and $x be an octabyte?


答:
Technically, there are not much differences between variable of type int* and int& (except those syntactical details about dereferencing and member access). The main difference in practical use IMHO is that you cannot change the object a reference is refering to after initializiation (while you can change the adress a pointer points to), and a reference cannot be NULL (at least, not without some ugly C++ casting hacks).

Here is a comprehensive explanation of the topic:

http://www.parashift.com/c++-faq-lite/references.html#faq-8.2

Title: Need help understanding reference operator(C++) in specific functions

Body:
In the current semester at the university we are working on OOP with C++.

I would like to understand the difference between a pointer and a reference operator.

The differences that I understand are:

1. Cannot change the object that the reference variable is binded to

2. we can use the reference variables to refer to the binded object without having to type the & operator (in contrast with the pointers where we would write *pi = 5;)

Also,does a reference variable contain the address of the object that is binded to?

In example:

```<code>int i;
int &ri = i;
</code>```

Here ri contains the address of i?

And the reason why when overloading ++ operator in this example of enumeration we are using the dereference or reference(*) operators before the name of the function.


问:
research papers vs books
For studying advanced topics, what's the better and nearer to complete approach? Can books cover what's in research papers, journals or those ACM transactions, or Springer's LNCS? Or reading research papers is indispensable for getting advanced? If we can't depend on books for information, how can a learner know of what he is missing in a specific topic, since research papers cover a specific (very specific) topic which cannot be found in a collected manner of the whole topic as books do. Is there a place (may be wikipedia) which could help finding the way through a topic? Rephrasing my question, do research papers offer new information which may not be found in books or are they clever applications of the information found in books?</p>

答:
Most research is going to be dependent on other research, but should offer something more or at least help in confirming an existing belief. I would expect to learn something new that wouldn't be found in other books. Otherwise, what's the point?

Books tend to pull lots of information into a single location. I would expect them to utilize the existing research and not the other way around.

Title: research papers vs books


问:
Should one use pseudocode before actual coding?
Pseudocode helps us understand tasks in a language-agnostic manner. Is it best practice or suggested approach to have pseudocode creation as part of the development lifecycle? For instance:

Identify and split the coding tasks

Write pseudocode

Get it approved [by PL or TL]

Start Coding based on Pseudocode

Is this a suggested approach? Is it practiced in the industry?

答: I would definitely recommend pseudocode. It helps you clarify what you are going to do and identify items you may have forgotten or potential problems. Its far easier/faster to fix your code when it's still in the planning stages rather then waiting until you've already coded a large portion of it.</p>


答:
Books, or what is is often referred to as the "dead tree edition" take months to print. In a rapidly advancing field like medicine where knowledge doubles every 18 months (or less), the printed version might well be considered a "history book".

Websites like this one are constantly being updated and often you can get the latest information very quickly from extremely knowledgeable people. Even better, you get a two-way interaction so you can request a better explanation for something you don't fully understand.

Journals come in both on-line and printed versions. Clearly a printed journal lies somewhere between books and current information in terms of timelessness.

As for a "complete" approach? A wise person will utilize all available sources of value, including books and journals.

Title: research papers vs books

Body: For studying advanced topics, what's the better and nearer to complete approach? Can books cover what's in research papers, journals or those ACM transactions, or Springer's LNCS? Or reading research papers is indispensable for getting advanced? If we can't depend on books for information, how can a learner know of what he is missing in a specific topic, since research papers cover a specific (very specific) topic which cannot be found in a collected manner of the whole topic as books do. Is there a place (may be wikipedia) which could help finding the way through a topic? Rephrasing my question, do research papers offer new information which may not be found in books or are they clever applications of the information found in books?</p>


答:
It strikes me that knowing that all streets run N_S or E_W will allow you to easily compute an excellent heuristic for the A* algorithm, which on first thought would seem to be the best general purpose algorithm to solve this.

With such a great heuristic you should be able to use an extremely sparse structure due to the ability to do extensive pruning.

EDIT - In response for the request to elaborate on the heuristic:
With the A* algorithm one requires an admissible heuristic, {h(x)} that is an estimate of the distance from the current node to the target. To be "admissible" the heuristic, or estimate of the distance from the current point (x) to the goal must be less than or equal to the true distance. Normally one might use the straight line distance ("as the crow flies") between the two points, since no actual road could be shorter than a straight line.

In your problem you are told that all roads run north-south or east-west, thus no diagonal roads. Lets take a specific example: Suppose one wants to estimate the minimum distance, h(x), for starting at the point (0,0) and traveling to (10,10). Now this is a square with a side of length 10, so ordinarily one would estimate that there could be a road that went straight from (0,0) to (10,10) so the straight line distance would be the square root of 200 or approx 14.14. But in your case, since all roads run N-S or E-W we know that the minimum possible distance is 20. Of course the true distance might be more depending what roads are available.

Since you have an admissible heuristic for two points (x1,y1), (x2,y2) being h(x) = (abs(x2-x1) + abs(y2-y1)); this h(x) is always greater than or equal to the straight line distance, and thus is a "better" heuristic in that it will lead to a smaller solution space which will need to be explored. In other words greater tree pruning.

Title: Building a route creator

Body:
Ok, already up front, I'm going to tell you, that this is a bonus task for Data structure course I'm taking. That should take care of all the questions whether or not this is for a homework.

Route creator

I have a task, where a company has to create a route for a given data set. The data set can be input for every operation and in the end, it should print out the optimum route. The conditions are like this:

Streets can only be directed North-South or East-West, effectively making every angle between 2 streets in 90 degrees.

The data set includes streets, junctions and places to pick client and where to drop him off, as well as the starting place for the car.

My problem is, that I'm having trouble thinking of the correct data structure way to do this.
What came up first from the top of my head was a directional graph. In theory, it should fit perfectly

Streets are input up front with numeric identificators

A node represents junction and is represented by the id's of the streets

An edge between 2 nodes represents a piece of street and has length

Places of interest are effectively a sub-class of Junction nodes therefore they have distance from the one node to another.

Best route would then be calculated by finding the shortest path from the starting place of the car to the starting place of the client + shortest path from the starting place of the client to the ending place of the client + shortest path from the ending place of the client to the starting place of the car.

Is my thinking in this matter even remotely correct? I am finding this quite difficult to image with any other data structure than a directed graph, but maybe I'm just limiting my options with this thinking.


答:
Make a grid (two dimensional array) of Junctions.  Each Junction may have a south bound and an east bound exit (the north and west ones are exits from the neighbor cell).  Each exit may have a name and a number interval.  This allows you to navigate.

For easier lookup a given street name is a list of Junction references.

Title: Building a route creator


答:
A reference is another name(alias) for an existing object; it gives you the power of "pass by reference" and the convenience of using it like you would the object itself.

In your example, the address of ri and i are the same and the values of each are the same. How the compiler handles this is another topic, but it really does boil down to my first sentence.


答:
More and more, pseudocode is written graphically with tools like UML. For instance, try out yUML.

an online tool for creating and publishing simple UML diagrams. It's makes it really easy for you to:

Embed UML diagrams in blogs, emails and wikis.

Post UML diagrams in forums and blog comments.

Use directly within your web based bug tracking tool.

Copy and paste UML diagrams into MS Word documents and Powerpoint presentations...

...yUML saves you time. It's designed to for those that like to create small UML diagrams and sketches.

Without yUML, creating a UML diagram might involve loading up a UML tool, creating a diagram, giving it a name, fiddling with layout, exporting it to bitmap, and then uploading it online somewhere. yUML doesn't make you do any of that...

Title: Should one use pseudocode before actual coding?

Body:
Pseudocode helps us understand tasks in a language-agnostic manner. Is it best practice or suggested approach to have pseudocode creation as part of the development lifecycle? For instance:

Identify and split the coding tasks

Write pseudocode

Get it approved [by PL or TL]

Start Coding based on Pseudocode

Is this a suggested approach? Is it practiced in the industry?


问:
Should I learn a programming language before I attend college for Computer Engineering?
I've dipped my toes in C++ programming but I haven't actually delved into it.  I want to know if I actually need to learn it or any other languages before I go to college for Computer Engineering or am I just going to learn it at school anyway?</p>

答:
Yes.

Which one you should learn depends on what "Computer Engineering" means. It's a pretty non-standard term. Where I studied, it was a combination of electronics and computer science.

If you expect to be primarily working with computer hardware, I would suggest learning C and Forth. If you are primarily going to be doing what I would consider "computer science", I would suggest learning something like Python or Smalltalk in order to try out "real work", and a functional programming language of your choice (I would suggest some variant of lisp or scheme, but choose what's easiest and coolest).


问:
Why do certain sites prevent spaces in passwords?
It seems less common with newer websites, but many websites I need an account on (like for paying bills, etc.) prevent me from creating a password with spaces in it.  This only makes things more difficult to remember, and I am aware of no database or programming restrictions on spaces in passwords, encrypted or (heaven forbid) otherwise.  Why, then, is the spacebar so commonly discriminated against when it comes to signing up for a site?</p>

答:
IMHO, It is outright foolish of any site/app that uses modern hashing and/or salting to store passwords to not allow for spaces in passwords. But, some legacy systems(read about this somewhere) still pass around passwords in plaintext - so not allowing spaces there may make sense. Also, some apps may "strip" all string inputs they receive. So, a password starting or ending with a space is not going to be good(of course, that was over contrived, but you can imagine what not can happen with almost anybody coming up with his own site). There is nothing "bad" in allowing spaces in passwords - as you point out, the DBs won't disallow the hashes or the plaintext versions.

Actually most of my Windows friends don't know that they can use spaces in their passwords - So, maybe, as per Tim Medora's answer, site owners don't want to take chances with lamahs(pardon that) or maybe some of them have misconceptions and/or are ignorant of the advantages spaces can provide.

OwnerDisplayName: beanland