答:
I still have no idea why you're insistent on parsing HTML (whether it's in a template or not). It's just a bad design (imho). The template is the presentation piece, which the model (or seemingly the view model in this case) should know nothing about. By parsing the HTML, you're introducing tight coupling needlessly.

If the intent is to make it easy for designers to work with (I have no idea why designers are working with code, HTML/CSS or not), then let them stick to writing the templates. But, have them also create a file (JSON perhaps?) that contains meta information about each view. When the validation routines execute, all they have to do is check the meta data against the POST data and validate each one accordingly.

For example:

Template:

```<code><form action="/accounts/create" method="POST">
<!-- other stuff here -->
<input type="text" name="fname" />
<input type="text" name="bdate" />
<!-- other stuff here -->
</form>
</code>```

JSON meta-data:

```<code>{
    "action": {
        "url": "/accounts/create",
        "inputs": {
            "fname": {
                "type": "text",
                "maxlen": 25
            },
            "bdate": {
                "type": "date"
            }
        }
    }
}
</code>```

Now, you'll have PHP code that will get the URL from the request, match it to a specific JSON entity and run all of the validation routines that you want on it.

What do you get out of this?

It's easy. It's readable.

Writing a tool to automate the JSON creation should be trivial (if you really wanted to, here's where you could parse the template to generate the meta-data).

There's no parsing to be done (other than the initial hit you'll take for parsing the JSON, which is miles better than parsing HTML, especially during a response).

It separates your presentation layer from your view logic. You could turn your template into a client-side-driven jQuery template rendering and it wouldn't matter. All that matters is that the names of the form elements match up to those in the JSON.

That's most likely how I'd go about doing something like this.

Title: why use a form object when you can get needed data from view object's html?

Body:
I am working with server side code.

I have a request object that handles request data validation and filtering.

I have a view object that uses template files to generate html for output. the template files are mostly html. you can put one view object inside of another view object in order to assemble a page piece by peice. for instance you might have a page layout view, and you might put a form view inside the page layout view.

One of the features of the request object is that it can automatically build validations using an html5 string containing a form. It parses the html string and grabs input types and other tag attributes that determine HTML5 validation, then matches this validation server side. I get this html string from a view object. This way no matter what the designer puts in the view's template file, it will automatically get validated according to the html5 attributes server side.

i create and use the same view that was originally used to generate the page, to build validations for the request when the page is then submitted back to the server.

I would like to get feedback on this idea. Pros/Cons/Other Concerns.

Body:
I still have no idea why you're insistent on parsing HTML (whether it's in a template or not). It's just a bad design (imho). The template is the presentation piece, which the model (or seemingly the view model in this case) should know nothing about. By parsing the HTML, you're introducing tight coupling needlessly.

If the intent is to make it easy for designers to work with (I have no idea why designers are working with code, HTML/CSS or not), then let them stick to writing the templates. But, have them also create a file (JSON perhaps?) that contains meta information about each view. When the validation routines execute, all they have to do is check the meta data against the POST data and validate each one accordingly.

For example:

Template:

<form action="/accounts/create" method="POST">
<!-- other stuff here -->
<input type="text" name="fname" />
<input type="text" name="bdate" />
<!-- other stuff here -->
</form>

JSON meta-data:

{
    "action": {
        "url": "/accounts/create",
        "inputs": {
            "fname": {
                "type": "text",
                "maxlen": 25
            },
            "bdate": {
                "type": "date"
            }
        }
    }
}

Now, you'll have PHP code that will get the URL from the request, match it to a specific JSON entity and run all of the validation routines that you want on it.

What do you get out of this?

It's easy. It's readable.

Writing a tool to automate the JSON creation should be trivial (if you really wanted to, here's where you could parse the template to generate the meta-data).

There's no parsing to be done (other than the initial hit you'll take for parsing the JSON, which is miles better than parsing HTML, especially during a response).

It separates your presentation layer from your view logic. You could turn your template into a client-side-driven jQuery template rendering and it wouldn't matter. All that matters is that the names of the form elements match up to those in the JSON.

That's most likely how I'd go about doing something like this.


问:
How to structure my data model for merging of accounts
My new site will allow for 'normal' registration or the use of Facebook openauth.

I have many tables that link data to a user_id.

Imagine one of my users with information on my site forgets they used Facebook to create an account.
They create a second 'normal' account and use the site for a while.
So the user has data associated with two user_ids.

I want to give them the option of "importing" the data associated with the first account into the newest account.

This is messy, and I would rather design things right in the first place but I can't wrap my head around an elegant way to do this.

Here are the options I have thought of:

Allow a user profile to have a master(parent?)_id, and write all of my db queries to select many user_ids.  Upon a merge from one account to another, the losing account gets the winning account's user_id as it's parent_id.

The above, but cleaner: consolidate many logins into a lookup table

System-wide one time update: Find all data with user_id 1 and change it to user_id 2.  This gets progressively harder as we store more data.

Merge with data loss- same as #3 but only crucial data.  The user loses historical records etc.

Or am I glossing over an easier way to handle the scenario I am trying to plan for?

答:
Keep all the ids/logins separate and do not merge anything.  Instead have a master table that maps the user's relationships.  Also add a column to the User table that would point to the master table.

```<code>Table MasterUser
ID   UserID
561  1
561  2
561  3
561  4

Table User
ID Email              MasterUserID
1  email@home.com      561
2  otheremail@home.com 561
3  meagain@home.com    561
4  same@home.com       561
</code>```

If the user logs in with "otheremail@home.com" you can do a lookup using the MasterUserID and quickly see all the IDs that user has.

The tricky part is knowing when to ask the user to associate accounts.  I suppose you could go by the current session.  But what if the user is on a shared computer?  You may want to notify the user via email and give them the option to remove a link if done in error.

Just some quick thoughts on how to merge any user data on the fly. Not sure if this pseudo code would actually pan out

```<code>AllUserIDs(@UserID)

    Declare @MasterUserID =

    SELECT MasterUserID
    FROM MasterUser
    WHERE UserID = @UserID

    --Return list
    SELECT UserID
    FROM MasterUser
    WHERE ID = @MasterUserID
END
</code>```

You could edit your other queries to look something like

```<code>SELECT *
FROM TABLE
WHERE UserID in (AllUserIDs(@UserID))
</code>```

Essentially replacing your @UserIDs with AllUserIDs(@UserID)

ContentLicense: CC BY-SA 3.0

Body:
Keep all the ids/logins separate and do not merge anything.  Instead have a master table that maps the user's relationships.  Also add a column to the User table that would point to the master table.

Table MasterUser
ID   UserID
561  1
561  2
561  3
561  4

Table User
ID Email              MasterUserID
1  email@home.com      561
2  otheremail@home.com 561
3  meagain@home.com    561
4  same@home.com       561

If the user logs in with "otheremail@home.com" you can do a lookup using the MasterUserID and quickly see all the IDs that user has.

The tricky part is knowing when to ask the user to associate accounts.  I suppose you could go by the current session.  But what if the user is on a shared computer?  You may want to notify the user via email and give them the option to remove a link if done in error.

Just some quick thoughts on how to merge any user data on the fly. Not sure if this pseudo code would actually pan out

AllUserIDs(@UserID)

    Declare @MasterUserID =

    SELECT MasterUserID
    FROM MasterUser
    WHERE UserID = @UserID

    --Return list
    SELECT UserID
    FROM MasterUser
    WHERE ID = @MasterUserID
END

You could edit your other queries to look something like

SELECT *
FROM TABLE
WHERE UserID in (AllUserIDs(@UserID))

Essentially replacing your @UserIDs with AllUserIDs(@UserID)


答:
I think I answered a question similar to this a while ago, but just can't find the link atm..

What I might do is create a model class without authentication information. Something like (done in Python/SQLAlchemy because that's what I felt like writing at the moment ;)):

User model

```<code>class User(Base):
    __tablename__ = "user"
    user_id = Column(Integer, primary_key=True, autoincrement=True)
    fname = Column(String(50), nullable=False)
    lname = Column(String(50), nullable=False)
</code>```

User auth model (keeping n authentication methods for each user)

```<code>class UserAuth(Base):
    __tablename__ = "user_auth"
    auth_id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey("user.user_id"), nullable=False)
    provider = Column(Integer, nullable=False)

class AuthFactory(Base):
    # the index here would match what's stored in the provider column of UserAuth
    _providers = [
        FacebookProvider,
        MySiteProvider
    ]
    def get_provider(self, id):
        return _providers[id]()
</code>```

If FacebookProvider and MySiteProvider (and whatever other provider you want to add eventually to your system) implement the same interface, then swapping between providers is trivial.

Note: The above code obviously hasn't been tested and there are many different ways of achieving the same result, this is just what I whipped up off the top of my head. Would love to know of any holes in the idea though as I'm planning on using this concept myself in a future project.

Title: How to structure my data model for merging of accounts

Body:
My new site will allow for 'normal' registration or the use of Facebook openauth.

I have many tables that link data to a user_id.

Imagine one of my users with information on my site forgets they used Facebook to create an account.
They create a second 'normal' account and use the site for a while.
So the user has data associated with two user_ids.

I want to give them the option of "importing" the data associated with the first account into the newest account.

This is messy, and I would rather design things right in the first place but I can't wrap my head around an elegant way to do this.

Here are the options I have thought of:

Allow a user profile to have a master(parent?)_id, and write all of my db queries to select many user_ids.  Upon a merge from one account to another, the losing account gets the winning account's user_id as it's parent_id.

The above, but cleaner: consolidate many logins into a lookup table

System-wide one time update: Find all data with user_id 1 and change it to user_id 2.  This gets progressively harder as we store more data.

Merge with data loss- same as #3 but only crucial data.  The user loses historical records etc.

Or am I glossing over an easier way to handle the scenario I am trying to plan for?

Body:
I think I answered a question similar to this a while ago, but just can't find the link atm..

What I might do is create a model class without authentication information. Something like (done in Python/SQLAlchemy because that's what I felt like writing at the moment ;)):

User model

class User(Base):
    __tablename__ = "user"
    user_id = Column(Integer, primary_key=True, autoincrement=True)
    fname = Column(String(50), nullable=False)
    lname = Column(String(50), nullable=False)

User auth model (keeping n authentication methods for each user)

class UserAuth(Base):
    __tablename__ = "user_auth"
    auth_id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey("user.user_id"), nullable=False)
    provider = Column(Integer, nullable=False)

class AuthFactory(Base):
    # the index here would match what's stored in the provider column of UserAuth
    _providers = [
        FacebookProvider,
        MySiteProvider
    ]
    def get_provider(self, id):
        return _providers[id]()

If FacebookProvider and MySiteProvider (and whatever other provider you want to add eventually to your system) implement the same interface, then swapping between providers is trivial.

Note: The above code obviously hasn't been tested and there are many different ways of achieving the same result, this is just what I whipped up off the top of my head. Would love to know of any holes in the idea though as I'm planning on using this concept myself in a future project.


问:
Should I learn design patterns or algorithms to improve my logical thinking skills?

Possible Duplicate:

  How can I improve my problem-solving ability?

When starting a programming task, I have trouble breaking it up into steps and figuring out how to go about solving it.

I want to get better at it. Should I to focus on data structures/algorithms? Or should I be studying more design patterns?

What do you think would help in thinking more logically and being able to break things into steps?

答:
I think its quite simple: code more!

Your problem sounds exactly what i had when i started programming. And the only way to go around it was to just code more, more and more! Only then you can have the real grasp on it.

Just start small, dont go on big projects first.


答:
I'm currently taking a course called "Algorithms Analysis".  This class is ALL about breaking problems up into steps and solving them (with an emphasis on optimization).

You should study algorithms.  After studying an algorithm, close your eyes and try to recreate the entire algorithm on your own.  It's important to understand each step at a higher level than just memorization so you can apply it to different examples.  With practice, you will get quicker.

Title: Should I learn design patterns or algorithms to improve my logical thinking skills?

Body:
Possible Duplicate:

  How can I improve my problem-solving ability?

When starting a programming task, I have trouble breaking it up into steps and figuring out how to go about solving it.

I want to get better at it. Should I to focus on data structures/algorithms? Or should I be studying more design patterns?

What do you think would help in thinking more logically and being able to break things into steps?


答:
i have trouble seeing the logic in code sometimes

This is common, don't worry about it. Understanding code that you're not familiar with is much like trying to understand how someone else thinks. Usually getting a walkthrough of that entire portion (not the entire system as it may make your head explode if the entire system is big enough) of the system architecture helps a great deal. Once you understand the overarching solution, the logic in the specific code chunks can start to make quite a bit more sense.

It sounds to me like you need practice at system architecture. The next time you're tackling a problem, forget about the code. First, fully understand the problem that you're dealing with. Of course, if you don't fully understand a given problem, engineering a solution will be difficult at best. Next, take a look to see if there's an implementation for that problem readily available (OS), or if there's a design pattern that can be applied to it (Wikipedia has a decent list). If not, then start desiging a solution (still not even thinking about the code - all of this should be abstract design).

Once your design is done, then start coding.

Of course, studying design patterns and algorithms (and algorithm design/analysis) will most definitely help you in your conquest here, but practice really is just as important (whether you actually implement your designs or not is beside the point).

Doing this enough times will help spur that abstract problem solving thinking that you seem to be having issues with.

And don't ever forget: No matter how good you think you get at this, there will always be someone (or a number of someones) who are quicker/better/brighter than you. Use them to help you get better - don't let their abilities frustrate you.


问:
Why isn't functional programming more popular in the industry? Does it catch on now?
During my four years at university we have been using much functional programming in several functional programming languages. But I have also used much object oriented programming to, and in fact I use object oriented languages more when doing my own small project to prepare for my first job. But I often wish that I was coding in a functional programming language when doing these projects.

However, when looking for a job, it is very rare to see a job where knowledge of a functional programming language is required.

Why isn't functional programming languages used more in the industry? There is quite much news about functional programming languages these days, so I wonder if functional programming is catching on in the industry now?

答:
Lack of killer app

Hey, this one over here looks fresh. (dig dig dig)

I think most programming languages thrived by having a "killer app" - something compelling that was exclusive to the language (or viewed that way). This is not to say that all of the uptake was that application, but that it drove the language to a larger acceptance.

Here's my not terribly accurate view of what niche has driven the adoption of some of the languages we have today:

C: Works everywhere (This was the late 70s and 80s)

C++: GUI frameworks (early 90s)

Java: Applets and servlets (in the late 90s)

Objective-C: iOS apps (Before that, OS X apps)

Ruby: Rails

C#: ASP.NET, WinForms

PHP: Wordpress, etc.

Javascript: AJAX, especially via frameworks

lua: Game scripting, especially WoW

Aside from that, many proprietary languages have gotten in the door through powerful sales organizations (Oracle, and to a lesser degree Microsoft's languages), effectively creating their own niche.

One very important note about that list: The language's "niche", as indicated by the killer app, gets more and more specific as decades pass. Note the last one on the list: Game scripting, specifically. It's getting harder and harder for languages to get attention because of the list of things that are already done well enough by another language.

So, what any functional language needs to really take off is a niche. In reality, there aren't any huge functional languages yet, but there are a whole lot in smaller niches:

Emacs Lisp: Constant use since the 80s in Emacs by developers. (Hardly ever used anywhere else.)

Erlang: Anywhere you want lots of concurrent agents.

Scheme: Education

APL/J/K: Finance (Let's call these functional, for the sake of the argument)

Common Lisp: "AI" - This is what people tend to say it's used for, which is a blessing and a curse.

Now, the only major language I feel I've left out of this discussion is Python. Python has done something very interesting; it has succeeded without appearing to be the winner in any major niche. This could mean that I'm flat-out wrong for viewing language popularity this way. It could also mean that a good enough language can become popular without a killer app to drive adoption and acceptance, but it is very difficult and might take a very long time. (Perl has a similar story, but came a few years earlier and is now has less uptake.)

From this, I can say which functional languages I think are on the rise:

Clojure: Web programming, esp. through Heroku

Scala: Lift (or maybe Play, these days) - JVM without Java

If you asked me where to look next for popular functional languages, I'd say be on the lookout for a functional language with turnkey cloud development (a la Heroku or GAE) or turnkey mobile app development.

ContentLicense: CC BY-SA 2.5


问:
What traits do the best managers you've worked for have in common?
I have been listening to Scott Hanselman and Rob Conery's podcast, This Developer's Life.

In the latest episode, they discuss personality traits:

1.0.4 - Being Mean.

What makes people mean in our
  industry? What about aggressive?
  Confident? What's the difference?
  Would you rather have a drill sergeant
  for a boss, or a zen master? We talk
  to Cyra Richardson and Giles Bowkett.

It got me thinking, what traits did the best managers you've worked for have in common?

EDIT: Just to clarify, as there have been a few close votes, I'm interested in whether there are traits common to managers of developers that are not necessarily those traits that a manager of some other profession requires.

As for whether this is programming related or not, well I don't want to ask this question on a site that isn't about programming because, frankly, I'm not as interested in what people who make cans of soup for a living want from their managers as I am interested in what developers want from their managers.

答:
They trusts their people to get the job done and don't try to "herd cats".

Give their people room to make mistakes(not huge ones obviously) and learn from them.


问:
Questions about releasing an application that has been built on an IDE on an educational license
If an application is made during education using an IDE that had an Educational License (provided by the institute), and later the developers decide to release it in the market as a product:

Is it legal, and valid to do so?

Is it valid to build that application through the free or commercial version of the same IDE, or the project has to be re-coded or developed from the start, entirely on the commercial version of the IDE.

What permissions and licenses should be acquired if there is such plan?

What are the other things too look for in this regard?

If there is such plan, how to prepare for it at the start of the project, like who to talk to and how to talk about it, what paperwork etc. should be done so that in the end, there is nothing illegal.

答:
If there are educational and commercial versions of an IDE, there will be most-likely written licensing information for that product, so check this first.

project has to be re-coded or developed from the start

That sounds like superstitious nonsense for me - I don't believe there exists an IDE where you can see a difference between code that was developed with a commercial license from day one, or code which was developed with the educational license and then later switched to the commercial license of that IDE. So even if an IDE vendor would try to include such absurd terms into the "terms of use", he would run into trouble to find some evidence against you.


问:
Best practices for expiration of tokens in a Security Token Service (STS)
When creating a Security Token Service (STS) for a claims based security model, it seems appropriate that tokens are generated in such a way that they expire after some duration, as suggested here.
Around this concept, I have a few specific questions, but am looking for any feedback regarding best practices in this area.

What are recommended values for the timeout length and/or what should be taken into consideration when determining this?

If a user is active for longer than the typical expiration period, how should this be handled such that the user is no required to re-authenticate in the middle of their session?

Is there an elegant way to design a service to perform batch actions "on behalf of" another user by utilizing the token?  i.e. Utilizing the token at a later time may have caused it to expire.

答:
I normally see 2-9 hours. 9 gives you the work day.

If the token has expired, they need to reauthenticate. End of story.

Depends on how the system works. Do you need the entire context or can you fake it? If the system can just say "I am system, but on behalf of Jimmy" within your app then it's easy. If you actually need Jimmy's token to perform the operation then you are stuck.


答:
1. Is it legal, and valid to do so?

According to what you describe, assuming no code changes after the move from educational to commercial, I'd say, yes - might be worth asking in the IDE vendor forums though.

2. Is it valid to build that application through the free or commercial version of the same IDE, or the project has to be re-coded or developed from the start, entirely on the commercial version of the IDE.

If the IDE requires your app to have a license that prevents derivative work from being commercial, then it's illegal, but that's very unlikely. I'd assume it's fine to take any software with educational license (even that you didn't write, assuming no intellectual property issues to it) and create a commercial version of it, unless the educational license (of the university or so) does not allow derivative commercial work.

3. What permissions and licenses should be acquired if there is such plan?

I'd say confirm (from the university/institute), even if you are the one who developed the software in education, whether the derivative commercial work is allowed, and ensure to have an IDE license that allows commercial work for the coming work of the software (likely you cannot ship it as-is, maybe the institute will permit you though -in writing-).

4. What are the other things too look for in this regard?

As mentioned above, official approval from the institute (just the professor who has been mentoring the project should be enough, better in writing), and a license for future development. Also, for all components that may have been used in the app (libraries, etc..), ensure they have commercial friendly licensing or obtain one.

5. If there is such plan, how to prepare for it at the start of the project, like who to talk to and how to talk about it, what paperwork etc. should be done so that in the end, there is nothing illegal.

I think an official letter from the univ/institute that clearly treats the app as educational before the date of the letter should be the most important step. Also obtaining a commerical license going forward for all app dependencies (including IDE). Basically the idea is you try to act as if you were other person picking the software from the univ/institute not the same who developed it (but not claim you actually are, but try to act equal to that). And of course remove the educational version from any involved computer.

Title: Questions about releasing an application that has been built on an IDE on an educational license

Body:
If an application is made during education using an IDE that had an Educational License (provided by the institute), and later the developers decide to release it in the market as a product:

Is it legal, and valid to do so?

Is it valid to build that application through the free or commercial version of the same IDE, or the project has to be re-coded or developed from the start, entirely on the commercial version of the IDE.

What permissions and licenses should be acquired if there is such plan?

What are the other things too look for in this regard?

If there is such plan, how to prepare for it at the start of the project, like who to talk to and how to talk about it, what paperwork etc. should be done so that in the end, there is nothing illegal.


答:
Chances are somebody has already met a similar functionnal problem and explained it on the web. If you don't know where to start, asking on the web is a valid solution.

Better than writing crap code anyway.

What language do you use? algorythms is more about knowing your API.

But you are right, learning design patterns indeed will make you a better programmer, so few people know them in the industry.


问:
What does SVN do better than Git?
No question that the majority of debates over programmer tools distill to either personal choice (by the user) or design emphasis, that is, optimizing design according to particular uses cases (by the tool builder). Text editors are probably the most prominent example--a coder who works on Windows at work and codes in Haskell on the Mac at home, values cross-platform and compiler integration and so chooses Emacs over TextMate, etc.

It's less common that a newly introduced technology is genuinely, demonstrably superior to the extant options.

Is this in fact the case with version-control systems (VCS), in particular, centralized VCS (CVS and SVN) versus distributed VCS (Git and Mercurial)?

I used SVN for about five years, and SVN is currently used where I work. A little less than three years ago, I switched to Git (and GitHub) for all of my personal projects.

I can think of a number of advantages of Git over Subversion (and which for the most part abstract to advantages of distributed over centralized VCS), but I cannot think of one contra example--some task (that's relevant and arises in a programmers usual workflow) that Subversion does better than Git.

The only conclusion I have drawn from this is that I don't have any data--not that Git is better, etc.

My guess is that such counter-examples exist, hence this question.

答: Speed. Sometimes takes 10 or 15 minutes to clone a big git repository, while a similar sized subversion repository takes a couple of minute to check out.</p>

Title: What does SVN do better than Git?


问:
Why do we tend to make things too complicated?
The fact that principles like KISS and YAGNI are so popular, speaks clearly about our inclination to make things too complicated.

Is this inclination a part of our nature or is it a part of our culture?

答:
We consider things to be simple when we have fully understood them. This is supported by the elaborateness of cargo cults, which are very complex systems because they are ill-understood.

Most programming happens in the "not yet understood" zone, because most fully understood projects have already been programmed earlier. (As a notable counterexample, consider compilers and compiler theory.) So, it is in the nature of software engineering to produce complicated things because we have not yet grokked the problem fully, to understand them in the process and then refactor the code. KISS and YAGNI try to suppress our tendencies to build too much code too early.

Conclusion: It is part of our nature.


答: I think a considerable contributing factor is the expectation that requirements will change. That's clearest with YAGNI: it's explicitly attacking the idea "I don't need it yet, but I might in the future".</p>

Title: Why do we tend to make things too complicated?

Body:
The fact that principles like KISS and YAGNI are so popular, speaks clearly about our inclination to make things too complicated.

Is this inclination a part of our nature or is it a part of our culture?


答:
the answer has two parts. the first one is the perspective of developer and the other one as user perspective.

the user intents to do want everything as easy as possible. the user does not know anything of the background, of daemons, of process, processors etc.. the user doesn't want to know anything of that. and this shouldn't be a condition to use a program.

the developer part is quite complicated since the developement process is quite complicated. as developer you should be a good designer, a good coder, a good tester and many more. a lot code is build during understanding like thiton said. and in my opion: the most code seems to be build in a hurry. time schedules and competition lead to urgency. so many problems with ugly code could be avoided if you could take more time for coding. not the money driven hastiness.

my conclusion: bad process management and rare time.


答:
Alex Papadimoulis of thedailywtf has written a very interesting article that touches on this subject: http://thedailywtf.com/Articles/Programming-Sucks!-Or-At-Least,-It-Ought-To-.aspx

Basically he says that many of the work we do is under-challenging or boring, which leads smart programmers like yourself to overcomplicate in design in order to keep enjoying the work. Is that familiar to you? I certainly have been guilty of this.

The conclusion would be that it is in our nature to look for challenges, but that we want to generate a culture in which writing challenging code and building software are basically two different things.

I myself find that work needs at least some challenge and enjoyment, because without these it's very hard to keep focused and do the work right. So I would say that we want to create a culture in which challenging code is a part of software development, as long as it is well tested and actually gets the job done without overcomplication. And I can thoroughly enjoy software that is concise and to the point way more than software that is over engineered.


答:
They support you when you say NO

One of the most demotivating trait in a manager is the lack of courage to standup for his people and always bow in front of his own boss even if it means affecting the product or the team.

Title: What traits do the best managers you've worked for have in common?

Body:
I have been listening to Scott Hanselman and Rob Conery's podcast, This Developer's Life.

In the latest episode, they discuss personality traits:

1.0.4 - Being Mean.

What makes people mean in our
  industry? What about aggressive?
  Confident? What's the difference?
  Would you rather have a drill sergeant
  for a boss, or a zen master? We talk
  to Cyra Richardson and Giles Bowkett.

It got me thinking, what traits did the best managers you've worked for have in common?

EDIT: Just to clarify, as there have been a few close votes, I'm interested in whether there are traits common to managers of developers that are not necessarily those traits that a manager of some other profession requires.

As for whether this is programming related or not, well I don't want to ask this question on a site that isn't about programming because, frankly, I'm not as interested in what people who make cans of soup for a living want from their managers as I am interested in what developers want from their managers.


问:
Software Manual - Where to start
Are there any software packages out there for generating a nice looking users manual for small projects?  I'm not talking about source documentation.  I want to create an end users manual that doesn't look like I spent 20 mins in Microsoft Word.  </p>

答:
I have used Asciidoc for years. I have created a 400 page manual that provides step by step instructions on basically everything my program does (it does a lot but the screen captures tend to expand the page count). Basically you create your documentation in a plain text markup which is quite easy to get the hang of. The big advantages of the plain text markup is that it can be easily added to your version control repository so each version of the manual matches the version of software. It is also easier for other developers to add documentation about new features and bug fixes. In addition, you can create multiple output formats (pdf, chm, html, xml, plain text, etc.) from one set of source files.

I have also found that you can easily compile smaller pieces of the manual. For example I have a section that details the changes and bug fixes for every version that I have released. I had one client ask to see this before purchasing and it was quite simple to write a small configuration file that pointed to the proper sections and then generate a pdf of the release notes only (along with a nice cover page, table of contents, page number, etc.). That has also saved me quite a bit of work when management has asked for that as well - there is nothing like showing them a lot of pages of actual work.

The only issue I have is that it is a little difficult to get running on windows as you have to use cygwin to make it work. There is also Sphinx, on the python side that uses restructured text as the markup language and can do much the same thing. I am planning to test it out on another software project I am involved with. The reason, I am hoping it will be a simpler setup process on windows.

Title: Software Manual - Where to start


问:
Android or iPhone application collecting payments
I'm starting to study a project that mainly will allows users to make payments from their iPhones or Androids. Since I don't have e-commerce experience and also I have never owned a smartphone, I ask you to give me some orientation on what is important when heading this kind of project.

What is making me doubt

Is it possible to do this without Apple or Google refusing my app or charging my transactions with amounts similar to 30%?

Is google checkout an alternative to paypal or am I getting this wrong?

For debit card payment, what are the most common payment services in the US nowadays?

How high is the technical complexity of that application? Is it very different to do it for iPhone and do it for Android?

What I already know:

The payments have nothing to do with the application itself; this is not an in-app scenario.

We would like to go live with Android and iOS, but it would be acceptable to start with only one of them.

No credit card information will be stored by the application; a payment gateway like PayPal should by in charge of the actual money movement.

Why am I asking this?

Someone is asking me to develop an iOS or Android application for allowing his cutomers to add money into their customer cards.

Details of the application requeriment:

This service would be available only in the US.

The application will cost a fix amount to download.

It is initially required for iOS or Android but off course, bb's and why not wp7 could need to be supported soon.

Searching Stack Overflow and then the web I came to the feeling of Apple and Google being restrictive to this kind of applications, I also would like to know if it is true.

Example

I've found Starbucks' mobile app to be a very good example of what I need as the link says: To reload the card, customers can link it to a debit, credit card or PayPal account

I wonder if doing that is possible for any application or if there is a commercial agreement between Starbucks and Apple behind.

答:
you can provide payment support in two ways ,

step 1 :By Inbuilt API's from Payment Comps like Paypal,CHASE etc.

Its easy & also security concerns are managed by provider & no need to write server side code but it is limited to certain features , where we can't customize it to our needs to a max level

step 2 : you need a create a server side API like iPhone - Server API - Payment System - got back response - pass result to iphone through server api as status.

where step 2 will needs server side support like php or any other & its highly customizable but security concerns we need to manage ourself.

Regarding App Submission , i dont see any rigorous measures in both plateform as we have submitted nearly 10 ecommerce apps.

so decide which kind of you want to use.

There's still a lot but i m not aware of them - still learning ....


问:
How should I react to diminishing application performance?
Sometimes it comes to me that the biggest challenge for an engineer when he find his application getting worse in performance is lack of enough information.

Imagine that you go through the weekly performance report from your application's access log, and find you get much lower response times from July. All you can do is to pray for it not to get worse the next time.

答:
If you do not have sufficient information, you need to collect the information you need.  If you do not have a hard goal for what is satisfactory performance, you need to get one (otherwise you cannot tell if you reached the goal or not):

Information is typically collected in several ways:

Profiler attached.   Collects lots of information and can help you pinpoint slow spots.

Logging steps.  You write your own log statements.  The log entries get timestamped and you can look at the steps you take to identify what is "too slow" for you.  Do it in a machine readable way so you can post proces to gather additional information.

Database surveillance.  What queries are being done?  How fast are they?  Is it fast enough according to your performance goal?

Continue refining your knowledge of the problem and find places to improve until you've reached your goal.


答:
Without more details on the type and nature of your application, it is hard to give more than general hints:

Measure, measure, measure. Profile your app to detect the performance bottlenecks. Then measure again after any changes, to verify the effects of the changes.

Identify what changed from June to July, which can cause the observed performance degradation. Do you have more users? More transactions? More accumulated data in the DB? More network traffic? (Of course you can have more than one of these at the same time.) This may also help identifying where the weak spots of your app are. Or they may even point you to external entities, like a web service you depend on, which slowed down, making your app wait longer.

Define "slow" and "fast enough", in agreement with your users. Do they primarily care about throughput (average amount of requests/data handled per time period) or latency (average response time)? These require different kinds of optimization.

Title: How should I react to diminishing application performance?

Body:
Sometimes it comes to me that the biggest challenge for an engineer when he find his application getting worse in performance is lack of enough information.

Imagine that you go through the weekly performance report from your application's access log, and find you get much lower response times from July. All you can do is to pray for it not to get worse the next time.


问:
Relation between BDD and TDD
What is the relation of BDD and TDD?

From what I understood BDD adds two main things over TDD: tests naming (ensure/should) and acceptance tests. Should I follow TDD during development by BDD? If yes, should my TDD unit tests be named in the same ensure/should style?

答:
What is the relation of BDD and TDD?

They are the same thing.

From what I understood BDD adds two main things over TDD: tests naming (ensure/should)

That's not really something BDD "adds". It's just a different convention that is meant to make it easier to teach and understand TDD.

The people who created BDD were all teaching TDD, and they noticed that the hardest thing to understand was that TDD has absolutely nothing to do with testing. Once students got over that hurdle, it went much easier for them. But, it's very hard to divorce yourself from thinking about testing, when the word "test" (or related terminology such as "assert") appears practically everywhere. So, they switched some words around.

But it's only the words! There is no actual difference between TDD and BDD.

and acceptance tests.

Acceptance tests are just as important a part of TDD as they are of BDD. Again: there is no difference between TDD and BDD: TDD done right is BDD, BDD is TDD done right.

Title: Relation between BDD and TDD


问:
Is slower performance of programming languages, really, a bad thing?
Here's how  I see it.

There's machine code and it's all that computers needs in order to run something. Computers don't care about programming languages. It doesn't matter to them whether the machine code comes from Perl, Python or PHP. Programming languages don't serve computers. They serve programmers.

Some programming languages run slower than others but that's not necessarily because there is something wrong with them. In many cases, it's because they do more things that programmers would otherwise have to do (i.e. memory management) and by doing these things, they are better in what they are supposed to do - serve programmers.

So, is slower performance, of programming languages, really, a bad thing?

答:
Someone commented that "Customers love software that performs to requirements and within budget". Well, this is true - but it has quite a bearing on slow software, and that, almost by definition means slower programming languages (and frameworks) and algorithms, and configuration. A slow programming language is possibly the most important part of all the above simply because its a foundation from which you will find it most difficult to change. If you use an Oracle DB and need more perf, you can optimise the tables/index/etc. Easy. If you have a poor algorithm in your code, you can write different code. If your framework is slow, you can replace it - that's not so easy but it is do-able without re-writing everything. If your language is too slow, you have to practically start again.

See Facebook for the hassle they went into to make PHP work fast enough when they needed to scale.

For the rest of us, 'non functional performance requirements' are often written into specifications, especially for scalable web apps. Fail to fulfill the 'page must be displayed to the user within 2 seconds of request" and you lose the contract (or pay penalties). So, yes customers love software that performs to reqs - and those reqs will say it has to be fast. (you may not care how long the users spend staring at the hourglass, but the customer sure does - its a huge cost).

For an example, at a large call centre I was told that they'd determined that for every second you could save on the call-taking process, 1 calltaker could be 'downsized'. That's real money suddenly, and a huge incentive for the bosses to get faster, efficient and more usable, software.

There's a lot of time spent worrying about programmers churning out code as fast as possible (and then unit testing and refactoring all the time, lol). I have found that this isn't as much of a factor as people think it is - if you're an expert in your language, you can code it much faster than if you're inexperienced. So a expert C++ dev can write code faster and more accurately than a novice PHP dev. So I think becoming an expert is more important than choosing an 'easy' language and this is why I dislike the cult of the 'rewrite in the cool, new stuff' that seems to be everywhere today.


答:
BDD adds a cycle around the TDD cycle.

So you start with a behaviour and let that drive your tests, then let the tests drive the development. Ideally, BDD is driven by some kind of acceptance test, but that's not 100% necessary. As long as you have the expected behaviour defined, you're ok.

So, let's say that you're writing a Login Page.

Start with the happy path:

```<code>Given that I am on the login page
When I enter valid details
Then I should be logged into the site
And shown my default page
</code>```

This Given-And-When-And-Then-And syntax is common in behaviour-driven development. One of the advantages of it is that it can be read (and, with training, written) by non-developers -- that is, your stakeholders can view the list of behaviours you have defined for successful completion of a task and see if it matches their expectations long before you release an incomplete product.

There is a scripting language, known as Gherkin, which looks a lot like the above and allows you to write test code behind the clauses in these behaviours. You should look for a Gherkin-based translator for your usual development framework. That's out of the scope of this answer.

Anyway, back to the behaviour. Your current application doesn't do this yet (if it does then why is someone requesting a change?), so you're failing this test, whether you're using a test runner or simply testing manually.

So now it's time to switch to the TDD cycle to provide that functionality.

Whether you're writing BDD or not, your tests should be named to a common syntax. One of the most common is the "should" syntax you described.

Write a test: ShouldAcceptValidDetails. Go through the Red-Green-Refactor cycle until you're happy with it. Do we now pass the behaviour test? If not, write another test: ShouldRedirectToUserDefaultPage. Red-Green-Refactor til you're happy. Wash, rinse, repeat until you fulfil the criteria set out in the behaviour.

And then we move on to the next behaviour.

```<code>Given that I am on the login page
When I enter an incorrect password
Then I should be returned to the login page
And shown the error "Incorrect Password"
</code>```

Now you shouldn't have preempted this to pass your earlier behaviour. You should fail this test at this point. So drop back down to your TDD cycle.

And so on until you have your page.

Highly recommend The Rspec Book for learning more about BDD and TDD, even if you're not a Ruby developer.

Title: Relation between BDD and TDD

Body:
What is the relation of BDD and TDD?

From what I understood BDD adds two main things over TDD: tests naming (ensure/should) and acceptance tests. Should I follow TDD during development by BDD? If yes, should my TDD unit tests be named in the same ensure/should style?

Body:
BDD adds a cycle around the TDD cycle.

So you start with a behaviour and let that drive your tests, then let the tests drive the development. Ideally, BDD is driven by some kind of acceptance test, but that's not 100% necessary. As long as you have the expected behaviour defined, you're ok.

So, let's say that you're writing a Login Page.

Start with the happy path:

Given that I am on the login page
When I enter valid details
Then I should be logged into the site
And shown my default page

This Given-And-When-And-Then-And syntax is common in behaviour-driven development. One of the advantages of it is that it can be read (and, with training, written) by non-developers -- that is, your stakeholders can view the list of behaviours you have defined for successful completion of a task and see if it matches their expectations long before you release an incomplete product.

There is a scripting language, known as Gherkin, which looks a lot like the above and allows you to write test code behind the clauses in these behaviours. You should look for a Gherkin-based translator for your usual development framework. That's out of the scope of this answer.

Anyway, back to the behaviour. Your current application doesn't do this yet (if it does then why is someone requesting a change?), so you're failing this test, whether you're using a test runner or simply testing manually.

So now it's time to switch to the TDD cycle to provide that functionality.

Whether you're writing BDD or not, your tests should be named to a common syntax. One of the most common is the "should" syntax you described.

Write a test: ShouldAcceptValidDetails. Go through the Red-Green-Refactor cycle until you're happy with it. Do we now pass the behaviour test? If not, write another test: ShouldRedirectToUserDefaultPage. Red-Green-Refactor til you're happy. Wash, rinse, repeat until you fulfil the criteria set out in the behaviour.

And then we move on to the next behaviour.

Given that I am on the login page
When I enter an incorrect password
Then I should be returned to the login page
And shown the error "Incorrect Password"

Now you shouldn't have preempted this to pass your earlier behaviour. You should fail this test at this point. So drop back down to your TDD cycle.

And so on until you have your page.

Highly recommend The Rspec Book for learning more about BDD and TDD, even if you're not a Ruby developer.


问:
How do we handle Categories in database schema and model classes
I am trying to develop an ecommerce solution but stuck on the categories management issue and don't know how to proceed further.

See, A category will have a parent category, which in-return can also point to another parent and so on, until the root category is reached. I tried to design the following database schema,

Please tell me if that's right ?

OR Is there any tutorial on categories and parent categories that can help me understand this scenario better ?

答:
Classic DB answer: "it depends"

A question:

Are you allowed to add an item to any category, whether parent of not?

That is, can a category have either sub-categories or items, but not both?

If yes, your current table is OK

If no, then have a separate self referencing CategoryParent table. Your current category becomes a child of that.

This constrains your items a lowest level category, but allows a hierarchy of categories.


问:
Should you write good documentation and clean code to increase the "Bus Factor"?
One of the main goals of software development companies is to increase their Bus factor This is also advocated in a talk that was organized by Google.

That means that you should code and document everything in a way that if you're run over by bus tomorrow, the project can still continue. In other words, you should make yourself easily replaceable by another programmer with a similar skill set to yours.

Being replacable, isn't that against the interest of a developer? In the book, 48 laws of power Rule 11 states that you should try to keep people dependent on you, in order to gain power, which then translates into monetary rewards.

Apart from the scenario, where you need some documentation for yourself in order to continue a project after 6 months of pause, there seems to be a clear conflict of interest here between the developer and the software company.

So as a programmer, should you really write excellent documentation and easily readable code for everyone; or should you write code and documentation in a way that it does the job and you yourself can understand it, but another person may have trouble understanding it?

答:
You should strive to become irreplaceable not by writing code noone else understands, but by gathering more experience and knowledge than others. The former way makes you a developer everyone tries to avoid working with, as they will fear and loath maintaining code you wrote. The latter way you become a sought out team member, whom managers want to have in their team.

In my experience writing clean, well documented (and preferably self-documenting) code has always paid off. In fact I took almost every opportunity to help and teach others (as well as learning from them when they knew something better), and I hardly ever felt in danger of getting replaced by someone less capable than me. In fact, this usually helped the whole team work better and solve problems faster, which is every manager's dream - and a sensible manager doesn't want to replace members of a good team.


答:
Being replacable, isn't that against the interest of a developer?

Depends what the interests of that developer are. If you are one who wants to stick it out in a single job for your entire career, be completely indispensable to a company that rewards incompetence and make good money then yes, absolutely.

But what happens when the company crashes, probably because they hired too many people like that? Where are you going to go next? What when they ask you why you stayed in the same job for 15 years? And so on.

Now look at it a different way: How many developers have lost their jobs by being someone who writes code that anyone can read?

The only likelihood of that happening is if the company is in trouble and making people redundant. If that is happening, you're better off getting out, and you'll be very well prepared for the upcoming interviews. Plus your conscience will be completely free -- you won't be leaving behind inexplicable code which you wrote for your own self-gain.

I don't know what kind of person you are, but that serves my interests better.

Personally, I think one of my greatest strengths is in automating my own job. What do you think a company tends to think when I've become surplus to my own requirements? Do they think "ok, we'll get rid of him now" or do they think "why don't we move him into another role and let him do it again"?

Title: Should you write good documentation and clean code to increase the "Bus Factor"?

Body:
One of the main goals of software development companies is to increase their Bus factor This is also advocated in a talk that was organized by Google.

That means that you should code and document everything in a way that if you're run over by bus tomorrow, the project can still continue. In other words, you should make yourself easily replaceable by another programmer with a similar skill set to yours.

Being replacable, isn't that against the interest of a developer? In the book, 48 laws of power Rule 11 states that you should try to keep people dependent on you, in order to gain power, which then translates into monetary rewards.

Apart from the scenario, where you need some documentation for yourself in order to continue a project after 6 months of pause, there seems to be a clear conflict of interest here between the developer and the software company.

So as a programmer, should you really write excellent documentation and easily readable code for everyone; or should you write code and documentation in a way that it does the job and you yourself can understand it, but another person may have trouble understanding it?


答:
If you don't spend 5 minutes writing up some quick documentation then you're going to spend an hour re-reading and explaining it to people when they need to use your code.

Even worse could be spending days searching for a new job because your boss found out you weren't writing maintainable code.


答:
Being replacable, isn't that against the interest of a developer?

I hate to break it to you, but everyone is replaceable. Sure, sometimes it may be a slight challenge to replace you (if you're experienced and bright enough), but it's light years from impossible.

The way to truly be a valuable commodity to your employer (not just current employer, but any employer) is to demonstrate the ability to write code that easy to grok by anyone reading the code (little ramp up time to work with it) and document the code (anyone can get a high level overview of your systems without digging into code).

Actually being good at code documentation is a tough quality to come by these days, so that alone will help set you apart from others.

Clean and well documented code is also worthy of being put on a resume (at least, tangible outcomes of it, i.e. "we were able to bring n new developers on with minimal ramp up and assistance due to my documentation), where being sneaky about making yourself "irreplaceable" isn't.


答:
You do not want to be irreplaceable. You do not want to make people feel depending on you, you want them to appreciate you. Generally, you want to stay far away from people, who believe even half of the laws of power should be applied to relationships (professional or personal).

These rules are an instruction set on how to successfully establish a win-lose situation. What you want, is a win-win situation.

As soon as people start feeling, you're trying to push them on the losing side of a win-lose situation, they will fight back. Attempts to establish win-lose situations often end up in a lose-lose outcome, because you're effectively wasting resources on getting your partner into a losing position, instead of investing them into the overall success of your partnership.

If you do this with your employers, they will try to force measures on you, to reduce your knowledge monopoly. Mostly, these will be ridiculous guidelines on how you must do your work and will thereby turn your work life into a living hell. Also, they will call you at 3 o'clock in the night when something breaks, because you're the only person, who can fix it. Trying to exploit such situations as leverage is likely to backfire and cause you more trouble.

The graveyards are full of indispensable men.

  - Gaulle, Charles De

So cut the crap and do your work properly. If not for anything else, then for you, because you're likely to be the poor soul, who has to make some changes to the code 2 years from now.


答:
If you are going to manipulate organizations or people so transparently they'd better be stupid or in a jam that leaves them no other choice. A well run software development shop would look at your obscure code and missing documentation and simply fire you before you could do much damage. If they're poorly run, or unable to get any other developers to work for them, why would you want to have a sinecure with them?

PS Neither Mr. Greene nor Machiavelli actually accomplished much aside from writing books that tried to flatter would-be "hard men" of the time. Take their advice with a grain of salt.


答:
(assuming production code)

I tend to go a bit further. I've written about making programs "idiot proof", but I don't always qualify that: I write a lot of code that other people will not see or work with (at least, that is the expectation when it is written). I am the idiot I am trying to defend myself from in that case. It's a good thing when your program detects problems for you, and the problem has been simplified so much that it's quite obvious that there is an error, and its origin. The truth is, implementation details are obvious when you write a program (unless you are implementing it prematurely), but they should be abstracted and error resistant for clients (even when module locality exists). The reason is that programs become very complex. Sometimes you can separate problems, but not all the time. If you keep your components very strict, simple, well encapsulated, and idiot proof, they do tend to scale well and most defects are detected before they are shipped. It's easier to reuse, and you have more confidence and an easier time reusing the programs, As well, those complex programs that you write only become more complex (even to you) after some time away from the program. When you read it in 6 months, it can take an absurd amount of time to understand and debug compared to the idiot proof version. If a component introduces a breaking change, it can go undetected for a long time otherwise. Programs are complex; you can't escape that reality, but you can make it idiot proof, which will make your life a lot easier when something goes wrong or when it must be reused or altered. Therefore, the idiot proof approach means that your software can be understood, reused, or maintained by your juniors or people newer on the team as well (not just somebody as good/experienced as you). Replacement is a separate concern: If people love working with your programs, you're doing a good job -- don't worry about replacement. Sure, I could come up with scenarios where unintelligible programs could save your job, but writing a good program others can use and maintain is clearly the lesser evil (look at the others' resopnses). If I catch myself writing something that is not idiot proof, I try to fix that.

Apart from the scenario, where you need some documentation for yourself in order to continue a project after 6 months of pause, there seems to be a clear conflict of interest here between the developer and the software company.

You really have no idea what you were thinking some of the time when you revisit dormant implementations. When you are really experienced, then the problem is simpler because you can rely more on established methodologies or approaches which you use. That, however, also assumes these methodologies are invariant. Even though the documentation may lax, you still have to be defensive in your implementations (e.g. you know better than to pass NULL in this scenario -- test that condition).

So as a programmer, should you really write excellent documentation and easily readable code for everyone; or should you write code and documentation in a way that it does the job and you yourself can understand it, but another person may have trouble understanding it?

I recommend the idiot proof approach, which is even clearer and more error resistant than the bus factor approach. Write your programs and documentation such that it is easily understood by somebody external to the project -- it's good for you too. Doing so will increase your value to your company and team, they will not want to replace you.


答: If you are irreplaceable, you can't be promoted.</p>


答:
Excellent documentation will eventually be obsolete with refactoring/evolutions, and keeping it up to date is really time consuming.

Clean code + unit test > excellent documentation


问:
DB centric iPhone app question
The iPhone app i have an idea for deals with processing of the data stored as part of Oracle database at work. It'll be an interface to a dynamic set of data that is updated tens of thousands of time a day. Each time you look, results are likely to be different.

That being said, the company i work for does not have an enterprise appstore, which (as i understand it) means that i would have to publish my app onto the regular appstore with some kind of access key.

Q1. Is this a common practice, given no company specific app store
  exists?

I wonder if any of the cocoa API allows for east access and synchronization with Oracle databases.

Q2. If you know of one and can point me in the right direction, i'd be
  very grateful.

Is there anything else i should know when dealing with such a problem? Security is obviously a concern, the data will likely be of absolutely no interest to an outsider, but then again, we do want to be as prudent as we can be.

Please let me know

答:
I understand you're asking about native iOS app, but...

If you don't need to take advantage of any iPhone/iPad specific hardware, and access to the information is the most important, I would really consider spending much less time on this and building a solid mobile web site (or "web app").

If you were to build a native iOS app, you'll have to write some kind of networking layer to let the phone interface with your Oracle db anyway... and you'll still need to implement the same security practices (SSL, user accounts, etc).

Building it as a web app would remove all of your AppStore / approval concerns, while also ensuring that it'll work from any web-enabled access point (android devices, tablets, browsers, etc).

Title: DB centric iPhone app question


问:
To Domain or not to Domain
The SQL92 and SQL99 standards define CREATE DOMAIN DDL constructs. Not all databases support this, or have a different name for it (SQL Server has User Defined Types, for example).

These allow one to define a constrained data-type to be used in their database, to simplify and enforce rules pertaining to the allowed values. Such a data-type could be used in column declarations, in inputs and outputs to stored procedures and functions etc...

I would like to know:

Do people actually use domains in their database designs?

If so to what extent?

How useful are they?

What pitfalls have you encountered?

I am trying to asses the viability of using these in future database development.

答:
As usual...

It Depends

Do you have a domain entity used in more than one place that supporting natively would otherwise require considerable effort and/or redundant constraints and behaviors?

If so, domain away. If not, don't bother.

I've found it necessary to create a user-defined type in SQL Server exactly once, based on the above heuristic. I don't even remember what it was any more - but it saved more work than it caused.

Title: To Domain or not to Domain


答:
Your table design for handling hierarchical categories is correct.  This is a general purpose design which can handle situations where there is no way to predict exactly how deep the tree will be along any one branch.

What you might want to consider in your design is whether you are going to make any amendments to assist you with the practicalities of navigating hierarchical data in a relational DBMS.

In my answer to this question I discussed the category hierarchy design.

In my answer to this other question I provide some detailed explanation around a practical implementation that makes hierarchical data much easier to work with - at least on the reading side - using concepts known as nested sets and visitation numbers.

Title: How do we handle Categories in database schema and model classes

Body:
I am trying to develop an ecommerce solution but stuck on the categories management issue and don't know how to proceed further.

See, A category will have a parent category, which in-return can also point to another parent and so on, until the root category is reached. I tried to design the following database schema,

Please tell me if that's right ?

OR Is there any tutorial on categories and parent categories that can help me understand this scenario better ?


问:
Does test-driven development force me to follow SOLID?
I hear a lot from TDD practitioners that one of TDD's advantages is that it forces developers to follow SOLID principles (Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion). But as for me it is enough to just write some tests (unit test primarily) to understand it is important to follow SOLID (and thus create testable architecture).

Does TDD force developers to follow SOLID more actively than just writing unit tests?

答:
No

TDD can make it easier to follow good practices because of the continuous refactoring, but it doesn't force you follow any principle.  All it does is make sure the code you write is tested.  You can follow whatever principles you like when writing code to satisfy the test; or no principles at all.


答:
Being replacable, isn't that against the interest of a developer?

You are right, but I think you misunderstood the meaning of replaceable. I could find a 1000 developers that write hectic code, undocumented that can quickly turns into an unmaintainable mess.

A developers that produce not only steady programs, but also clean code, informative documentation and ensures the continuity of the project, that's not only irreplaceable, that's priceless.


答:
First of all, TDD does not strictly force you to write SOLID code. You could do TDD and create one big mess if you wanted to.

Of course, knowing SOLID principles helps, because otherwise you may just end up not having a good answer to many of your problems, and hence write bad code accompanied by bad tests.

If you already know about SOLID principles, TDD will encourage you to think about them and use them actively.

That said, it doesn't necessarily cover all of the letters in SOLID, but it strongly encourages and promotes you to write at least partly SOLID code, because it makes the consequences of not doing so immediately visible and annoying.

For example:

You need to write decoupled code so you can mock what you need. This supports the Dependency Inversion Principle.

You need to write tests that are clear and short so you won't have to change too much in the tests (which can become a large source of code noise if done otherwise). This supports the Single Responsibility Principle.

This may be argued over, but the Interface Segregation Principle allows  classes to depend on lighter interfaces that make mocking easier to follow and understand, because you don't have to ask "Why weren't these 5 methods mocked as well?", or even more importantly, you don't have a lot of choice when deciding which method to mock. This is good when you don't really want to go over the whole code of the class before you test it, and just use trial and error to get a basic understanding of how it works.

Adhering to the Open/Closed principle may well help tests that are written after the code, because it usually allows you to override external service calls in test classes that derive from the classes under test. In TDD I believe this is not as required as other principles, but I may be mistaken.

Adhering to the Liskov substitution rule is great if you want to minimize the changes for your class to receive an unsupported instance that just happens to implement the same statically-typed interface, but it's not likely to happen in proper test-cases because you're generally not going to pass any class-under-test the real-world implementations of its dependencies.

Most importantly, SOLID principles were made to encourage you to write cleaner, more understandable and maintainable code, and so was TDD. So if you do TDD properly, and you pay attention to how your code and your tests look (and it's not so hard because you get immediate feedback, API and correctness wise), you can worry less about SOLID principles, in general.

Title: Does test-driven development force me to follow SOLID?

Body:
I hear a lot from TDD practitioners that one of TDD's advantages is that it forces developers to follow SOLID principles (Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion). But as for me it is enough to just write some tests (unit test primarily) to understand it is important to follow SOLID (and thus create testable architecture).

Does TDD force developers to follow SOLID more actively than just writing unit tests?


答:
Yes:
TDD is mainly a good design technique (and only secondary a testing technique). It helps very much to achieve the solid principles, though (pathological) examples of TDD with a lot of code smells are still possible.

The connection between TDD and the solid principles are disputed (with the conclusion above) in this great hanselminute podcast named "Test Driven Development is Design - The Last Word on TDD".


答: It isn't too hard to fix the enterprise app store -- if you can afford oracle, you can afford the $300 jump in dev program level. I'd just upgrade my program.</p>

Title: DB centric iPhone app question

Body:
The iPhone app i have an idea for deals with processing of the data stored as part of Oracle database at work. It'll be an interface to a dynamic set of data that is updated tens of thousands of time a day. Each time you look, results are likely to be different.

That being said, the company i work for does not have an enterprise appstore, which (as i understand it) means that i would have to publish my app onto the regular appstore with some kind of access key.

Q1. Is this a common practice, given no company specific app store
  exists?

I wonder if any of the cocoa API allows for east access and synchronization with Oracle databases.

Q2. If you know of one and can point me in the right direction, i'd be
  very grateful.

Is there anything else i should know when dealing with such a problem? Security is obviously a concern, the data will likely be of absolutely no interest to an outsider, but then again, we do want to be as prudent as we can be.

Please let me know


问:
Why is Mercurial considered to be easier than Git?
When looking at comparisons, it seems to me that there could be a 1:1 mapping between their feature sets. Yet, an often cited statement is that "Mercurial is easier". What is the basis of this statement? (if any)</p>

答:
There are a few things that IMO are likely to put new users off Git:

The Git culture is more command-line centric. While both tools do tend to focus too much on the command line (as I've said several times, command line instructions may be powerful and more fluent, but they are not a good marketing strategy) this is much more the case with Git. Whereas Mercurial has a de facto standard GUI tool in TortoiseHg, which is even the default download option for Windows users on the Mercurial homepage, Git has several competing GUI front ends (TortoiseGit, Git Extensions, gitk, etc) which aren't well advertised on the Git website, and which are all a complete eyesore anyway. (Black text on red labels? C'mon, TortoiseGit, you can do better than that!) There's also a much more pervasive attitude in the Git community that people who use GUI tools are not proper software developers.

Git has several out-of-the-box defaults that make perfect sense to advanced users, but are likely to be surprising if not intimidating to new users. For instance, it is much more aggressive about automating tasks such as merging (for example, git pull automatically merges and commits where possible). There is a case for fully automated merges, but most inexperienced users are terrified of merging, and need to be given the opportunity to gain confidence in their tools before unleashing their full power on their source code.

Documentation and inherent complexity:

```<code>$ hg help log | wc -l
64
$ git help log | wc -l
912
</code>```

Body:
There are a few things that IMO are likely to put new users off Git:

The Git culture is more command-line centric. While both tools do tend to focus too much on the command line (as I've said several times, command line instructions may be powerful and more fluent, but they are not a good marketing strategy) this is much more the case with Git. Whereas Mercurial has a de facto standard GUI tool in TortoiseHg, which is even the default download option for Windows users on the Mercurial homepage, Git has several competing GUI front ends (TortoiseGit, Git Extensions, gitk, etc) which aren't well advertised on the Git website, and which are all a complete eyesore anyway. (Black text on red labels? C'mon, TortoiseGit, you can do better than that!) There's also a much more pervasive attitude in the Git community that people who use GUI tools are not proper software developers.

Git has several out-of-the-box defaults that make perfect sense to advanced users, but are likely to be surprising if not intimidating to new users. For instance, it is much more aggressive about automating tasks such as merging (for example, git pull automatically merges and commits where possible). There is a case for fully automated merges, but most inexperienced users are terrified of merging, and need to be given the opportunity to gain confidence in their tools before unleashing their full power on their source code.

Documentation and inherent complexity:

$ hg help log | wc -l
64
$ git help log | wc -l
912


答:
Assuming that the column CategoryParent is the Foreign Key referring to category_id, and assuming that the CategoryParent column ALLOWS NULL, you are OK.

It is a good to append Foreign Key columns with _fk so that it is clear. Also make sure that the CategoryParent has the exact datatyp as the primary key.

Blockquote
   Is there any tutorial on categories and parent categories that can help me understand this scenario better ?
  Blockquote

Your case is a typical self-referencing or hierarchical relationship. This case exists in many cases other than categories, for example, in organization charts.

A similar example can be found here: DataModeling


答: I document what little code I write, not so that others can read it, but so that I can read it in 3 months time! It's about making maintenance easier. If you are responsible for code you wrote, and you can't fix bugs that show up later down the line, then you'll want it to be well documented... It's pretty irrelevant how replaceable you are if you aren't able to do your job!


答:
The negative responses aren't too surprising, given the number of better-than-average programmers this site attracts. Talented people don't generally need to resort to these kinds of security-through-obfuscation tactics. But I worked at a Fortune 500 automotive supplier with a few not-so-talented developers who had carved out little fiefdoms for themselves, which they zealously guarded by creating copious amounts of documentation for the horrendous interfaces they had designed.

One guy's whole job was maintaining the code for a module that bridged two entirely separate subsystems, allowing modules on each system to communicate via a UART. Basically, it was Serial Programming 101. Instead of just creating a general interface that looked something like this:

```
  int sendData(int targetModule, void *data, size_t byteCount);
  int recvData(int sourceModule, void *data, size_t maxBytes);
```

he created separate opcodes for every single message that any two communicating modules might want to send to eachother. Which meant his module needed to know about every message, and needed to be updated whenever a message was added or changed. Talk about inappropriate intimacy!

The thing is, this guy kept a Word doc neatly listing all the opcodes/messages, and diligently updated it as necessary. It became his whole job. A few times a week, he'd send out a new revision to all the people unfortunate enough to have him on their critical path. And this was seen as 'professional', since management loved seeing documentation.  Kinda makes me weep for the automotive industry.

I guess my point is: sometimes writing documentation can, in fact, protect mediocre programmers. Managers often can't tell the difference between a good design and a bad one, and many are forced to make technical decisions with limited information. It's incredibly stressful for them. Seeing a Word doc with dozens of neatly formatted tables can be very comforting—even if what it describes is a fundamentally bad idea.

Body:
The negative responses aren't too surprising, given the number of better-than-average programmers this site attracts. Talented people don't generally need to resort to these kinds of security-through-obfuscation tactics. But I worked at a Fortune 500 automotive supplier with a few not-so-talented developers who had carved out little fiefdoms for themselves, which they zealously guarded by creating copious amounts of documentation for the horrendous interfaces they had designed.

One guy's whole job was maintaining the code for a module that bridged two entirely separate subsystems, allowing modules on each system to communicate via a UART. Basically, it was Serial Programming 101. Instead of just creating a general interface that looked something like this:

  int sendData(int targetModule, void *data, size_t byteCount);
  int recvData(int sourceModule, void *data, size_t maxBytes);

he created separate opcodes for every single message that any two communicating modules might want to send to eachother. Which meant his module needed to know about every message, and needed to be updated whenever a message was added or changed. Talk about inappropriate intimacy!

The thing is, this guy kept a Word doc neatly listing all the opcodes/messages, and diligently updated it as necessary. It became his whole job. A few times a week, he'd send out a new revision to all the people unfortunate enough to have him on their critical path. And this was seen as 'professional', since management loved seeing documentation.  Kinda makes me weep for the automotive industry.

I guess my point is: sometimes writing documentation can, in fact, protect mediocre programmers. Managers often can't tell the difference between a good design and a bad one, and many are forced to make technical decisions with limited information. It's incredibly stressful for them. Seeing a Word doc with dozens of neatly formatted tables can be very comforting—even if what it describes is a fundamentally bad idea.


答:
If you're the single point of failure, your client (or employer) will probably try to replace you; there's always a point where it's less costly to replace software than maintain it, no matter how essential it seems. There is a reason IT is one of the most outsourceable professions.

On the other hand, being replaceable gives you several priceless benefits:

being able to take vacation

not being on call

freedom to leave and work on a new and exiting project


问:
Module vs. Package?
Whenever I do from 'x' import 'y' I was wondering which one is considered the 'module' and which is the 'package', and why it isn't the other way around?

答:
A Python module is simply a Python source file, which can expose classes, functions and global variables.

When imported from another Python source file, the file name is treated as a namespace.

A Python package is simply a directory of Python module(s).

For example, imagine the following directory tree in /usr/lib/python/site-packages:

```<code>mypackage/__init__.py <-- this is what tells Python to treat this directory as a package
mypackage/mymodule.py
</code>```

So then you would do:

```<code>import mypackage.mymodule
</code>```

or

```<code>from mypackage.mymodule import myclass
</code>```

Title: Module vs. Package?

Body:
A Python module is simply a Python source file, which can expose classes, functions and global variables.

When imported from another Python source file, the file name is treated as a namespace.

A Python package is simply a directory of Python module(s).

For example, imagine the following directory tree in /usr/lib/python/site-packages:

mypackage/__init__.py <-- this is what tells Python to treat this directory as a package
mypackage/mymodule.py

So then you would do:

import mypackage.mymodule

or

from mypackage.mymodule import myclass


问:
How much do i need to learn in order to get an entry level asp.net job?

Possible Duplicate:

  If you develop with ASP.NET, which other technologies do you use?

I'm currently learning C#, but I've noticed that there is a lot of demand for ASP.NET developers.

I purchased the book 'Beginning ASP.NET 4: in C#' by Wrox. I will start with that book and finish the web project provided in the book after I've learned C# fully.

I wanted to know how much C#, SQL, CSS, XHTML, Javascript and/or jQuery I need to learn in order to have a chance of getting an entry level ASP.NET job.

答:
Here is a good litmus test:

Can you build a cookbook application?

At its core, a cookbook application is a CRUD application. This means it includes web pages which:

C reate data.

R ead data.

U pdate data.

D elete data.

To do this (without an out-of-the-box CMS of course ;), you must implement a fair amount of C#, SQL, XHTML, and CSS. This would be a good start.

Once you can build a cookbook application, reflect a little bit more. Can you build an attractive cookbook application? That is, can you build an application which is both aesthetically pleasing and very usable?

To do this, you must implement a fair amount of javascript and/or jQuery.

If you can do this, then you are most certainly ready to interview for an entry-level ASP.NET position.

And when preparing for the interview, be ready to discuss your experience putting together the "cookbook application".


答:
Ah the old data growth issue...

I've seen this so many times:

Engineers builds shiny new project. When they test locally with a small set of dummy data, all is well.

Engineers rejoice in happiness :)

Project ships and data gets added, more users, more feature etc

Suddenly, the shiny application is not so shiny.

Engineers run around trying to profile/scale the application as an after thought

All this can be avoided if a little thought is placed at the beginning of the project.

Plan and think about data growth at the beginning of the project

Plan for some kind of data archiving

Plan for phased developments at key data volumes -> 1K, 10K, 100K, 10,000K

Plan to split data over services/dates/users/domains  etc


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
On the seventh day, God said, "Ship it!  We'll release patches later."

  — Josh Flachsbart

LastEditorDisplayName: Roger Pate


答:
Every "irreplaceable" computer professional I've had the misfortune of interacting with was replaced, in large part because they were trying to hold their employers' resources hostage. When I've had people who report to me tell me their time is to valuable to "waste" documenting, I replace them as soon as possible.

It would seem that if a prospective employee considers the 48 laws of power to be ethically or morally acceptable, then you would be better off without them.


问:
Do "Builder" static methods violate SOLID?
I am writing a class which consists mostly of data storage responsibilities. The context for the use of this class will, in general, be retrieving an array of objects of this type for display later. In light of that, I've created a static method, build_question_array(), which queries the database, instantiates the objects, and returns the array.  Does this violate the "SOLID" principle?

答:
Firstly, it does not obey the Open/Closed principle, because you won't be able to change anything at runtime in a static method.

I don't know whether it obeys the Single Responsibility principle, because I don't know whether it implements or delegates all of its work. If it implements it, it doesn't obey this principle.

EDIT: If that static method is inside the data structure's class, then it definitely does not obey SRP. The data class should not know or care about its various types of uses.

The Liskov Substitution principle isn't a factor since it's only one class, and it's a static method.

Interface Segregation also doesn't apply here.

Dependency Inversion is questionable here, because unless you can pass a delegate to this function or you're using a dynamic language, you're making every one of your clients depend on this sole implementation of this functionality.

So all in all, no, it doesn't.


答:
Can you run the software under a debugger or IDE?

Does the debugger have a "pause" button, or can you interrupt the program by typing Ctrl-C or some such keystroke?

If the program is getting slower and slower, it is doing at least one thing it doesn't need to be doing, and doing more and more of it.
Since it could be running in, say, 1/3 of the time it is currently running, that means 2/3 of the time it's doing things it doesn't need to do.
If you can take an X-Ray snapshot at a random point in time, chances are 2/3 you will see it doing the unnecessary thing(s).

Pause it while it's running, and examine what it's doing and why.
Especially examine every line of code on the call stack.
See if you can explain to yourself or someone else precisely why, in detail, that particular instant of time was being spent.
(You don't need to measure anything. You need to see if what it is doing can be gotten rid of.)

Repeat this a few times, like 5 or 10 times.

If what the program is doing at that point in time is not really necessary, and it is doing it on more than one time you stopped it, you have found something you can fix that will give you a big speedup, guaranteed.
The bigger the problem is, the quicker you will find it.

It's got nothing to do with requirements.

It's got nothing to do with measurements.

It's got everything to do with just "cleaning house", by this method.
Here's a fairly typical example.

Edit:
It's conventional wisdom to hear "measure measure" or "use a profiler".
What is not conventional is to hear how much speedup was achieved that way.
The few times I've heard the results of profiling, it was like 10% to 40%, or a factor of 1.1 to 1.4.
That's pretty anemic.
If a series of problems is found and fixed, there is a compounding effect, as shown in the example above.

P.S. Here's an example in C++ of a 3 order of magnitude speedup, containing all source code versions, copies of samples, and blow-by-blow description of how it is done. Some programmers have learned/discovered how to do this, but most have not. It couldn't be simpler.
To this day, I am still totally mystified that it is not common knowledge.
The only explanation I can see is that teachers don't work with programs large enough to require this kind of tuning.
What they do is teach gprof, for no other reason than that it's there, so they can teach it and move on.
What that does is infect their students with all the incredibly persistent myths of performance tuning, resulting in exactly the problems you describe.

P.P.S. In case the point isn't clear, any thread, whether it is alone or among thousands, has a certain minimum amount of work it absolutely must do to accomplish its purpose. Anything it is doing beyond that is taking extra time.
In the example linked to above (which is only one particular example - every app is different) these "bottlenecks" were removed:

33.3 % in push_back

11.1 % in out-of-line indexing

7.4 % in Add/Remove

31.9 % in new and delete

9.3 % in getting Nth list element

6.1 % in character I/O

Adding up to over 99%!
By removing them you get orders of magnitude speedup.

Now the kind of thing I hear is "Well sure, it's silly to do 2, and 6 wasn't necessary either."
Hey, nolo contendere, but what about the other four "bottlenecks"?
If you don't fix them, how much speedup do you get?

If you want serious speedup, whether or not a profiler is used, you have to clean out all of the problems !
Any ones missed will be the dominant speed limiters.


问:
What's the difference between static and dynamic binding?
We are learning about methods in class, and I am having trouble especially with the concept of static vs. dynamic.

Wikipedia says this:

Methods can be bound to a class at compile time (static binding) or to an object at runtime (dynamic binding).

Can anyone describe what they mean here?

答:
Here are a few links with examples:

Run time binding or compile time binding?

Overloading is compile-time binding

METHOD Overload Vs Overriding

C#, early and late binding


问:
How can I manage my ViewControllers in my game?
I'm building a very simple iOS game that doesn't require any fancy OpenGL; I'd like to stick with Core Graphics & Core Animation.  I'd like to make this a fullscreen game, and my question is of ViewController hierarchy + management:

It seems as though I should have two types of ViewControllers: Basic VCs for navigating between menu screens (ie. Settings, Main Menu, Level Select, etc.), and Gameplay VCs for managing all my UIViews and CALayers.

What's a good way to manage these? Is it best practice to have one hierarchy of VCs like a traditional UINavigationController-based app, covering the NavBar when I'm displaying a Game ViewController? Or instead should I be removing all other ViewControllers from the stack when I enter "game mode", and setting it as my window.rootViewController property? Any alternatives / downsides to continually resetting window.rootViewController?

My gut tells me the latter is better on resources+performance, but advice + direction here would be appreciated.

答:
i've seen both done, but i prefer the latter for memory considerations. before you switch the rootViewController, you need to fade out and removefromsuperview the previous, then addSubview the new one and fade it in, then finally set as root. this will mess with orientation unless you have only one VC on screen that inherits from UIViewController.

so, i'd have one main VC for handling all menu stuff, and separate out its subviews into classes that inherit from NSObject (there should only be one class on screen at a time that inherits from UIViewController - just google search for apple's recommendations for splitting a single screen into separate IB files/classes). when you go into game-mode, you call back to your app delegate.

next, your app delegate can handle the switch from menu-mode to game-mode. it fades out the previous VC, alloc/inits the game VC, fades in and does the removefromsuperview, etc on the previous VC.

you really only need two classes at the top level that your app delegate switches between: one menu VC (with subviews) and one game VC (with subviews).


问:
Reason behind multi-line declaration style?
I'm a little curious about the reason behind the Windows header file declaration styles.

When I read them, I see multi-line declarations such as the following:

```<code>WINBASEAPI
HANDLE
WINAPI
GetStdHandle(
    IN DWORD nStdHandle
    );
</code>```

What is the primary reason why they're not written as something like:

```<code>WINBASEAPI HANDLE WINAPI GetStdHandle(IN DWORD nStdHandle);
</code>```

i.e. in a single line?

答:
The reason is most likely a convention to enhance the readability of methods with many arguments or modifiers. When you're used to such a convention, it becomes easier to mentally parse the code. Also, when there're many arguments, you can avoid horizontal scrolling, an action which interrupts your mental parsing process a little.

In short: All for the sake of readability. Keep in mind that readability can be subjective at times.


答:
I am not one of the authors, but obviously they thought this style is more readable than putting everything on a single line. The perceived advantage of this style is that you can easily find the name, qualifiers and parameters of each function, because they are always at the same position (indent depth).

Moreover, when using code documenting tools such as Doxygen, this style allows one to append parameter doc comments on the same line right after each parameter, which (IMHO) makes them easier to read and maintain.

Even with the single line approach, often you need to break lines when they get too long. And in WinAPI files, looong function declarations are pretty common :-) So probably at some point they decided to have a "standard" approach as to where to break those lines.

Title: Reason behind multi-line declaration style?

Body:
I'm a little curious about the reason behind the Windows header file declaration styles.

When I read them, I see multi-line declarations such as the following:

```<code>WINBASEAPI
HANDLE
WINAPI
GetStdHandle(
    IN DWORD nStdHandle
    );
</code>```

What is the primary reason why they're not written as something like:

```<code>WINBASEAPI HANDLE WINAPI GetStdHandle(IN DWORD nStdHandle);
</code>```

i.e. in a single line?