答:
I'd start by recommending to ignore Flash, except if you only aim at targeting mostly the Windows landscape.

Now between Java and HTML5, I think there's some clarification needed.

I wouldn't implement your game as an Applet, except for a few exceptions. Applets were a good idea at the time to provide more dynamic content embedded in a page when there weren't many other alternatives, and to get more processing software on the client side than with the JavaScript engines of the time. However they were still too slow to feel like a real application, especially to start up (not really an issue anymore), and still present some issues: communicating with other parts of the page is tricky, they're sandboxed and require permissions (and to be signed) if you manipulate resources, and many other issues (overlapping elements, start and close events, managing multiple applets on a page...).

Applets would still allow you to implement relatively simple games or applications, but bear in mind that if you plan to expand later, they're probably not the right fit if you want more than a simple piece of dynamic content embedded in a page.
I'd rather recommend you togo for a fully fledged WebStart or JavaFX directly, if you need power, and you can still embed them.

If your game is relatively lightweight on the client (though it's getting quite powerful now), then go for HTML5. It's the upcoming standard, it should have the widest reach in terms of supported platforms, and good modern browsers will still give you enough powers. Others will pick-up.

There are a few other things to consider though. But for your first-draft / quick-prototype, just don't over-think it and go for an HTML5 client.

Title: Why should I choose Java, Flash, or HTML5 for an online game with server communication

Body:
I'm starting to design a game that is going to have the following characteristics, and I'm trying to decide how I should program it. I'll also give a bit of my experience after, to help make the decision a bit better.

The game should be able to support both Facebook integration, and a stand alone version.

I don't want to do it right away, but I am thinking it would be a good idea to port this to Android/ iPhone at some point in time.

The game will involve communication with a server. The method of communication is still opened, but I imagine most of it will be over HTTPS. I'm suspecting most of the work is going to be done on the server at this point in time, and that the client is mainly going to show the results of the previous frame, and select what to do for the next frame.

I suspect that at some point in time, I'm going to want to put in animations and the like, but this is not critical for the beginning of the game.

The game is essentially an online board game, complete with cards, a board, etc.

I'm currently looking at Flash, HTML 5, and a Java applet. Some random pieces of information.

I have access to Adobe Flash, actually the whole Design Premium, CS5.

I have some experience with programming Android apps.

I have done work with HTML, but it has been quite a while. I've only done a little bit of Javascript, but I don't recall it being particularly hard.

I routinely program in C, C++, Matlab, and Android (Java). I fairly often program in Python, Perl, Shell, and I have programmed before in Basic, HTML, Javascript.


问:
How can I move a team from C# ASP.NET development to PHP development using Drupal?
I have a team of skilled C# developers with vast experience in creating ASP.NET MVC applications. We will soon be starting a new big web site project based on the Drupal platform. My developers do not have any experience in Drupal or PHP and I want to make the transition as quickly and effective as possible.

We decided to make this decision based on two factors:

In my organization there are a couple of teams competing on doing this project. None of the other teams has experience in PHP or Drupal, and I truly believe that my team would do it the best, whether it's ASP.NET or Drupal.

One of the requirements from higher management was that we won't build something from scratch, but use an existing foundation. Many of the requirements are available in plugins/modules for the various CMS.

I know this is not an ideal environment, but it's a given state and I have to make the best out of it. None of the .NET Framework based CMS supported all of our requirements. Since my team is dynamic in nature, I believe it can adapt to working with Drupal.

Hiring other people is not an option, and sending them to a course will take too much time.
I thought about dedicating a week in which each developer will study a specific subject and then will pass it on to the team.

Any suggestions on how you would do it?

答:
I would not want to be a developer on this team/on this project, it has the makings of a disaster (seriously).  This sounds like a typical management question.  So, you're changing your developers skillset, you don't want to get them any training and you also don't want to hire an architect with experience.

You will have growing pains in this project.

You will end up with code (hopefully) that will have to be retooled later after they figure out the "gotchas" that will come up.

In my opinion, someone on the project has to have enough knowledge of the language to see the big picture.  Having each developer try learn one subset without knowing how they all fit together is going to get you in trouble eventually.  Someone needs to have an understanding of how everything integrates and that isn't going to come in a week.

Best of luck. :p

ContentLicense: CC BY-SA 3.0


问:
Does Object Oriented Programming Really Model The Real World?
I've seen it commonly repeated the object-oriented programming is based on modeling the real world but is it?

It seems to me that is not true of anything outside of the business layer. My GUI classes/data access classes aren't modeling anything in the real world. Even in my business layer, I've got classes like observers, managers, factories, etc. which aren't real world objects. I try to design my classes to take advantage of things like encapsulation but is the real world encapsulated?

While some objects I create are modeling real-world objects, would not pre-OOP code do the same? I doubt that OO was the first people to include concepts like Customer in their code bases. But OO is really about how to model things, and that method of modeling doesn't seem inspired by the real world to me.

So: does object-oriented programming really model the real world?

答:
I think "Does" is the important part of this question. I think Object Oriented programming certainly Can model real world "objects", but this is programming. There is no methodology that can't be abused, so I don't think it's fair to say "OOP doesn't model the real world" just because you can do stupid things with Objects. That's no fairer than to say that Pointers aren't safe because you can do stupid things with pointers.

Wikipedia's article on the matter sums it up well:

Real-world modeling and relationships

  OOP can be used to associate real-world objects and processes with digital counterparts. However, not everyone agrees that OOP facilitates direct real-world mapping (see Negative Criticism section) or that real-world mapping is even a worthy goal; Bertrand Meyer argues in Object-Oriented Software Construction[21] that a program is not a model of the world but a model of some part of the world; "Reality is a cousin twice removed".

The thing is unless your program is a universe simulation, you only care about parts of the real world--hence "model". That's what models are for, they give you the structure and the functionality that you need to display.

In the real world we have things (Objects) and things can perform actions (methods). We can quantify aspects of things (Properties). OOP has every potential to model real world things when used in a reductionist way; every complex thing has smaller or more specific sub classes and all of these things have natural interactions via methods.

OOP is a method of abstraction, so the practical thing is whether OOP really logically models objects in the Real World, it's less important that you're not modeling every single possible thing everything could ever do. If you need to do every single possible thing, you're not really modeling.

ContentLicense: CC BY-SA 4.0


问:
Is Visual Source Safe (The latest Version) really that bad? Why? What's the Best Alternative? Why?
Over the years I've constantly heard horror stories, had people say "Real Programmers Dont Use VSS", and so on. BUT, then in the workplace I've worked at two companies, one, a very well known public facing high traffic website, and another high end Financial Services "Web-Based" hosted solution catering to some very large, very well known companies, which is where I currently Reside and everything's working just fine (KNOCK KNOCK!!).

I'm constantly interfacing with EXTREMELY Old technology with some of these financial institutions.. OLD LIKE YOU WOULDN'T BELIEVE.. which leads me to the conclusion that if it works "LEAVE IT", and that maybe there's some value in old technology? at least enough value to overrule a rewrite!? right??

Is there something fundamentally flawed with the underlying technology that VSS uses? I have a feeling that if i said "someone said VSS Sucks" they would beg to differ, most likely give me this look like i dont know -ish, and I'd never gain back their respect and my credibility (well, that'll be hard to blow.. lol), BUT, give me an argument that I can take to someone whose been coding for 30 years, that builds Platforms that leverage current technology (.NET 3.5 / SQL 2008 R2 ), write's their own ORM with scaffolding and is able to provide a quality platform that supports thousands of concurrent users on a multi-tenant hosted solution, and does not agree with any benefits from having Source Control Integrated, and yet uses the Infamous Visual Source Safe.

I have extensive experience with TFS up to 2010, and honestly I think it's great when a team (beyond developers) can embrace it. I've worked side by side with someone whose a die hard SVN'r and from a purist standpoint, I see the beauty in it (I need a bit more, out of my SS, but it surely suffices). So, why are such smarties not running away from Visual Source Safe? surely if it was so bad, it would've have been realized by now, and I would not be sitting here with this simple old, Check In, Check Out, Version Resistant, Label Intensive system. But here I am...

I would love to drop an argument that would be the end all argument, but if it's a matter of opinion and personal experience, there seems to be too much leeway for keeping VSS.

UPDATE: I guess the best case is to have the VSS supporters check other people's experiences and draw from that until we (please no) experience the breaking factor ourselves. Until then, i wont be engaging in a discussion to migrate off of VSS..

UPDATE 11-2012: So i was able to convince everyone at my work place that since MS is sun downing Visual Source Safe it might be time to migrate over to TFS. I was able to convince them and have recently upgraded our team to Visual Studio 2012 and TFS 2012. The migration was fairly painless, had to run analyze.exe which found a bunch of errors (not sure they'll ever affect the project) and then manually run the VSSConverter.exe. Again, painless, except it took 16 hours to migrate 5 years worth of everything.. and now we're on TFS.. much more integrated.. much more cooler.. so all in all, VSS served it's purpose for years without hick-up. There were no horror stories and Visual Source Save as source control worked just fine. so to all the nay sayers (me included). there's nothing wrong with using VSS. i wouldnt start a new project with it, and i would definitely consider migrating to TFS. (it's really not super difficult and a new "wizard" type converter is due out any day now so migrating should be painless). But from my experience, it worked just fine and got the job done.

答:
Often it's a matter of priorities and costs. Changing a source control system for a large team of developers can distract from higher priority projects and, even if the software is free, cost in terms of developer time. I've been through 2 VSS to TFS and one VSS to SVN transitions and it wasn't quite as smooth as was hoped. Your manager doesn't want to tell a VP that his very important project was delayed because of some crazy team internal project.

It's kind of a "if it ain't broke, don't fix it" mentality. You see this in other areas as well such as the slow transition away from Windows XP in corporate IT departments. Basically, for the change to take place, you have to give logic reasons why the cost and limitations of keeping the old way is greater than moving to something new.


问:
if it's been designed correctly is AOP useful?

Possible Duplicate:

  Are certain problems solved more elegantly with AOP?

I don't know much about aspect oriented programming (AOP) but I looked at a few examples and it seems to me more of a debugging tool or patching things. I looked over the examples and I can't think of anywhere I'd use them in -my- code.

Assuming the code has been design right and the language supports it (such as AspectJ) what are real world uses where using AOP is good design and can't be done as easily with traditional well designed classes/code/software?

答:
I bet you are using AOP in your code (or have in the past) and you didn't even know it.  MVC web frameworks often have filters that are used in a very AOP-like way, and even something like an HttpModule in ASP.NET I would call AOP (I'm not sure what the analog is in the Java world).

Debugging, logging, tracing, are certainly the "killer apps" of AOP, but any time where you have boilerplate or repetitive code that you can't otherwise refactor using normal OO techniques is a great place to consider AOP.

It's not a silver bullet, but it's a great tool to have in your SOLID toolbox.


答: OO code doesn't usually model the real world--at least that's not the goal, it simply allows you to think about your code in a manner that is more natural, more like the way you think about things in the real world--this is what the quote is trying to say.</p>

Title: Does Object Oriented Programming Really Model The Real World?

Body:
I've seen it commonly repeated the object-oriented programming is based on modeling the real world but is it?

It seems to me that is not true of anything outside of the business layer. My GUI classes/data access classes aren't modeling anything in the real world. Even in my business layer, I've got classes like observers, managers, factories, etc. which aren't real world objects. I try to design my classes to take advantage of things like encapsulation but is the real world encapsulated?

While some objects I create are modeling real-world objects, would not pre-OOP code do the same? I doubt that OO was the first people to include concepts like Customer in their code bases. But OO is really about how to model things, and that method of modeling doesn't seem inspired by the real world to me.

So: does object-oriented programming really model the real world?


问:
Does the $100 Google Apps Marketplace Fee Apply To All My Developers or Just Me?
On the Google Apps Marketplace Vendor Listing page, Google says the following:

Google charges a one-time fee of $100 for submitting your first listing.

I've searched Google Groups and other forums, and I cannot seem to find the answer to the question of whether or not the one time $100 fee applies to only my individual Google Apps login or if it applies to other Google Apps logins on my domain as well.

For instance, If I, james@mydomain.com, pay the $100 fee so I can submit N listings, does this also apply to john@mydomain.com or does John have to pay the $100 fee to so he can publish his apps without having to ask me to do it?

Is it best to use a single, group login like admin@mydomain.com or development@mydomain.com when paying the $100 Listing fee?  What is your experience in this regard with posting multiple listings to the marketplace where N developers are involved?

答:
Going through the website it seems really unclear.  I would assume that it is per email address (think, if you did yours at x@gmail.com, does that mean every one from gmail should get it free).

I would just say make one email for publishing, for example support@domain.com, and everyone can custom make their own applications on a separate email, but when going to post it to the Google Market, be forced to post under one email.

UPDATE: A Google Groups posting confirms that the Marketplace Vendor fee covers one account only.

One possible issue is that the vendor logo is the same for all apps published under that account.

Thus, if all apps are going to be published using the same brand logos, use the support@domain.com account and pay the $100 fee once. But if the apps are going to be released using different brand logos, then separate Vendor accounts must be created.

For instance, brandA@mydomain.com and brandB@mydomain.com would be 2 separate accounts on the same Google Apps domain but could have different brands associated with them. Thus, if you require different Vendor logos for your apps, you'll need to setup separate accounts and pay separate fees. Again, separate accounts doesn't mean separate Google Apps domains, just separate accounts under that Google Apps domain. The logos you use for the vendor accounts do not need to be the same logo you use for Google Apps logo.


答:
After taking a look at the steps to become a Vendor for the Apps Marketplace, it looks like the form is setting you up to be a company and not an individual developer by default. So that one time $100 fee covers you and your company of x number developers, to post apps under your "Company Name" that will be used in the Apps Marketplace.

EDIT:
However, all x developers must login to the same Google Apps account, like marketplace@yourdomain.com and not bob@yourdomain.com, bill@yourdomain.com, etc.

Title: Does the $100 Google Apps Marketplace Fee Apply To All My Developers or Just Me?

Body:
On the Google Apps Marketplace Vendor Listing page, Google says the following:

Google charges a one-time fee of $100 for submitting your first listing.

I've searched Google Groups and other forums, and I cannot seem to find the answer to the question of whether or not the one time $100 fee applies to only my individual Google Apps login or if it applies to other Google Apps logins on my domain as well.

For instance, If I, james@mydomain.com, pay the $100 fee so I can submit N listings, does this also apply to john@mydomain.com or does John have to pay the $100 fee to so he can publish his apps without having to ask me to do it?

Is it best to use a single, group login like admin@mydomain.com or development@mydomain.com when paying the $100 Listing fee?  What is your experience in this regard with posting multiple listings to the marketplace where N developers are involved?


问:
About shared (static) Members and its behavior
I just realized that I can access shared members from instances of classes (probably this is not correct, but compile and run), and also learn/discover that, I can modify shared members, then create a new instance and access the new value of the shared member.

My question is, what happens to the shared members, when it comes back to the "default" value (class declaration), how dangerous is it do this ? is it totally bad ? is it valid in some cases ?.

If you want to test my point here is the code (console project vb.net) that I used to test shared members, as you can see/compile/run, the shared member "x" of the class "Hello" has default value string "Default", but at runtime it changes it, and after creating a new object of that class, this object has the new value of the shared member.

```<code>Module Module1
    Public Class hello

        Public Shared x As String = "Default"

        Public Sub New()

        End Sub
    End Class

    Sub Main()

         Console.WriteLine("hello.x=" & hello.x)
         Dim obj As New hello()

         Console.WriteLine("obj.x=" & obj.x)
         obj.x = "Default shared memeber, modified in object"
         Console.WriteLine("obj.x=" & obj.x)

         hello.x = "Defaul shared member, modified in class"
         Console.WriteLine("hello.x=" & hello.x)

         Dim obj2 As New hello()
         Console.WriteLine("obj2.x=" & obj2.x)

          Console.ReadLine()

     End Sub

End Module
</code>```

UPDATE: First at all, thanks to everyone, each answer give feedback, I suppose, by respect I should choose one as "the answer", I don't want to be offensive to anyone, so please don't take it so bad if I didn't choose you answer.

答:
what happens to the shared members, when it comes back to the "default" value (class declaration), how dangerous is it do this ?

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.

It is more typical to declare a non-static class with some static members, than to declare an entire class as static.

Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.

Quoted from MSDN-Static Classes and Static Class Members.

is it totally bad ? is it valid in some cases ?.

No it is not bad, just be careful and use it when it is appropriate. It all depends on what you want to do.


答: In several programming languages with classes that support "static members", each single class is managed internally as if it were a namespace, and its "static members" as global variables. This happens without the class being instantiated.</p>

Title: About shared (static) Members and its behavior

Body:
I just realized that I can access shared members from instances of classes (probably this is not correct, but compile and run), and also learn/discover that, I can modify shared members, then create a new instance and access the new value of the shared member.

My question is, what happens to the shared members, when it comes back to the "default" value (class declaration), how dangerous is it do this ? is it totally bad ? is it valid in some cases ?.

If you want to test my point here is the code (console project vb.net) that I used to test shared members, as you can see/compile/run, the shared member "x" of the class "Hello" has default value string "Default", but at runtime it changes it, and after creating a new object of that class, this object has the new value of the shared member.

```<code>Module Module1
    Public Class hello

        Public Shared x As String = "Default"

        Public Sub New()

        End Sub
    End Class

    Sub Main()

         Console.WriteLine("hello.x=" & hello.x)
         Dim obj As New hello()

         Console.WriteLine("obj.x=" & obj.x)
         obj.x = "Default shared memeber, modified in object"
         Console.WriteLine("obj.x=" & obj.x)

         hello.x = "Defaul shared member, modified in class"
         Console.WriteLine("hello.x=" & hello.x)

         Dim obj2 As New hello()
         Console.WriteLine("obj2.x=" & obj2.x)

          Console.ReadLine()

     End Sub

End Module
</code>```

UPDATE: First at all, thanks to everyone, each answer give feedback, I suppose, by respect I should choose one as "the answer", I don't want to be offensive to anyone, so please don't take it so bad if I didn't choose you answer.


问:
Functional Programming For Embedded Software
I was discussing F# and Functional Programming with a friend last night and he brought up an interesting question to me.  How would you do embedded software in functional?  I mean this seems like a fairly natural fit in terms of stateless code but embedded also entails being very frugal with memory and I'm not sure of the story for functional in that regard.

Any suggestions about languages or packages for embedded with functional?

答: Forth is an excellent choice for embedded systems programming. Being a stack language, it can be analysed in terms of function composition (concatenative programming). I see no reason why such a language with more functional aspects could not also be implemented efficiently, but as yet no such thing (to  my knowledge) exists.</p>


答:
Shared (or static) members don't have an instance. They are not 'part' of an object. Think of shared members or functions as communal. If one piece of code updates a shared member, the next piece of code to access it will see the new value. Shared means 'shared memory'. It's important to understand whose memory it is. Shared memory is shared by all threads within the process space. So, you might be even more surprised if you spun up another thread and tried to access the shared memory space. Your child thread will update the memory of the main thread.

In some languages (e.g., C), you don't need to associate everything with a containing class or module. In other languages (e.g., VB) you provide a context for your member in the form of a class, but that's really only so you can a) find it, and b) hide it if you want to.

Private shared members will be visible only to members of a class, but they're still shared.  With shared functions, each caller gets a copy of any parameters passed to the function, but that's it. If the function uses any shared members, they are potential trouble spots for two reasons. First, later on in your code, you might forget who/what last updated the shared member so it could have an unexpected value. Second, if your program is multithreaded, you can create resource contention which are very difficult to diagnose.

Shared members and functions are absolutely valid in many cases. You should consider what you're trying to do, whether there might be write-contention for a given resource, and whether there are performance considerations (e.g., caching).  If you're a beginner programmer, I'd suggest you fully understand shared members/functions before you get into the habit of using them. A good place to use them is with functions that don't have side-effects (i.e., that don't change program state by setting other members). Then you might use them for things like caches (if you really need that) among other things.  Just don't abuse them.


问:
How do I speed up XML parsing operation?
I currently have a php script set up to do some xml parsing. Sometimes the script is set as an on page include and other times it is accessed via an ajax call. The problem is the load time for this particular page is very long. I started to think that the php I had written to find what I need in the XML was written poorly and my script is very resource intense. After much research and testing the problem is indeed not my scripting (well perhaps you could consider it a problem with my scripting), but it looks like it takes a long time to load the particular xml sources.

My code is like such:

```<code>$source_recent = 'my xml feed';
$source_additional = 'the other feed I need';

$xmlstr_recent = file_get_contents($source_recent);
$feed_recent = new SimpleXMLElement($xmlstr_recent);

$xmlstr_additional = file_get_contents($source_additional);
$feed_additional = new SimpleXMLElement($xmlstr_additional);
</code>```

In all my testing, the above code is what takes the time, not the additional processing I do below.

Is there anyway around this or am I at the mercy of the load time of the xml URL's?

One crazy thought I had to get around it is to load the xml contents into a db every so often, then just query the db for what I need.

Thoughts? Ideas?

答:
Is the problem that it takes a long time to parse the XML, or is the problem that your code sits around waiting for e.g. HTTP requests to return?

It is possible to create nonblocking sockets in PHP, though things might get a tad complicated.

If you have expat installed, you can also set up event handlers to react to elements as they are parsed, which complements an asynchronous read very nicely.

Perhaps you can delegate this task to another process/service developed in a language that supports asynchronous operations. It won't guarantee a speedup (you still have to wait for both HTTP requests to return), but at least you can start working on data as they come in rather than wait until you've received all the data before starting to process.

Note that this is distinct from the second half of tdammers's answer.  This answer focuses on keeping the retrieval and processing of the XML at "request time" (necessary when the data in the XML files change frequently and/or the data has to be "real time"), whereas tdammers's answer focuses on keeping the data in a cache (offers much better performance when the data don't change that often and/or if "stale" data are acceptable).


答:
In order to think about object-orientation in its proper context, let's move up one level of abstraction and talk about programming in general, ok?

Regardless of whether you take OO or functional approaches, your program has to do something, doesn't it?  The whole point of the program is to exhibit certain behaviors given a certain set of stimuli.  So the reasons that programs exist at all is because they do something.  The key word here is behavior.

In addition to considering what behaviors a program must implement, your program generally needs to exhibit certain qualities.  For example, it is not enough for a heart-monitor program to have the behaviors required of it -- it usually also needs to performant quickly enough to operate in near-real time.  Other "qualities" that a program may need to exhibit are: security, flexibility, modularity, extensibility, readability, and so on.  We call these Architecture Quality Attributes.  So we can say that our program needs to meet certain behavioral (functional) goals as well as exhibit certain qualities (non-functional).

So far, none of this has talked about OO, has it?  Let's do that now.

Once an engineer understands the requirements (behavioral, AQAs, constraints, etc), the question arises: how shall I organize my code so that it does all the things it needs to do while also exhibiting the qualities necessary to be a useful program?  Object-oriented programming is a strategy for organizing your program's functionality into cohesive modules of co-operating objects.  Functional programming is just another strategy for organizing your program's functionality, and it does so in a different way.  Both strategies have their strengths and weaknesses.

We have been witnessing a recent resurgence in functional concepts because it has strengths that are very compelling for hugely distributed processing, among other reasons.

But moving back to OO, you can see now that it does not necessarily model the "real-world"; what it does is organize the behavior of your program so that your program can exhibit the qualities needed to meet any number of business objectives.  Techniques such as TDD, DDD, and BDD are the ways in which we discover how best to organize our objects.  Books such as Principles, Patterns, and Practices, Growing Object-Oriented Software Guided by Tests, Specification by Example, and Domain-Driven Design lay out the theory and practice of object-orientation with a focus on behavior-driven design.

When you read about things like "observers, managers, factories, etc", you're applying OO patterns that help your program exhibit certain qualities that may be necessary for it to be useful.  They are "proven recipies" that "tend to work", given that your needs match the problem that the pattern solves.

I hope that helps you understand what OO is about without appearing too biased between OO and functional paradigms.


问:
How can I feel more confident about my programming skills?
Programming isn't alien to me. I first starting doing markup (HTML, now please don't laugh at me) when I was 12 and a little bit of BASIC when I was 13 (I knew much about Flowcharts, Pseudocodes at this point), but then I was admonished into Biology in high school and hence missed out on "real" programming knowledge of languages such as C, Java, etcetera. I took up CS for my UG B.E. (similar to BS, but way more theoretical). I learnt C & C++ (to a lesser extent) on my own (my prof was a total pain and the class was filled with code-jocks (who had already learnt it in school, and hence paid no attention to class and didn't let lesser mortals like me to pay any attention to class either)) and could whip up an awesome addition or multiplication program (ones which now even kinder-gardeners' whip up with way more finesse) and a piss-poor knowledge of Java (which has even grown rusty in recent times).

My main problem is that I've always felt inadequate and strangled by my limited programming skills and belittled by the code-jocks (believe me, I've come across this site ages ago, but could just now build up the courage to actually post a question) and have been at times even depressed over said inability. Most people say that Programming isn't necessarily about the language but the state of mind that the person has and the techniques they employ to solve problems/issues. I agree with such sentiments, but can I ever acquire such a "state of mind", and if such how should I approach "Programming/Coding", and if there are any set ways and steps one most go through to attain the "Zen of Coding". How do I do so? Also, it wouldn't hurt if some Saint wanted to mentor this downtrodden piece of $#!^.

P.S. I would forever be grateful to any person who considers me worth their time, and as a bonus would name my first piece of Software I ship after them. (If I ever get to ship one, i.e.,)

TL;DR: Never really learnt "Programming/Coding", can't solve problems even if I try to. Help me!

答:
Ask yourself why you actually feel lack of confidence. I think it's because you care what your peers think, and that's completely understandable. But to be truly zen about it, you need to clear such thoughts and only compare yourself to yourself over time. Be guided by your interest, learn and work hard, and you'll become a good programmer without all the psych BS.

It's not really confidence you need, it's less noise in your path of progress.

OwnerDisplayName: Ameen


问:
Question about state and domain objects
Suppose I create a domain object called UserAdministration, if i have a method called CreateUser how would i pass state to this method, would I create properties on the UserAdministration object and have a CreateUser method or would i pass all the info for CreateUser method in a poco?

Also how do I identify my domain objects?

答:
How would i pass state to this method

There are several ways, here are 3 of them:

1-Pass the values as parameters to public constuctor

2-Pass the values to a public method

3-Create public properties in the class, create an instance, then set each property and call the method without passing parameters

How do I identify my domain objects?

A domain object represents a persistent data store in your solution. If you application is about CRM, then you are bound to deal with domain objects such as parties (customers, companies, etc.), ContactAddress, TouchPoint, etc. All such objects should appear in your UML Class Diagram. A detailed discussion of this could be found in UML, OOA and Domain Driven Design books.

Title: Question about state and domain objects


答: Do you know what is actually taking the most time?  Is it disk I/O reading the file, is it memory allocation, is it creating the DOM tree?  Sometimes it's faster to do stream parsing rather than reading the whole file into memory and building a DOM tree, especially if the data you want is near the beginning of the file.</p>

Title: How do I speed up XML parsing operation?

Body:
I currently have a php script set up to do some xml parsing. Sometimes the script is set as an on page include and other times it is accessed via an ajax call. The problem is the load time for this particular page is very long. I started to think that the php I had written to find what I need in the XML was written poorly and my script is very resource intense. After much research and testing the problem is indeed not my scripting (well perhaps you could consider it a problem with my scripting), but it looks like it takes a long time to load the particular xml sources.

My code is like such:

```<code>$source_recent = 'my xml feed';
$source_additional = 'the other feed I need';

$xmlstr_recent = file_get_contents($source_recent);
$feed_recent = new SimpleXMLElement($xmlstr_recent);

$xmlstr_additional = file_get_contents($source_additional);
$feed_additional = new SimpleXMLElement($xmlstr_additional);
</code>```

In all my testing, the above code is what takes the time, not the additional processing I do below.

Is there anyway around this or am I at the mercy of the load time of the xml URL's?

One crazy thought I had to get around it is to load the xml contents into a db every so often, then just query the db for what I need.

Thoughts? Ideas?


问:
What would be the best way to learn about compilers, and executable formats?
I want to write my own compiler for my own language. Yes, it's going to be hard, and it will take long, but I think it will be worth it.

I have looked into OSDev.org, and read about executable formats there, but they aren't much help. I am looking for information beyond what they have there.

So, anything will help. Books, websites, PDFs, anything.

I am looking into 32-bit, not 64- or 16-bit.

答:
I would think the best place to start in practical terms would be a solid foundation in using lex and yacc (or flex and bison), since these are likely the tools you'll use to actually build the compiler. There's a tutorial here, and O'Reilly has a great book about them.

From a theoretical standpoint, you'll want to study compiler design. Google turns up plenty of quality resources, but the the classic book on the subject is Compilers: principles, techniques, and tools by Alfred V. Aho. I can't recommend it highly enough.


问:
What to do with bugs that do not repro?
I have a tester that while testing will have an error occur (ok so far), but then he frequently reports it right away.  We (the developers) then later find that the tester has not tried to reproduce the issue and (when asked) cannot find a way to make it happen again.

Now these are still bugs, I don't want to ignore them.  But without repro steps I am kind of stuck.  Sometimes there is a stack trace (though frequently it is not useful because this is compact framework and there are no line numbers).  But when there is one I can take the stack trace and crack open the code and start guessing, but that does not lead to testable "fixes".

What do you do in scenarios like this?

答:
A bug without context is not a bug, it's a fluke. The problem could be your code, it could be a third party library, it could be the hardware, or it could be solar radiation causing a single bit to flip on it's own. If you can't reproduce it with at least some regularity (even if only "it happens once every 10 or 20 times I do X"), it's not much better than your tester telling you "Something somewhere went wrong somehow - fix it".

You may have to explain to your tester that his job is not to just generate input until something breaks. If it were, you could replace him with a random number generator. Part of his job is to identify bugs, which entails identifying how to produce them.

ContentLicense: CC BY-SA 2.5

Title: What to do with bugs that do not repro?


问:
What's new in PL/I, DB2, and S/390 assembler?
I have an upcoming technical interview with a former employer that will focus on PL/I, DB2, and ISPF.  The job will be with systems that I architected and wrote myself 20 years ago. The few years of professional programming that I did since then was all assembly language.  The problem is that I haven't programmed professionally in 15 years, and the personal programming that I've done since then has been in other "modern" languages.  My question is whether there are new features in PL/I and DB2 that I should be aware of.  (When browsing through the latest "Principles of Operation" I saw machine instructions to support C style strings that weren't there in ancient times - cool.)</p>

答:
One nice change with DB2 is that the z/OS and LUW (Linux/UNIX/Windows) code is coming closer and closer together as far as functionality is concerned. Since V8, DB2 now stores everything internal in its system tables as Unicode, translating to the specified ZPARM CCSIDs as needed. It's also a lot more flexible with different CCSIDs and Unicode in character data.

ISPF has great support for files stored in the USS file system - for example, in the "other data set" field, you can put path names. If you have a directory, you will get a file list similar to the standard PDS member listing.

One thing you may remember from that long ago was the rather dismal opinion of Language Environment (LE). It took several years, but LE is now a stable run-time, and it makes combining languages like PL/I and C much easier in an environment. COBOL and Assembler still have a few quirks in this area, but they're easy to handle.

From the assembler side of things, pick up the latest POP and look at all the neat new instructions. Depending on the hardware at the shop, though, some of the really neat new ones may not be available, such as the compare-and-branch instructions (introduced with the current z196/z114). All machines are 64-bit now, and C/C++ can generate code for AMODE 64.

If you dabbled on the system side in assembler, C has a METAL feature designed for use in places where you could only use assembler in the past; the METAL code does not use LE and has a limited number of standard C library routines.


答:
While some objects I create are modelling real world objects, would not pre-OOP code do the same?

The greatest difference between OOP and pre-OOP code is that the former models a real world situation as a group of distinct entities interacting with each other, each with limited "power" regarding what it can do, and also capable of "reacting" to external events with actions of its own. The latter models everything as a big chunk of data that doesn't do anything on its own, while the computation represents "things that happen" and can affect any or all of them.

Whether it better models the real world or not, that really depends on which facets of the world you're modelling. A physics simulation, for example, where you want to describe the effects that, say, a fire being lit would have in the surrouding objects, would be better represented by a "traditional" approach, since both the light and the heat are well-defined processes that affect both external and internal state of other objects, and do not vary according to the behavior of each particular object, only being affected by their properties.

On the other hand, if you're modelling different components that interact to produce the desired behavior, treating them as agents instead of passive things can make it easier to do it correctly without missing anything. If I wanna turn on my TV, I just press the button, if the power cord is unplugged the TV.turnOn will check that for me. So, there's no risk of turning a cog and forgetting to turn that other that's touching it, since the cog itself (if programmed correctly) will take care of the secondary interactions that come as a consequence of the primary one.

But OO is really about how to model things, and that method of modelling doesn't seem inspired by the real world to me.

I believe it has more to do with the way we perceive the world than how the world actually is. One could argue that everything is just a bunch of atoms (or energy, or waves, whatever), but that doesn't help us handle the task of dealing with the problems we face, with understanding the environment around us and predicting future events (or describing past ones). So we make "mental models" of the world, and often those mental models find a better correspondence with OO than the data+processes one - which arguably models "better" how the real world actually operates.

It's also interesting to note that most people think of OOP as synonym with "classic OOP", where we taxonomically create sets and subsets of things, and unambiguously put objects in a very specific set. That's very useful for creating reusable new types, but not so great when the entity you're modelling is pretty much self-contained, and while it initiates interactions with other objects it rarely, if ever, is the target of an interaction. Or worse, when there are few (maybe only one) instance of that entiy, or the instances vary wildly in composition, behavior or both.

However, there's also "prototypical OOP", where an object is described by picking a similar one and enumerating the aspects where they differ. I'd suggest this essay for a good and not-too-technical explanation of the thought process (the whole post is too big, even for Steve Yegge's standards, so I'm pointing to the relevant section :P). Again, this is a good match for our mental models when imagining unknown instances by comparison to a known one, but not necessarily for how the real world "works"... (two cows are actually completely distict entities, even if we perceive them as being "alike" in many ways)


问:
Would the concept of source code layers be of any use?
I'm talking about something like layers in photoshop, except they apply directly to the source code.  For example, in pseudo-code... inventing what some project might look like - say a computational fluid dynamics program:

[base layer]

```<code>cfdTime runTime(0);

fieldVariable U;
fieldVariable p;
U.initialize();
p.initialize();

while (runTime.run())
{
    U.solve();
    p.solve()
    runTime++;
}
</code>```

[turbulence layer]

```<code>turbulenceModel turbulence;
scalar nu(readScalar(turbulence.dictionary("nu"));

while (runTime.run())
{
    turbulence.update();
}
</code>```

[base layer + turbulence layer]

```<code>cfdTime runTime(0);

fieldVariable U;
fieldVariable p;
U.initialize();
p.initialize();

turbulenceModel turbulence;
scalar nu(readScalar(turbulence.dictionary("nu"));

while (runTime.run())
{
    U.solve();
    p.solve()
    turbulence.update();
    runTime++;
}
</code>```

You get the idea.  Obviously a lot of things would need to be worked out.

I'm all over object-oriented programming (OOP).  This idea strikes me as an awkward alternative to OOP... and I don't think it's worth much... but I thought I'd toss it to the community... there just might be something useful in it that I'm not quite seeing.

It may be useful from a GUI-only perspective - creating layers in the GUI for complex functional programming... while the underlying code is always the same.  Or it may be useful for code optimisation, perhaps an alternative to #ifdef that developers won't run screaming from.  Or, it may be an entire alternative to OOP.

Your thoughts?

答:
What you are referring to strikes me as being just Aspect Oriented Progamming, which is:

[...] a programming paradigm which aims to increase modularity by
  allowing the separation of cross-cutting concerns

Or even by extension Aspect Oriented Software Development, which is:

[...] an emerging software development technology that seeks new
  modularizations of software systems in order to isolate secondary or
  supporting functions from the main program's business logic[, allowing]
  multiple concerns to be expressed separately and automatically
  unified into working systems.

While this idea doesn't translate to layers if you consider its implementation, the conceptual representation of the cross-cutting concerns could fit this analogy.

For more information, you may want to read Ian Sommerville's Software Engineering textbook, which covers AOP in detail in chapter 21 [slides], or read some introductory articles like:

A Look at AOP

A herd of academic papers published since it appeared in the mid 90s and was popularized by G. Kiczales' Xerox Labs paper in 1996.

It is interesting to note (to complement Asumu's answer) that some languages can support features like AOP from the ground-up, while these things may seem unnatural in other mainstream languages.

In the case of your example, what you're showing could be implement with AOP as long as your modularize the different entitites correctly, so as to have good join points.

OwnerDisplayName: Marupio


问:
How does key-based caching work?
I recently read an article on the 37Signals blog and I'm left wondering how it is that they get the cache key.

It's all well and good having a cache key that includes the object's timestamp (this means that when you update the object the cache will be invalidated); but how do you then use the cache key in a template without causing a DB hit for the very object that you are trying to fetch from the cache.

Specifically, how does this affect One to Many relations where you are rendering a Post's Comments for example.

Example in Django:

```<code>{% for comment in post.comments.all %}
   {% cache comment.pk comment.modified %}
     <p>{{ post.body }}</p>
   {% endcache %}
{% endfor %}
</code>```

Is caching in Rails different to just requests to memcached for example (I know that they convert your cache key to something different). Do they also cache the cache key?

答:
Your example is good if it needs some data retrieval or processing for each comment. If you just take body and display it - cache will be useless. But you can cache all comments tree (including {% for %}). It this case you need to invalidate it with every added comment, so you can put last comment timestamp or comments count somewhere into Post and build comments cache key with it. If you prefer more normalized data, and use comments on only one page, you can just clear a cache key on comment save.

For me, saving comments count in Post looks good enough (if you don't allow to delete and edit comments) - you have a value to show anywhere with the Post and a key for caching.

Title: How does key-based caching work?


答:
In general I recommend against the use of shared/static variables. Wherever possible use instance variables. There are rare exceptions in my view.

One of the cases where a shared/static variable may make sense is when you want to introduce constants, although some language support constants as a separate concepts. In VB.NET and C# (and possibly other .NET languages) please be aware that there is a difference between a constant and a read-only variable (declared as 'ReadOnly' in VB.NET or 'readonly' in C#).

A shared/static variable is in some sense a 'global' variable, although you can restrict access to it by using appropriate access modifiers. Global variables are considered to be bad practice and can be extremely difficult to debug, e.g. when there are a gazillion places where your code writes to or reads from that variable, and in particular if the content of the shared/static variable influences the logic of your code, e.g. when used in an if-statement.

From an object-oriented perspective you could argue that a shared/static variable is breaking encapsulation.

There are many other aspects and factors that you may need to consider. In general I advise my teams against them although there are reasonable exceptions where they make sense. In summary:

Yes, shared/static variable are dangerous

No, they are not bad as such

Yes, their use is a valid and appropriate approach in select cases


问:
What are the advantages to using SQL query builders?
Are there any advantages to using a query builder, rather than using raw SQL?

E.g.

```<code>$q->select('*')
  ->from('posts')
  ->innerJoin('terms', 'post_id')
  ->where(...)
</code>```

vs:

```<code>SELECT * FROM posts WHERE ...
</code>```

I see that many frameworks use these kind of abstraction layers, but I fail to understand the benefits.

答:
The abstraction of writing the SQL via a framework well, abstracts.

Writing SQL by hand is not all that bad by itself, but you start to get issues with escaping and sanitizing and this turns into a mess. An abstraction layer can take care of all of this behind the scenes allowing your code to be clean and free of lots of mysql_real_escape_string() calls or the like.

Additionally, this brings in the possibility of accounting for different dialects of SQL. Not all databases are built same and there may be variations in keywords or the syntax of a certain functionality. Using an abstraction layer brings in the ability to generate the correct syntax for your variant dynamically.

While an abstraction layer can introduce a performance hit, it is generally negligible compared to the cleanliness and robustness of code you receive in return.


问:
Is it advisable to force your web server to parse HTML files for PHP code?
I can't remember what site I glanced over and picked up that tidbit, but someone suggested that you should keep PHP parsing to .PHP files, and not modify one's webserver's htaccess to include PHP parsing within .HTML files.

Is this true? Is there any generally agreed upon reason as to doing it one way or the other?

答:
The way I see it, if you have choice, change the file extension to .php, but if you inherit a website and don't want all the addresses to change when you start putting in includes and what-not, then you can either parse php inside html files or use mod-rewrite to fake it. (Since you mentioned .htaccess, I am continuing the assumption of Apache.)

The only time I've run in to trouble with this is that I inherited a site that had XML tags in it, (I really don't know why) and php short tags were enabled, so it tried to parse the XML as PHP. What I did for that was used a search/replace tool to:

```<code>//change all the <?XML tags to
echo'<?XML';
</code>```

At the time I REALLY didn't know what I was doing. Now I might sometimes know what I'm doing. ;)

Body:
The way I see it, if you have choice, change the file extension to .php, but if you inherit a website and don't want all the addresses to change when you start putting in includes and what-not, then you can either parse php inside html files or use mod-rewrite to fake it. (Since you mentioned .htaccess, I am continuing the assumption of Apache.)

The only time I've run in to trouble with this is that I inherited a site that had XML tags in it, (I really don't know why) and php short tags were enabled, so it tried to parse the XML as PHP. What I did for that was used a search/replace tool to:

//change all the <?XML tags to
echo'<?XML';

At the time I REALLY didn't know what I was doing. Now I might sometimes know what I'm doing. ;)


答:
Quite often, some of the argument for these queries indeed is some values rather than constants. Now, many of them has essentially been derived from user form posts. And hence there are many possibilities for SQL injection attacks. So inherently query formation does require full validation.

Now, this is not to say that we don't trust developer, but formation of query might be easy, but repeating all possible validation checks everywhere might just implies that you might miss sometimes incidentally or modify query but don't modify query but don't update the validation check. Some newbie might even know all the dangers of missing out on this. Hence the query builder abstraction is quite essential.

Title: What are the advantages to using SQL query builders?

Body:
Are there any advantages to using a query builder, rather than using raw SQL?

E.g.

```<code>$q->select('*')
  ->from('posts')
  ->innerJoin('terms', 'post_id')
  ->where(...)
</code>```

vs:

```<code>SELECT * FROM posts WHERE ...
</code>```

I see that many frameworks use these kind of abstraction layers, but I fail to understand the benefits.


答:
Theoretically? Yes. Glenn Nelson pointed out how they will often help you. (If it is a good query builder).

In practice? Doesn't always live up to the theory and could actually cause problems. Suppose that you are using a query builder against some popular DBMS and everything is peachy. Then a customer asks you to hit their DBMS that has some quirks that your chosen query builder just can't handle. (I hit this problem when I had to work with an older version of Pervasive.)

BUT! What you should absolutely do is separate out the Data Access Layer and make sure you can swap in a new one if needed. That way you can you that cool query builder with all the features but if you need to plug in a new one that uses that odd pseudo-sql for the DB in question.


问:
How to ensure a single coding standard in .NET with tool support
Probably, the basic situation is familiar to everyone. You have agreed on certain coding standards in your team and now it is time to make sure that everybody follows them.

Some do it via heavy paired programming, others maintain a list of coding standards and do a manual review. Others even use the static code analysis tool from Visual Studio to make sure that coding standards are enforced.

What are your best practices to ensure coding standards? Which tools do you use - are there some essential tools every dev should know? How do you integrate the standardisation of your code in your development tools?

答:
StyleCop (now also StyleCop for Resharper) is commonly used to enforce coding style rules within C# code bases.

It can be integrated into your CI build and cause build failures if any violations have been introduced.

OwnerDisplayName: Stefan Papp

OwnerDisplayName: Oded


答:
StyleCop and FxCop are my light weight tools that remind code styles to my developers.
Resharper is also good one, but it makes VS very slow.

I recommend FxCop because of its' rich rules library, with great documentation, classifications, examples and many other features.

There's also StyleCop Fixer extension for visual studio available, helps to fix ordinary mistakes.

Code Metrics is also affected sometimes by code styles. You can monitor maintainability of codes with this tool.

Title: How to ensure a single coding standard in .NET with tool support

Body:
Probably, the basic situation is familiar to everyone. You have agreed on certain coding standards in your team and now it is time to make sure that everybody follows them.

Some do it via heavy paired programming, others maintain a list of coding standards and do a manual review. Others even use the static code analysis tool from Visual Studio to make sure that coding standards are enforced.

What are your best practices to ensure coding standards? Which tools do you use - are there some essential tools every dev should know? How do you integrate the standardisation of your code in your development tools?

OwnerDisplayName: Reza


答:
First, make sure you have a proper build server that continously builds your code. TFS or Jenkins/Hudson+Msbuild are good options. On this build server you of course run tests, and you can also run static code analysis as well as syntax checkers.

I recommend Using FxCop or Gendarme for static code analysis. Both can be used side by side.

One important key to success: don't deploy them with a massive ruleset and expect it to work well. You will have millions of warnings and noone will care.

Rules of thumb are:

Always have zero warnings. Reduce the set of checks initially if you have to, then add some new checks every sprint and fix those. Make sure every check performed has actual value to you and is consistent with your standards.

If you have domain specific rules you need to adhere to, don't be afraid to implement your own rules.

For syntax check, use StyleCop or StyleCop for Resharper if you are using Resharper (which I highly recommend as well).

OwnerDisplayName: Anders Forsgren


答: I would like to emphasise getting the automatic code analysis already mentioned (FxCop, StyleCopy, CI builds etc) working first, in preference to manual reviews. The automatic checks will pick up far more things than a manual review is likely to, and is normally much more rigorous, consistent and is self documenting. Manual reviews can be good for more high level design decisions etc, but in my experience they can be very subjective and haphazard. </p>

OwnerDisplayName: ShellShock


答:
parsing a .php file to html on server side is just overload to server I/O i think you wanted to ask about caching of web pages  (this will reduce network, CPU, RAM load on the server if you have huge number of web requests that your server can't handle)

please have a look on web chaching here

Title: Is it advisable to force your web server to parse HTML files for PHP code?

Body:
I can't remember what site I glanced over and picked up that tidbit, but someone suggested that you should keep PHP parsing to .PHP files, and not modify one's webserver's htaccess to include PHP parsing within .HTML files.

Is this true? Is there any generally agreed upon reason as to doing it one way or the other?


问:
How should I go about learning a very large and complex application?
Being a young and fairly inexperienced developer recently employed by a "real" software company I'd like some opinions and pointers on how to do the following:

Approaches on how to get familiar with a companies products , especially when you've no idea how it all works. The company I'm at now has one HUGE product , continually evolving and having been here for 2 weeks I've still no idea how it all sticks together apart from a special kind of glue made from the tears and frustration of young developers, it's incredibly fragmented and only 4 people in the office know the inner workings, all of them constantly busy

Give useful input on the product : Now, I know I'm just a kid in the company and I can't be expected to deliver anything ground-breaking in my first months, but  you have to give as much as you're paid. I'm getting around twice as much as at my previous job but objectively speaking I've not done anything to deserve it yet. Just sat around staring at my laptop screen trying to decipher code. Now you might say that this is what I'm here for , to start off with at least, but at my previous job I was something of a go-to-guy, making decisions and contributing to almost every aspect of the company's daily running. While that was a lot of work I enjoyed the feeling of being 'connected' in the inner workings of the company I have a stake in (a symbiotic relationship if you will).please edit this point down, I'll leave it up to you guys to decide what's important

I'll post more things as I think of them, have to get back to reading and writing something only vaguely resembling C#

答:
While I admire those who can sit back and read code like they read a novel, I find it a bit tedious at times and that it does not really work with large complex software products and libraries.

I wrote a long post about reading and understanding code here that might be useful for this particular discussion - technikhil.wordpress.com/2010/07/06/how-to-read-code-a-primer The post deals with reading code in the context of improving oneself, so it talks about how to go about finding good code to read; but in this case since you already have identified the code you want to comprehend - these points might be useful -

Go through the design documentation and try to get a feel for the
way the code has been built. Good software projects follow certain
architectural patterns – these dictate the code organization. Once
you get a handle on this, understanding the code becomes a whole lot
easier. If you can create a class diagram of the code you can get a
good idea of the layout.

The next thing to do is to compile it and run it. This can be
straightforward or tough depending on the process followed in the
project and it’s documentation.

Now it’s time to fire up your favorite IDE and go exploring. A good place to start your code exploration  would be to try to trace a functionality of the project that you are familiar with. This would let you go through the various layers and sub-systems and get a handle on how they inter-connect. For example when I was exploring NUnit – I started by writing a test and looking at the code classes I needed to do that.

Try and identify the design patterns used in the code. If you do not know what design patterns are, then you need to stop reading this post right now and read this book. Familiarize yourself with design patterns – they form a great way to recognize and understand the design of well written code. This makes it easier to keep it in your head while reading code. It also helps you identify nuances and customizations made by the programmers more easily.

Try to write tests for the code to fully understand it – this is really useful way to understand the dependencies between different parts of the code. When you try to write a test for the code you first need to satisfy (mock) all its dependencies. Next you need to understand the possible entry points as well as the exit values for the code. This improves your understanding of the code and gets you to the next level.

Try to refactor the code. In this step you have moved from simply understanding the code to becoming familiar enough to be able to modify it. As the sophistication of your refactoring increases so too does your understanding.


问:
Subscribe/Publish Model in Web-based Application (c#) - Best Practices for Event Handlers
I was recently exposed to a desktop application that uses an publish/subscribe model to handle commands, events, etc. I can't seem to find any good examples of using this in a web application, so I wonder if I am off base in trying to use this for web based development (on the server side)? I'm using asp.net c#.

My main question in regards to the design is:
When using a publish/subscribe model, is it better to have generic commands/events that pass no parameters and then have the subscribers look at static context objects that contain the data relevant to the event? Or is it better to create custom arguments for every event that contain data related to the event?

The whole concept of a global container seems so convenient but at the same time seems to break encapsulation.

Any thoughts or best practices from anyone who has implemented this type of model in a web based application? Even suggestions on this model out of the scope of my question are appreciated.

答:
For patterns (observer pattern, publish/subscribe, visitor pattern) where there is a single entity talking to or dealing with multiple entities the communication has what i call it language problem.

There is something similar i had answered which i recommend you to read Observer pattern; knowing *what* changed?

Basically, if you only give single argument or no arguments which means events are triggered and received as you want but they don't quite convey much. It works fine for many trivial example. On the other side if you keep too much information diverse for each module - then definitely you are creating something (as you call it a container) is only a dumping bags. Even for a moment if we keep encapsulation violation arguments away for a moment, dumping bags are not good. For the first part, if you have one more customer and if the container gets one more information is added all other customers now will have to ignore one more field (and recompile themselves)

Part of the problem really is, that while we typically generalize the observers (i.e. different concrete objects as observer and implement observe() or notify() method) but it is equally important that the notification that needs to be given itself is a matter of abstraction. We must ask - what should i notify? and even more what must i not notify?

Take a real world notifiers to understand this:

1. First of that class is broadcast type messages

* a notification at airport notifies about: arrived departed flights and their times.

* a stock market bill board notifies about: updates on various stocks

The first thing to understand that what gets notified is far more stable and very easily understandable, and hence, attaching any number receiver will not ever create a problem. The metadata is well defined and even if it has to change, it is likely that most observer will get benefited from it.

So really speaking language problem doesn't exists in broadcast type notifications.

2. The multicast or unicast scenario where there messages specific to obsever

Any typical newsletter or rss feed or email are rather personal, there is too and from fields that get the message to places. Here the message can be anything - so for all practical purposes, the message transmission doesn't typically have any single format that can hold all information - this is another extreme where to which a container can evolve to. As in the cases of emails for example, the metadata is again standardized but much meaningful information is in the body and it is upto the end observer/reader to interpret this. the language problem does exists here but channels (in our case the API which carries information) must be freed from interpreting this. Let the source somehow create a blob of information and let the observer know what to do with the blob.

So in essence, what you really need to do is to model the notification - what is truly the message content which needs to be black-boxed. the essence of the answer i gave in above link is that you may create a sort of generic name-value pairs or any general encoding of messages and pass on. It can even be something like  void* of C. But that exercise is must. On the other hand, find what is the metadata (such as source, timestamps, etc.). These fields can be visible to all message readers.

One last thing to note is, be critical to what is the responsibility of the source/publisher and what is not avoid customizations, extensions to the definition or role of publisher for specific customers. This is the single most source of digression in most such cases. Avoid till you come to a point of loosing salary! :)

Doing all this will force you to put more effort but save you from the technical debt of evolving into a huge (depending on your scale) garbage bag  type container and most people cannot figure out why these things are there.


答:
Parsing HTML for PHP tags will create extra overhead.  But unless you are talking about a fairly high traffic site, that extra overhead wont have a noticable impact on the performance of the site.

The bigger issue might be maintenance.  Will the next guy know there's PHP in those html files?  Whether thats a big issue or not would depend on your specific situation.


问:
How to recognize a good programmer?
Our company is looking for new programmers. And here comes the problem - there are many developers who look really great at the interview, seem to know the technology you need and have a good job background, but after two months of work, you find out that they are not able to work in a team, writing some code takes them a very long time, and moreover, the result is not as good as it should be.

So, do you use any formalized tests (are there any?)? How do you recognize a good programmer - and a good person? Are there any simple 'good' questions that might reveal the future problems?
...or is it just about your 'feeling' about the person (ie., mainly your experience), and trying him/her out?

Edit: According to Manoj's answer, here is the question related to the coding task at the job interview.

答:
first I start with the usual interview stuff, I consider very important to see if the person in front of me worth something, and to determine his/hers skills and knowledge.

After that  I use a couple of technics in the field of Java, like discussing some principles, mainly taken from Effective Java.

At this stage, when I think that I might have a good programmer in front of me, I give him a piece of code to code-review it. What I want to see is that he can pinpoint the dangerous parts of the code, give some pointers on improvements, find pitfalls on performance an multi threading AND that he can distinguish between important remarks and "taste-remarks". All this helps me to find a more proficient employee.

but in the end I always remember that hiring is a kind of gambling...very very hard to anticipate...

OwnerDisplayName: gius

Title: How to recognize a good programmer?


问:
Difference between Dependency Injection (DI) and Inversion of Control (IOC)
I've been seeing a lot of references of Dependency Injection (DI) & Inversion Of Control (IOC), but I don't really know if there is a difference between them or not.

I would like to start using one or both of them, but I'm a little confused as to how they are different.

答:
I would say "Inversion of Control" is a way to design a system where all the modules are thought of abstract entities.

And, "Dependency Injection" is an implementation where the concrete relation between different modules is decided at "run time".

OwnerDisplayName: Elijah Manor


问:
Are service locators really that bad?
People say Service Locators are bad because they expose the dependencies in some random method from the class (and not in the constructor's arguments like it should):

```<code>class A{

function F(){
   DB::query(...)
}
}
</code>```

instead of

```<code>class A{
protected $db;

function __construct(DB $db){
  $this->db = $db;
}

function F(){
  $this->db->query(...);
}
}
</code>```

But consider a function, like imagejpeg() from GD. Obviously you can't "inject" that, so you have to call it somewhere in your class, just like your service. So isn't this the same thing? That function is a dependency too.

Or what about instantiating an object somehwere in your class methods, like PDO. Aren't these things exactly like services after all? So why all the fuss about service locators being evil?

答:
The reason service locators are evil is because your class really should not be concered with any of the details of how to instantiate it's dependencies. You will end up with classes that know way too much about way too many things are get very hard to separate. Moreover, when you need to swap out that database class it is strewn about dozens of files in dozens of places rather than in a few initialization statements. </p>

<p>In the case of GD* functions, the way to manage that is to build an some sort of adapter interface and class that deals with calling GD* directly. Your classes talk to this interface which can easily be swapped and mocked out as you need. And need not actually be fully implemented when you are writing your main line of business code. </p>

Title: Are service locators really that bad?

Body:
The reason service locators are evil is because your class really should not be concered with any of the details of how to instantiate it's dependencies. You will end up with classes that know way too much about way too many things are get very hard to separate. Moreover, when you need to swap out that database class it is strewn about dozens of files in dozens of places rather than in a few initialization statements.

In the case of GD* functions, the way to manage that is to build an some sort of adapter interface and class that deals with calling GD* directly. Your classes talk to this interface which can easily be swapped and mocked out as you need. And need not actually be fully implemented when you are writing your main line of business code.


问:
Algorithm for scheduling a set of real life tasks that are input by the user
I am trying to write some code to schedule a set of real life tasks that are input by the user. These tasks are stored in an SQLite database. And at the moment, the only parameters I am taking into consideration are the,

```<code>The project to which a task belongs to --> p
The name of the task itself --> t
And the due date for this task --> d
</code>```

The project and due date parameters are optional. But assuming that the user will always input at least the task name and due date for every task.. I was wondering if it is possible to schedule the set of tasks using a scheduler like the Completely Fair Scheduler (CFS) for example. I realize that the CFS was written for scheduling tasks with much finer granularity (nanoseconds) than the set of tasks being proposed for this purpose... But I realized that it might be possible and maybe more efficient if I can modify it to work with tasks that are on the same time scale as our perception of time.

A typical entry in the database would be in the format (p, t, d). 'p' is optional. Here are a few examples:

```<code>(_, 'Call home', 29/2/2012)
(Work, 'Meet boss', 14/3/2012)
(Work, 'Ask for raise', 18/3/2012)
(_, 'Book tickets', 10/3/2012)
(Work, 'Quit', 14/4/2012)
(Personal, 'Get botox injections', 10/3/2012)
(Personal, 'Get breast implants', 10/10/2012)
(_, 'Dad bday', 7/10/2012)
</code>```

Here is a situation to consider. I would like to wake up in the morning. Run this "yet to be coded" algorithm on the set of tasks.. like the ones given above.. and I would like to receive a schedule for the rest of day, that maximizes throughput. At a later stage, I would like to pass arguments to this algorithms that would allow me to control the scheduler to return a set of tasks depending on my current situation. Like if I am at work, I want to be able to pass arguments to the algorithm, to ask it to only return tasks that can be completed at work..

I hope I am able to convey the gist of it. I understand that the due date alone is not sufficient to schedule tasks using the CFS for example... but if there are other parameters that I should consider, please do let me know. And any suggestions for the kind of scheduling algorithm to employ would be helpful.

答:
Okay, I've given some thought to it. This is how I imagine to accomplish it..

Assuming there is a set of tasks..where each task has,

```<code>A deadline
Time taken for completion
Time spent on the task so far
</code>```

I intend to represent those set of tasks as a genetic chromosome. Each chromosome will be encoded with an arbitrary number of tasks. The fitness of each chromosome will be determined by a fitness function that rewards chromosomes that have a set of tasks nearing the deadline and still incomplete. It also rewards tasks that haven't been given any attention in the recent past.

The fitness function punishes those tasks whose deadline is far away and those tasks that have had far more access to my attention (assuming I am the CPU) in the recent past.

My understanding is that.. the consequence of performing the above steps is that after a few generations it might be possible to arrive at a chromosome which has a set of tasks that is...

nearing its deadline

hasn't been given attention in the recent past

have the greatest probability of being completed in the given time (What I mean by this is that, if I ask the algo to give me a schedule for 3 hours then the winning chromosome must contain tasks that can be accomplished in that time frame)

Could someone please comment on my approach? Do you think it might work? I don't intend to take into consideration the dependencies between various tasks at the moment. I would like to get a bare functioning prototype to a working stage, after which I can recursively improve the algorithm...

Thanks.

Body:
Okay, I've given some thought to it. This is how I imagine to accomplish it..

Assuming there is a set of tasks..where each task has,

A deadline
Time taken for completion
Time spent on the task so far

I intend to represent those set of tasks as a genetic chromosome. Each chromosome will be encoded with an arbitrary number of tasks. The fitness of each chromosome will be determined by a fitness function that rewards chromosomes that have a set of tasks nearing the deadline and still incomplete. It also rewards tasks that haven't been given any attention in the recent past.

The fitness function punishes those tasks whose deadline is far away and those tasks that have had far more access to my attention (assuming I am the CPU) in the recent past.

My understanding is that.. the consequence of performing the above steps is that after a few generations it might be possible to arrive at a chromosome which has a set of tasks that is...

nearing its deadline

hasn't been given attention in the recent past

have the greatest probability of being completed in the given time (What I mean by this is that, if I ask the algo to give me a schedule for 3 hours then the winning chromosome must contain tasks that can be accomplished in that time frame)

Could someone please comment on my approach? Do you think it might work? I don't intend to take into consideration the dependencies between various tasks at the moment. I would like to get a bare functioning prototype to a working stage, after which I can recursively improve the algorithm...

Thanks.


问:
how to advance into higher level functional programming
first my apologies if this isn't the right place for this question but I think that th.CS is not the right place for sure neither is StackOverflow.

I really like functional programming and I think I'm a medium level guy in F# and understand the basic concepts of Haskell rather well - and yes I think I know/fell like I know what a Monad is.

Now I really want to take this to the next level and want to understand what all the talk about functors and stuff is all about.
I just don't know where to start.

Read something about Lambda Calculus? Category Theory? Both I know a bit and I don't think that this is the right/quickest way to enlightment.

Maybe you can give me some hints on that.

PS: I'm not afraid of math and I don't get frustrated on excercises easily but I would prefere some intros/text where you can put some code down because this way you get the feedback at once.

答:
Learn you a Haskell has an excellent introduction to functors.

For the really heavy stuff you can read Oleg Kiselyov's excellent site: delimited continuations, zippers, iteratees, ...


问:
Getting a logo and graphics for an open source project
I have been working on an open source project for about 2 years.

I would like to create a web site, but I am on essentially a zero budget. I also need a logo.

My question: How should an open source developer go about improving the project's "visual appeal" without spending a lot of money? Are there graphic designers willing to donate time? How does one find them (if they exist).

With a project you spend so much time on - you want to give it a nice looking web site so that it will grab people's eye. On the other hand, you don't want to spend money on something you are giving away for free.

Has anyone had any personal experiences they can share?

答:
Since it is open source have you considered using a free, existing site like Github rather than building a new website?

As for a logo, you could try:

Farming the job out and perhaps offering $25, someone in the world might well be willing to do it for that price.

As part of your Githup homepage ask for help designing a logo.

Run a contest and announce it on your Github page. Pick some appropriate prize like offer to send the winner a t-shirt with the logo on it that you signed personally.


问:
Should a standard include header be specified in each file or as a compiler parameter?
I've got a file such as this:

```<code>#ifndef STDINCLUDE
#define STDINCLUDE

#include <memory>
#include <stdexcept>

#endif
</code>```

I want this file to be included in every header file, because I use stuff from those headers so much. Is it preferable to include this via compiler options (-I stdinclude.hpp), or should I physically include them in each header? (#include <stdinclude>). Note that I am attempting to be cross-platform-minded. I use cmake to serve atleast Unix and Windows.

答:
For many compilers, including gcc, the -I option specifies a directory to search for include files, not an individual file.  I don't know of an option to include a single file.  For one thing, such an object would not specify where in the source to place the #include directive.

Even if there were such an option, I would not recommend using it.  The choice of which headers to include is information that should be in the source file.  If you were to specify it on the command line, you'd be decoupling that information from the source file (presumably it would be in a Makefile or something similar), which would make the source code more difficult to understand and maintain.  And anyone trying to port your software to a different build system would have to port that option separately.

Presumably most of your source files include headers other than stdinclude.hpp.  Including that one file via a compiler option, and everything else via explicit #include directives, is arbitrary and potentially confusing.

By having an explicit

```<code>#include <stdheader.hpp>
</code>```

or, since it's part of your project:

```<code>#include "stdheader.hpp"
</code>```

you let the reader know that your code uses something defined in that header.

If that's all there is to your stdheader.hpp file, you might even consider dropping it and having each source file use

```<code>#include <memory>
#include <stdexcept>
</code>```

directly.  That way, your readers will know exactly what's being #included, and won't have to know or care what's in stdheader.hpp.  That's a pretty good benefit for one extra line per file.  If stdheader.h becomes more elaborate, using it might make more sense.

Body:
For many compilers, including gcc, the -I option specifies a directory to search for include files, not an individual file.  I don't know of an option to include a single file.  For one thing, such an object would not specify where in the source to place the #include directive.

Even if there were such an option, I would not recommend using it.  The choice of which headers to include is information that should be in the source file.  If you were to specify it on the command line, you'd be decoupling that information from the source file (presumably it would be in a Makefile or something similar), which would make the source code more difficult to understand and maintain.  And anyone trying to port your software to a different build system would have to port that option separately.

Presumably most of your source files include headers other than stdinclude.hpp.  Including that one file via a compiler option, and everything else via explicit #include directives, is arbitrary and potentially confusing.

By having an explicit

#include <stdheader.hpp>

or, since it's part of your project:

#include "stdheader.hpp"

you let the reader know that your code uses something defined in that header.

If that's all there is to your stdheader.hpp file, you might even consider dropping it and having each source file use

#include <memory>
#include <stdexcept>

directly.  That way, your readers will know exactly what's being #included, and won't have to know or care what's in stdheader.hpp.  That's a pretty good benefit for one extra line per file.  If stdheader.h becomes more elaborate, using it might make more sense.


问:
Does Object Oriented Programming Really Model The Real World?
I've seen it commonly repeated the object-oriented programming is based on modeling the real world but is it?

It seems to me that is not true of anything outside of the business layer. My GUI classes/data access classes aren't modeling anything in the real world. Even in my business layer, I've got classes like observers, managers, factories, etc. which aren't real world objects. I try to design my classes to take advantage of things like encapsulation but is the real world encapsulated?

While some objects I create are modeling real-world objects, would not pre-OOP code do the same? I doubt that OO was the first people to include concepts like Customer in their code bases. But OO is really about how to model things, and that method of modeling doesn't seem inspired by the real world to me.

So: does object-oriented programming really model the real world?

答: It does not model our world, but it does model the human interpretation of our world. Humans naturally separe things as objects. OO is effective because it allows humans to program the way they think.</p>


问:
Can Javascript code be encrypted making it hard for someone to copy?
When you compile and distribute a client you are automatically protecting yourself from someone seeing and modifying your code. Can this be achieved on a Javascript client?</p>

答:
Regarding client-side javascript code, which is what we usually see on the web, is unusable when put through an encryption scheme as the web browser needs to read the code so it can be interpreted by the browser. Usable javascript code is always trivial to view and get a copy of.

You could obfuscate the code, making it harder to understand, with a minifier such as the yui-compressor. Though its purpose is to compress the code so that the cost of bandwidth can be cut down or if you are concerned for having it load fast enough for your users.

Does this mean it is easy to "copy"? It depends on what your javascript code does. Most of the javascript code that is difficult to reproduce is tied to something it expects from a web server such as JSON/XML/HTML data. Web applications are difficult to copy because they depend on code-behind from different data sources.

By the way, don't worry, others will try to steal your site...

Anecdotally I used to work at a e-commerce store that has a very nifty designer web application. The customers can design the product the way they want it and the controls on the website rely heavily on javascript. A lot of people have tried to copy the site and seemingly fail for which we only could secretly scoff about (and feel a teeny bit proud about ourselves):

We found through a Google Alert that a shady chinese site completely ripped the site for their own (not even replacing the logo). Apparently they tried to set up their own store. The problem was that they didn't have the graphical assets that our backend provided. Thus they clearly haven't had any use other than to show off on "hey, look what we can do".

For years we've seen several freelancer.com ads where we were referred to which didn't seem to pan out, probably due to the ridiculously proposed budgets, short time schedules and poor description of what they want to do with it. For some reason the people who put these ads up have no idea how incredibly complex the business behind the website really is.

Sometimes people are really lazy: One time we've got a call from a company who wanted to know who designed our website. Apparently some design agency was using us as reference and the problem is that we did it all in-house.

This shows that even if you have a javascript web app, it is still difficult to copy it and make a business out of it because you have everything else under the hood to worry about. In our case we had most of the product structure and graphical assets done in the back end, not to mention the production pipeline to produce the actual products that also needs to be in place. So it's all not just web development.


答:
Use the context.

According to your profile, the open source project you are talking about is an extension for IntelliJ IDEA. This means that:

You can inspire yourself from the logo of IntelliJ IDEA to create your custom logo. Since the existent logo is rather basic and not very well though, it must not be very difficult to work from it even with no professional experience in visual identity.

It also has an additional advantage: by having a logo close to the one already used by IntelliJ IDEA, you show that your product is related.

This being said, be careful. Inspiring yourself of some parts of the logo doesn't mean copy the logo itself, which would be illegal in most countries.

You can talk to people from JetBrains. I'm sure they have full-time designers, and they are also interested in extending their product with third-party extensions. Not only they may be interested in providing you a few services like the design of your logo, but they may even suggest your extension on their website.

Title: Getting a logo and graphics for an open source project

Body:
I have been working on an open source project for about 2 years.

I would like to create a web site, but I am on essentially a zero budget. I also need a logo.

My question: How should an open source developer go about improving the project's "visual appeal" without spending a lot of money? Are there graphic designers willing to donate time? How does one find them (if they exist).

With a project you spend so much time on - you want to give it a nice looking web site so that it will grab people's eye. On the other hand, you don't want to spend money on something you are giving away for free.

Has anyone had any personal experiences they can share?


答:
"Protected"? No. "Inconvenient"? Yes. (Just as with binary.)

At a certain level, no popular operating systems (yet) can prevent a sufficiently motivated actor from recovering the in-memory representation of your program and reverse-engineering it. So the "protection" is only relative to the value of your code to another.

If you accept that it is a matter of degrees, then the question becomes "Is it possible to make JavaScript quite inconvenient to understand?"

It is:

Trivial to make JavaScript somewhat difficult to undersand using a minimizer

Fairly easy to make JavaScript rather difficult to understand using an obfuscator

Theoretically possible to make JavaScript quite difficult to understand using your own obfuscation protocol (i.e., encrypted payloads, program execution based on deceptive side-effects and intentional use of language edge-cases)

Title: Can Javascript code be encrypted making it hard for someone to copy?

Body: When you compile and distribute a client you are automatically protecting yourself from someone seeing and modifying your code. Can this be achieved on a Javascript client?</p>


答:
No JS obfuscator is worth the money and sweat to use them.

JavaScript can always be reversed, and no matter what the obfuscator's method is, you will able to run through the obfuscated code and study it in any modern browser. Except if the obfuscator would also package code meant to make your life harder to prevent the use of debug tools, but it would just be eventually circumvented and rendered useless as well.

If you really need secrecy for your code, then don't use JavaScript and rely on other technologies. If you approach the problem the other way around, and you already built the new coolest JS-based web-app and want it to be hidden: give it up.

So, I'd say no, you can't really protect it, and don't bother spending cash on paid obfuscators (if you want to waste time, feel free to use the free ones out there, though they're barely worth your time too). Just use a good minifier / compressor / compiler to reduce the pay load. It will already make it harder to read, but not longer to run as will a lot of obfuscators. And it's still less readable to make it slightly more annoying to read and discourage some.

For good minifiers / compressors / compilers, read my answer (and the rest of the thread) to: What do you Use to Compress JavaScript Libraries?

Also, when distributing a client, you're not really protecting yourself that much either. Disassemblers exist and knowledgeable software engineers who know how to use them are legion. Don't rely on obfuscation / obscurity for security, and don't consider a client a trade secret.

If you really meant to encrypt the JavaScript code, that would imply that something needs to decrypt it before executing the code, meaning you'd need to either have a browser plugin installed on all clients or to have your page contained a JS-based decryptor, essentially giving the tool to anyone who'd like to decrypt the code. Additionally, the browser would see the decrypted version at runtime anyways.


问:
What JavaScript inconsistencies should I look out for?
I remember reading some "funny" examples once of weird results JavaScript can give when you, for example, add strings to numbers etc. Does anyone have any good examples or a link to the blog that I might have read them on? Which ones are likely to catch a programmer out in the real world?</p>

答:
All the ones that are described in:

the WAT talk (warning: this is really fun! - skip the Ruby part if you want),

WTFJS,

a Collection of JavaScript Gotchas,

anything listed in resources in this answer,

and any message that JSLint and JSHint will spit or throw back at you.


答:
You can but it would be pointless. The browser has to eventually see unencrypted javascript otherwise it cant run it. It would then be trivial to find what the browser is currently running.

If you need lots of security on your client side code then your doing something wrong. You should be doing your complex logic and validating inputs on the server side.

On a side note, its also worth mentioning that its also trivial in most languages to get from compiled code to human readable code. There are techniques to make it harder but none of them is perfect.


问:
Pronunciation in programming?
How do you correctly or erroneously pronounce programming terms?  Any that you find need strict correction or history into the early CS culture?

Programming

char = "tchar" not care?

! = bang not exclamation?

# = pound not hash? Exception #! = shebang

* = splat not star?

regex = "rej ex" not "regg ex"?

sql = "s q l" not "sequel" (already answered, just i.e.)

Unixen

| = pipe not vertical bar?

bin = bin as in pin , not as in binary?

lib = lib as in library , not as in liberate?

etc = "ett see" , not "e t c" (as in /etc and not "&c")

Annoyance

/ = slash not backslash

LaTeX = "laytek" not "lay teks"

答:
# = Hash     (£ is a pound sign)

! = Pling

Title: Pronunciation in programming?

Body:
# = Hash     (£ is a pound sign)

! = Pling