问:
Learning good OOP design and unlearning some bad habits

Possible Duplicate:

  What books or resources would you recommend to learn practical OO design and development concepts?

I have been mostly a C programmer so far in my career with knowledge of C++. I rely on C++ mostly for the convenience STL provides and I hardly ever focus on good design practices. As I have started to look for a new job position, this bad habit of mine has come back to haunt me. During the interviews, I have been asked to design a problem (like chess, or some other scenario) using OOP and I doing really badly at that (I came to know this through feedback from one interview).

I tried to google stuff and came up with so many opinions and related books that I don't know where to begin. I need a good through introduction to OOP design with which I can learn practical design, not just theory.

Can you point me to any book which meets my requirements? I prefer C++, but any other language is fine as long as I can pick-up good practices.

Also, I know that books can only go so far. I would also appreciate any good practice project ideas that helped you learn and improve your OOP concepts.

答:
(IMO) There are not great books about software design. Many of the patterns books (I prefer the original, but have heard good things about some others) are pretty good to get the terminology and firm up concepts, but they should be used only after some practice. Without the practice first, programmers tend to over-apply design patterns or misunderstand what problems the patterns prevent.

As for practice problems, I recommend something you've already done for a start. Then you understand the domain and what it's supposed to do and can focus on design alone. Mostly though you just need to iterate. Design a program, implement it, see how it works (and doesn't). Make a new design with lessons learned for a new problem, repeat.

Program design is one of those things that ends up being more craft than science. Keep at it and you'll get progressively better.


答:
As for training, I suggest going to http://www.cleancoders.com/ and watching those. They cover  very important ideas.

Once you have watched the videos, take a look at Head First Design Patterns. That walks you through a number of problems and solutions.

I don't have specific project suggestions, but I would advise you to try whatever project in a strictly object oriented language such as Java. C++ let's you cheat too easily, and maybe without even knowing you are doing so.

ContentLicense: CC BY-SA 3.0

Title: Learning good OOP design and unlearning some bad habits

Body:
Possible Duplicate:

  What books or resources would you recommend to learn practical OO design and development concepts?

I have been mostly a C programmer so far in my career with knowledge of C++. I rely on C++ mostly for the convenience STL provides and I hardly ever focus on good design practices. As I have started to look for a new job position, this bad habit of mine has come back to haunt me. During the interviews, I have been asked to design a problem (like chess, or some other scenario) using OOP and I doing really badly at that (I came to know this through feedback from one interview).

I tried to google stuff and came up with so many opinions and related books that I don't know where to begin. I need a good through introduction to OOP design with which I can learn practical design, not just theory.

Can you point me to any book which meets my requirements? I prefer C++, but any other language is fine as long as I can pick-up good practices.

Also, I know that books can only go so far. I would also appreciate any good practice project ideas that helped you learn and improve your OOP concepts.


问:
Simplifying C++11 optimal parameter passing when a copy is needed
It seems to me that in C++11 lots of attention was made to simplify returning values from functions and methods, i.e.: with move semantics it's possible to simply return heavy-to-copy but cheap-to-move values (while in C++98/03 the general guideline was to use output parameters via non-const references or pointers), e.g.:

```<code>// C++11 style
vector<string> MakeAVeryBigStringList();

// C++98/03 style
void MakeAVeryBigStringList(vector<string>& result);
</code>```

On the other side, it seems to me that more work should be done on input parameter passing, in particular when a copy of an input parameter is needed, e.g. in constructors and setters.

My understanding is that the best technique in this case is to use templates and std::forward<>, e.g. (following the pattern of this answer on C++11 optimal parameter passing):

```<code>class Person
{
    std::string m_name;

public:
    template <class T,
              class = typename std::enable_if
              <
                  std::is_constructible<std::string, T>::value
              >::type>
    explicit Person(T&& name)
        : m_name(std::forward<T>(name))
    {
    }

    ...
};
</code>```

A similar code could be written for setters.

Frankly, this code seems boilerplate and complex, and doesn't scale up well when there are more parameters (e.g. if a surname attribute is added to the above class).

Would it be possible to add a new feature to C++11 to simplify code like this (just like lambdas simplify C++98/03 code with functors in several cases)?

I was thinking of a syntax with some special character, like @ (since introducing a &&& in addition to && would be too much typing :)
e.g.:

```<code>class Person
{
    std::string m_name;

public:
    /*
       Simplified syntax to produce boilerplate code like this:

       template <class T,
              class = typename std::enable_if
              <
                  std::is_constructible<std::string, T>::value
              >::type>
    */
    explicit Person(std::string@ name)
        : m_name(name) // implicit std::forward as well
    {
    }

    ...
};
</code>```

This would be very convenient also for more complex cases involving more parameters, e.g.

```<code>Person(std::string@ name, std::string@ surname)
    : m_name(name),
      m_surname(surname)
{
}
</code>```

Would it be possible to add a simplified convenient syntax like this in C++?
What would be the downsides of such a syntax?

答:
Frankly, this code seems boilerplate and complex

Probably because it's completely wrong. The "By value" part of that answer was what you were supposed to do. The other part, nobody ever does that. The only reason to do so was that you knew in advance your data member was non-movable (rather rare) and non-copyable and you didn't know what it could be constructed from, an extremely rare combination of circumstances. It doesn't even cover that circumstance, since it would have to be variadic.

```<code>class Person {
    std::string name;
public:
    Person(std::string cname)
        : name(std::move(cname)) {}
};
</code>```

Done.

Body:
Frankly, this code seems boilerplate and complex

Probably because it's completely wrong. The "By value" part of that answer was what you were supposed to do. The other part, nobody ever does that. The only reason to do so was that you knew in advance your data member was non-movable (rather rare) and non-copyable and you didn't know what it could be constructed from, an extremely rare combination of circumstances. It doesn't even cover that circumstance, since it would have to be variadic.

class Person {
    std::string name;
public:
    Person(std::string cname)
        : name(std::move(cname)) {}
};

Done.


答:
Sadly, no, because there's too many cases.  In your sample, you use std::string@ to represent the perfectly forwarded type of an object that should be perfectly forwarded to a std::string constructor, and say "A similar code could be written for setters.".  But you're wrong.  You'd need another seperate syntax for assignment.  For instance, I can construct a std::vector<anything> from an int, but I can't assign an int to a std::vector<anything>.  So I'd need like std::vector<anything># for assignments.  And what about the + operator?  If I want to perfect forward a RHS to a member's operator+, then I'd need a notation for that too.  And it can't be an existing symbol like + or that would make C++ much harder to parse than it already is!  So you can see that this doens't apply universally how you appear to think it does.

Secondly, I disagree that the existing boilerplate doesn't scale well.  It scales linearly, which is pretty well I think.  (Note that the members and the mem-init-list boilerplate is required in any case and is thus not part of the scaling.  Even if it were, that's still linear)

```<code>class Person
{
    std::string m_name;
    std::string m_address;
    std::string m_nickname;
    std::string m_phonenumber;
    std::string m_comment;

public:
    template <class T, class U, class V, class W, class X,
              class = typename std::enable_if <
                  std::is_constructible<std::string, T>::value &&
                  std::is_constructible<std::string, U>::value &&
                  std::is_constructible<std::string, V>::value &&
                  std::is_constructible<std::string, W>::value &&
                  std::is_constructible<std::string, X>::value
              >::type>
    explicit Person(T&& name, U&& addr, V&& nick, W&& phone, X&& comment)
        : m_name(std::forward<T>(name)),
          m_address(std::forward<T>(addr)),
          m_nickname(std::forward<T>(nick)),
          m_phonenumber(std::forward<T>(phone)),
          m_comment(std::forward<T>(comment)),
    {
    }

    ...
};
</code>```

Third: This is only needed when you need to pass an unknown type perfectly to the member, which is very rare.  Normally, you'd just take all the members as std::string by value, and move them into the members, which is amazingly close to optimal considering how amazingly easy it is.

Title: Simplifying C++11 optimal parameter passing when a copy is needed

Body:
It seems to me that in C++11 lots of attention was made to simplify returning values from functions and methods, i.e.: with move semantics it's possible to simply return heavy-to-copy but cheap-to-move values (while in C++98/03 the general guideline was to use output parameters via non-const references or pointers), e.g.:

```<code>// C++11 style
vector<string> MakeAVeryBigStringList();

// C++98/03 style
void MakeAVeryBigStringList(vector<string>& result);
</code>```

On the other side, it seems to me that more work should be done on input parameter passing, in particular when a copy of an input parameter is needed, e.g. in constructors and setters.

My understanding is that the best technique in this case is to use templates and std::forward<>, e.g. (following the pattern of this answer on C++11 optimal parameter passing):

```<code>class Person
{
    std::string m_name;

public:
    template <class T,
              class = typename std::enable_if
              <
                  std::is_constructible<std::string, T>::value
              >::type>
    explicit Person(T&& name)
        : m_name(std::forward<T>(name))
    {
    }

    ...
};
</code>```

A similar code could be written for setters.

Frankly, this code seems boilerplate and complex, and doesn't scale up well when there are more parameters (e.g. if a surname attribute is added to the above class).

Would it be possible to add a new feature to C++11 to simplify code like this (just like lambdas simplify C++98/03 code with functors in several cases)?

I was thinking of a syntax with some special character, like @ (since introducing a &&& in addition to && would be too much typing :)
e.g.:

```<code>class Person
{
    std::string m_name;

public:
    /*
       Simplified syntax to produce boilerplate code like this:

       template <class T,
              class = typename std::enable_if
              <
                  std::is_constructible<std::string, T>::value
              >::type>
    */
    explicit Person(std::string@ name)
        : m_name(name) // implicit std::forward as well
    {
    }

    ...
};
</code>```

This would be very convenient also for more complex cases involving more parameters, e.g.

```<code>Person(std::string@ name, std::string@ surname)
    : m_name(name),
      m_surname(surname)
{
}
</code>```

Would it be possible to add a simplified convenient syntax like this in C++?
What would be the downsides of such a syntax?

Body:
Sadly, no, because there's too many cases.  In your sample, you use std::string@ to represent the perfectly forwarded type of an object that should be perfectly forwarded to a std::string constructor, and say "A similar code could be written for setters.".  But you're wrong.  You'd need another seperate syntax for assignment.  For instance, I can construct a std::vector<anything> from an int, but I can't assign an int to a std::vector<anything>.  So I'd need like std::vector<anything># for assignments.  And what about the + operator?  If I want to perfect forward a RHS to a member's operator+, then I'd need a notation for that too.  And it can't be an existing symbol like + or that would make C++ much harder to parse than it already is!  So you can see that this doens't apply universally how you appear to think it does.

Secondly, I disagree that the existing boilerplate doesn't scale well.  It scales linearly, which is pretty well I think.  (Note that the members and the mem-init-list boilerplate is required in any case and is thus not part of the scaling.  Even if it were, that's still linear)

class Person
{
    std::string m_name;
    std::string m_address;
    std::string m_nickname;
    std::string m_phonenumber;
    std::string m_comment;

public:
    template <class T, class U, class V, class W, class X,
              class = typename std::enable_if <
                  std::is_constructible<std::string, T>::value &&
                  std::is_constructible<std::string, U>::value &&
                  std::is_constructible<std::string, V>::value &&
                  std::is_constructible<std::string, W>::value &&
                  std::is_constructible<std::string, X>::value
              >::type>
    explicit Person(T&& name, U&& addr, V&& nick, W&& phone, X&& comment)
        : m_name(std::forward<T>(name)),
          m_address(std::forward<T>(addr)),
          m_nickname(std::forward<T>(nick)),
          m_phonenumber(std::forward<T>(phone)),
          m_comment(std::forward<T>(comment)),
    {
    }

    ...
};

Third: This is only needed when you need to pass an unknown type perfectly to the member, which is very rare.  Normally, you'd just take all the members as std::string by value, and move them into the members, which is amazingly close to optimal considering how amazingly easy it is.


问:
Why do Windows commands allow `-` and `/` switches?
```<code>> shutdown /?
> Usage: shutdown [/i | /l | /s | /r | /g | /a | /p | /h | /e | /o] [/hybrid] [/f]
</code>```

The windows cmd.exe command shutdown only documents forward slash / switches, but it accepts dash - switches as well. For instance, both work:

```<code>shutdown /s /t 0
shutdown -s -t 0
</code>```

When was this added and why?

答:
Slashes are Windows's original option syntax and not all windows commands accept the dash-options.

With Dir /? you the list of the options for dir.

But with

```<code>Dir -?
</code>```

you get a file not found-message (tested with Windows XP) (Same with dir -w...).

Body:
Slashes are Windows's original option syntax and not all windows commands accept the dash-options.

With Dir /? you the list of the options for dir.

But with

Dir -?

you get a file not found-message (tested with Windows XP) (Same with dir -w...).


问:
Custom HTML Tags: Are there any specifications stating a standard way to handle them?
It seems like for years they've just been given default styling and inline display. Is there a spec somewhere that has dictated this? I've looked over the RFC's but I'm not particularly good with RFC-ese, and I didn't notice anything anywhere.

For example

```<code><body>
   Some content <mycustomtag>something else</mycustomtag> more content.
</body>
</code>```

I can still style it with CSS, and the browser doesn't outright vomit... so it seems like there is some sort of expected behavior. Was that dictated by a specification?

答:
HTML 2.0 (RFC 1866) says, in Undeclared Markup Error Handling: “To facilitate experimentation and interoperability between implementations of various versions of HTML, the installed base of HTML user agents supports a superset of the HTML 2.0 language by reducing it to HTML 2.0: markup in the form of a start-tag or end-tag, whose generic identifier is not declared is mapped to nothing during tokenization. – – Information providers are warned that this convention is not binding: unspecified behavior may result, as such markup does not conform to this specification.”

This means that unknown tags are ignored. Any data between them is processed normally. That is, the tags are skipped, the (purported) element is not: its content is handled as if the tags were not there. So instead of being treated as inline elements, the constructs were treated as content.

HTML 2.0 is a great improvement over its successors in clarity and exactness. But what happened in practice is that browsers started recognizing elements with undefined tags, creating element nodes in the DOM and making them available to styling and client-side scripting. IE is the last one to follow suit here (as so often), and in Quirks Mode, even IE 9 ignores unknown tags (does not create styleable elements), unless you use document.createElement() to “define” them.

In XHTML, things are different in principle. Though the XHTML specs are obscure, it’s apparently the idea that XHTML is just XML with tags bound to “HTML namespace”. That is, you can use any tags in XHTML, and those declared to be in HTML namespace will be interpreted using HTML semantics, other elements are either from other namespaces known to the implementation (say, MathML or SVG namespace) or without any namespace, being just XML tags – which still create (styleable) nodes in the DOM.


问:
Assigned to a new WPF project, know nothing about it
I started as the analyst, talking to the client and jotting down requirements and all that jazz. Ended as the sole developer of the project.

The schedule is OK, but not OK for someone that don't know nothing about how to develop a WPF application, IMHO.

What can I do about it, tell program manager that she made a huge mistake by choosing someone with no skills(she had no choice, I was the only one not allocated), or slit my wrists? Do I have other choices?

P.S.: Really trying to learn it, can't get how to structure the project MVVM, IoC, Logging. The concept count is too damn high.

答:
I'd start with the basics first and add the design patterns and AOP concerns once those are nailed down.  Trying to learn all of that in one shot is just going to confuse you, as you seem to be aware.

I would suggest that you talk to the PM not in terms of "I can't do it", but rather in terms of "this is going to be a relatively simple implementation".  I'm not sure where the MVVM/Logging/etc requirements are coming from, but I'd fix those if I were you as being unfeasible, given your skill set with the framework.

The main thing is to manage expectations.  The app will have to be relatively simple and it might not be the most maintainable thing in the world since this is your first crack at it.

Edit to clarify about MVVM: My intent here was to suggest that MVVM is not a specific requirement of WPF projects rather than to question its validity as a pattern or its usefulness.  Similar concept of the AOP techniques as well.


问:
How effectively "sell" a good design in large meetings
Many times I have witnessed a sad tragedy.  Here's what happens:

A team design review for a new project.

I see a simple design that has quite a few holes.

I casually mention the holes and ways to avoid them.

The warnings are ignored with comments like "that 'never' happen in real life"

Eventually the things that "will 'never' happen" happen

An emergency team design review for a broken project.

So what do I do?  Copping the "I told you so" attitude is not going to win friends and influence people.  Sometimes years go by and the comments from step 3 are forgotten anyway.  I definitely don't want to be the annoying pest reminding the world of the gotchas.  I often sit back and watch the Titanic sail off to Europe.

It's frustrating to see bad designs move forward.  It's also frustrating that I can't seem to convince others of the pending peril of the current path.  I do worst on team meetings where everyone has different ways of understanding different terms.  Also, egos tend to win of reason and thought.  I'm looking for good tactics to convince groups people to use some new and complicated ideas.

答:
If possible, review the design before (or even after) the meeting, and talk to the designers in private. Shoot people down in a meeting in front of all their colleages will tend to make them instantly defensive and closed-minded about your suggestions, and can lead to a reputation as a "trouble maker" even though you think you're being helpful.

A good (but often difficult) way to present "criticisms" is to ask leading questions - let the other person try to answer your question and realise the flaw for themselves. Then it seems much more like their own idea and they will be more likely to take it forward. Again, this works best in private discussions, but can be a more diplomatic and effective way forward in a meeting situation (Note: Try to avoid getting into an argument or long discussion to convince people in the meeting. Just get the idea across and try not to labour the point. It may be better to let go of it and then have a chat with the designers after the meeting to "clear up something I didn't quite understand" than to be "the guy who made a simple 30 minute meeting waste my whole morning")

Another approach is to email your suggestions (diplomatically) to the lead designer (or a relevant but small distribution list). It may help get your ideas considered, and also gives you a "paper trail" to support any "I told you so" situation in the future (if things go pear-shaped, you at least have proof that you tried to help but were ignored. But if things get that bad, you probably aren't working in the right company)

Finally, bear in mind that sometimes you may be "wrong". The people you're talking to may have a clearer or more complete understanding of their design than you do, and have good reasons for their approach (for example, I was recently accused by a team member of creating an "inefficient" design, but it was a deliberate design as I knew performance would still be acceptable, but it would halve the development cost - it was a business decision rather than a code quality decision). Just try to be open minded about others' ideas - sometimes what appears to be a bad idea to you may be a good idea for reasons you haven't considered.

ContentLicense: CC BY-SA 2.5


答:
Yeah, you're in for a lot of fun.  Look, here's some advice... MVVM is great if you want to unit-test your ViewModels.  Are you going to do that?  (Are you doing any unit testing at all?)

The WinForms approach would be to have a Model, a View (the form) and then when you load a form, you pass the Model to something that loads data into the form (controller?).  At the end of editing you have something that validates the data, and if it's good, it applies the changes from the form back to the Model.  You know what, you can do that with WPF too, and it would actually be just fine if that's what you're familiar with.

Definitely use IoC for your model and services, but that doesn't mean you have to use a full-on dependency injection framework.

If you did that, followed the principles of Separation of Concerns, DRY, SOLID, etc., then I wouldn't have any problem picking up your project and making changes to it.  Focus on fulfilling the project objectives and doing everything in a straightforward way.

Title: Assigned to a new WPF project, know nothing about it

Body:
I started as the analyst, talking to the client and jotting down requirements and all that jazz. Ended as the sole developer of the project.

The schedule is OK, but not OK for someone that don't know nothing about how to develop a WPF application, IMHO.

What can I do about it, tell program manager that she made a huge mistake by choosing someone with no skills(she had no choice, I was the only one not allocated), or slit my wrists? Do I have other choices?

P.S.: Really trying to learn it, can't get how to structure the project MVVM, IoC, Logging. The concept count is too damn high.


问:
What kind of image should be used in a web page?
I have a site that will have lots of images of large size. What is the best format that I should choose for displaying these images?

I need the website to load fast. I am jumbled with different formats of images like jpeg, png, gif, bmp, etc. Which to use in this case and why ?

答: If your aim is as you say to for "the web-site to load faster" then you might also want to look at making the images available via a Content Delivery Network (CDN) like Amazon Cloud Front or Max CDN.</p>


问:
using "IS" is better or checking for "NOT NULL"
In C#.NET language: This style of coding is recommended or the one below it?

```<code>        if (sheet.Models.Data is GroupDataModel)
        {
            GroupDataModel gdm = (GroupDataModel)sheet.Models.Data;
            Group group = gdm.GetGroup(sheet.ActiveCell.Row.Index);
            if (group!=null && controller != null)
            {
                controller.CheckApplicationState();
            }
        }
</code>```

or this one:

```<code>        var gdm = sheet.Models.Data as GroupDataModel;
        if (gdm != null)
        {
            Group group = gdm.GetGroup(sheet.ActiveCell.Row.Index);
            if (@group!=null && controller != null)
            {
                controller.CheckApplicationState();
            }
        }
</code>```

答:
If you intend to cast (or use as) if the result of calling is is true, you should just call as and avoid two cast attempts.

I prefer the second version for this reason.


答:
The 'Head First Design Patterns' book mentioned in the Ben's answer is excellent.  It really brings the ideas from the original 'Gang of Four' Design Patterns Book to life.

As Telastyn says in the answer, understanding to domain is critical and this will really help inform your object model.  For this I really recommend Eric Evans' Domain Driven Design.  It also has a great bibliography of books on OO.

Finally, your approach to testing will inform the way you design your software and what OO patterns you use.

I didn't really 'get' Factory Pattern until I had to write a unit test for some legacy code which in its constructor created one of its dependencies.

This made it very hard to test and drove me to refactor the code to have the dependency created by a Factory which when the tests were being run could be set up to return a mock object.


答:
In short, if you already know what type it can cast to use a C-style cast:

```<code>var o = (string) iKnowThisIsAString;
</code>```

Note that only with a C-style cast can you perform explicit type coercion. If you don't know whether it's the desired type and you're going to use it if it is, use as keyword:

```<code>var txt = o as string;
if (txt != null) return txt.Replace("_","-");

//or for early return:
if (txt == null) return;
</code>```

Note that as will not call any type conversion operators. It will only be non-null if the object is not null and natively of the specified type.

Title: using "IS" is better or checking for "NOT NULL"

Body:
In C#.NET language: This style of coding is recommended or the one below it?

```<code>        if (sheet.Models.Data is GroupDataModel)
        {
            GroupDataModel gdm = (GroupDataModel)sheet.Models.Data;
            Group group = gdm.GetGroup(sheet.ActiveCell.Row.Index);
            if (group!=null && controller != null)
            {
                controller.CheckApplicationState();
            }
        }
</code>```

or this one:

```<code>        var gdm = sheet.Models.Data as GroupDataModel;
        if (gdm != null)
        {
            Group group = gdm.GetGroup(sheet.ActiveCell.Row.Index);
            if (@group!=null && controller != null)
            {
                controller.CheckApplicationState();
            }
        }
</code>```

Body:
In short, if you already know what type it can cast to use a C-style cast:

var o = (string) iKnowThisIsAString;

Note that only with a C-style cast can you perform explicit type coercion. If you don't know whether it's the desired type and you're going to use it if it is, use as keyword:

var txt = o as string;
if (txt != null) return txt.Replace("_","-");

//or for early return:
if (txt == null) return;

Note that as will not call any type conversion operators. It will only be non-null if the object is not null and natively of the specified type.


答:
Stack Overflow, online MSDN resources and the like will be your friend. Work through some of the simple example projects, modify them and ask questions. Most of the time you'll find your question has already been asked and answered.

Also, if there is someone else in your organization who knows WPF, see if they can help you. It may be a quick mentoring session or a short term pair programming with them helping you by looking over your shoulder. This option will, of course, depend on their availability.

As for dealing with the program manager, tell her that you'll need a little extra time to get up to speed on WPF built into the schedule. I'd guess that you aren't expected to know WPF right now so this should be acceptable. Most companies prefer their employees to learn new things since it can be leveraged in future projects.


问:
What problems do configuration management tools solve?
My company is creating a service in an Amazon Virtual Private Cloud. Without getting too much into the details, there will be about 5 different types of servers, and each type will need to be replicated based on demand. A bit of reading gives me the impression that we're going to want to use a config management tool like Puppet or Chef.

My bosses are receptive to the idea, but need convincing that it's actually worth the upfront cost of learning one of these tools. I have no experience with these tools, and can't really offer anything other than a few bullet points on what they do, and that wiser people on the internet seem to think it's a good idea.

The benefits of a CM just seem like vague best practices at this point, since I haven't yet experienced the problems that they are meant to solve. What headaches can I expect if we don't use a config management tool?

答:
As a start point look at this info - Configuration management. The concept itself is very broad, that you may need to narrow it down on certain areas.

CM, when applied over the life cycle of a system, provides visibility
  and control of its performance, functional and physical attributes. CM
  verifies that a system performs as intended, and is identified and
  documented in sufficient detail to support its projected life cycle.
  The CM process facilitates orderly management of system information
  and system changes for such beneficial purposes as to revise
  capability; improve performance, reliability, or maintainability;
  extend life; reduce cost; reduce risk and liability; or correct
  defects. The relatively minimal cost of implementing CM is returned
  many fold in cost avoidance.

In addition to Wikipedia, look at this summarized article to get more in-depth thoughts - Configuration Management Tools Summary.


答:
In short, try not to re-invent the wheel.

Look at best practices on WPF development. Open source projects and sample MSDN labs are good start points. For example: - WPF documentation samples.


问:
Optimistic work sharing on sparsely distributed systems
What would a system like BOINC look like if it were written today?
At the time BOINC was written, databases were the primary choice for maintaining a shared state and concurrency among nodes.

Since then, many approaches have been developed for tasking with optimistic concurrency (OT, synchronization primitives like vector clocks, virtual synchrony, shared iterators etc.)

Is there a paradigm for optimistically distributing units of work on sparsely distributing systems which communicate through message passing?

Sorry if this is a bit vague.

P.S.
The concept of Tuple-spaces is great, but locking is inherent to its definition.

Edit2:

The entire system is sparsely distributed - they can communicate only through WAN. And communication can be slow and faulty. The question is about how to best distribute units of work among them without a central co-ordinator and with as little consensus as possible (because consensus is expensive).

The answers here seem to be talking about databases - data isn't the problem. The problem is in distributing work.

Edit:

I already have a federation system which works well. I'm looking to extend it to get clients to do units of work.

答:
When you know what your system really needs is when you can choose the better solution. The biggest data systems are made for great amounts of data, if your system has little data (GBs) then one typical solution will fit. You must think that big sparse data systems require special data models that are very different from SQL typical data models.

RDBMS data models look forward to represent a consistent state in every moment, distributed systems don't (see CAP theorem).


问:
How to rewrite a TCP MMOG server designed to run in a single machine, in a distributed way?
I have a MMOG server running on C++, using winsockets. My server won't support more than 200 players. I had the idea of redesigning it so it will use multiple servers instead of one, so, maybe, for example, each server could take care of a number of players, and, if it was too laggy, it could transfer the responsability of that player to other server. I'm not sure of how to program a consistent game logic like that, though. Are there techniques for this?</p>

答:
The first thing you must think is about partition. That is, split players in groups that don't usually interact. As much partitions you have you can have more servers (you can read more with PCAM methodology of partitioning http://www.mcs.anl.gov/~itf/dbpp/text/node15.html).
On the other hand systems that make thinks like yours usually have their clients connected to more than one server at the same time in order to have a failover (but this is more harder to do).</p>


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
Not that anyone will notice, but this is why braces belong on the same line as the conditional (except for very long conditionals, but that's an edge case):

In C, this is a valid construct:

```
while(true);
{
    char c;
    getchar(); //Wait for input
}
```

Quick! What does this code do? If you answered "infinite loop asking for input", you are wrong! It doesn't even get to the input. It gets caught at while(true). Notice that semicolon at the end. This pattern is actually more common that it seems like it should be; C requires you to declare your variables at the beginning of a block, which is why a new one was started.

A line of code is a thought. Braces are a part of the thought containing the conditional or loop. Therefore, they belong on the same line.

Body:
Not that anyone will notice, but this is why braces belong on the same line as the conditional (except for very long conditionals, but that's an edge case):

In C, this is a valid construct:

while(true);
{
    char c;
    getchar(); //Wait for input
}

Quick! What does this code do? If you answered "infinite loop asking for input", you are wrong! It doesn't even get to the input. It gets caught at while(true). Notice that semicolon at the end. This pattern is actually more common that it seems like it should be; C requires you to declare your variables at the beginning of a block, which is why a new one was started.

A line of code is a thought. Braces are a part of the thought containing the conditional or loop. Therefore, they belong on the same line.


问:
Synchronizing local and remote cache in distributed caching
With a distributed cache, a subset of the cache is kept locally while the rest is held remotely.

In a get operation, if the entry is not available locally, the remote cache will be used and and the entry is added to local cache.

In a put operation, both the local cache and remote cache are updated. Other nodes in the cluster also need to be notified to invalidate their local cache as well.

What's a simplest way to achieve this if you implemented it yourself, assuming that nodes are not aware of each other.

Edit
My current implementation goes like this:

Each cache entry contains a time stamp.

Put operation will update local cache and remote cache

Get operation will try local cache then remote cache

A background thread on each node will check remote cache periodically for each entry in local cache. If the timestamp on remote is newer overwrite the local.  If entry is not found in remote, delete it from local.

答: Well, I see that you are looking for Memcached. This product makes things exactly as you wish, is free and stable. Used by Wikipedia and others. If you want to do your own, you can take a look to it's documentation where the way it works is explained.</p>


答:
I think Uncle Bob's Agile Principles, Patterns, and Practices would be a really good book for you.  The book uses C# for many examples but think of those examples as pseudo-code rather than production C#.  Everything that book teaches can easily be applied to just about any OO language and the level of material will probably be perfect for you.

While you are new and learning, I would strongly advise to stay away from "design patterns" books.  Too many people pick those up, learn few patterns and start slapping them all over the place.  As Uncle Bob points out in the above book, you should code into a pattern when you see one developing, rather than starting with the goal of building a specific pattern in the first place.  However, you need good OOP sense before you can make design decision that would lead you to a pattern.

As far as material outside of the books, I would say learn the SOLID, KISS and DRY principles.  And when I say "learn", I don't mean read about them and think you understand them.  I mean, when you code you live and breath those principles.  Every time you add another function or another variable keep asking yourself:

am I duplicating existing code?

Is my function/class doing too many things?

Can what I just wrote be done simpler?

....

As @worldofchris mentioned (+1 to that answer), I would also recommend learning TDD while you are learning OO.  The two go hand-in-hand and well-designed code, will lend itself to be easily testable.  Conversely, if your code is already testable, it's quality will tend to be higher in relation to code that has no unit test coverage.


答:
Clean Code

Pragmatic Programmer

Working with Legacy Code

The majority of books will make you feel happy. That won't get you a job.

Start by reading few chapters of Pragmatic Programmer and then move onto Clean Code. Review your old code as you read the books and start refactoring.

Reading books won't give you experience, but making your code "clean" will. It's up to you to decide when to draw the line regarding quality of your code.

Reason why I recommend these books is because guys who wrote them have been working in this industry for decades, and they have a very good idea of what works and what doesn't.


答:
A great book on the subject is Object Oriented Design Heuristics. The book has over 60 heuristics in it which are language independent. In addition to the theory the book has a 122 page appendix of C++ examples. I can't recommend this book enough, it is an excellent introduction.

It's a bit more difficult of a read, but Applying UML And Patterns is also a great introduction. This book is huge and is not a quick read, but it uses two case studies to introduce the material (the monopoly game and a point of sale system).

These two books (and Refactoring) are 3 of the biggest influences in my programming career. You won't be disappointed.


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

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

答: Poor writers make poor writers, and nothing else. Poor writing skill does not mean they can't communicate at all, but they just can't write or express very well. Of course anyone can say communication skill is important and crucial in company and so on and so forth, but that doesn't mean a programmer with poor communication skill can't get the job done nicely. The programming and writing are art, but of completely different kind. Writing is about how to make some other human understand what you are saying and/or act accordingly, but programming is not making computer understand your requirement, because no computer will understand any user requirement (at least within 100 years from now IMO). The programming is about how to translate the requirement to the programming language, and that's why writing skill is not so related. </p>

Title: Do poor writers make poor programmers?


答:
Fundamentally, they are two different things. But what do you think reads better?

```<code>if (sheet.Models.Data is GroupDataModel)
</code>```

or

```<code>var gdm = sheet.Models.Data as GroupDataModel;
if (gdm != null)
</code>```

You've got your answer here. Oded made a very valid point, but programming isn't much different from writing articles. It needs to be easily readable by other engineers.

Body:
Fundamentally, they are two different things. But what do you think reads better?

if (sheet.Models.Data is GroupDataModel)

or

var gdm = sheet.Models.Data as GroupDataModel;
if (gdm != null)

You've got your answer here. Oded made a very valid point, but programming isn't much different from writing articles. It needs to be easily readable by other engineers.


答:
The first thing you have to do is profile what's making it slow or "laggy". Understand the problem. Is it an OS limitation (too many sockets open)? Is the server using 100% CPU? Is the DDOS flooding the network and slowing it down? If not, can you do any profiling of your code to determine what the current bottlenecks are?

Is your code multi-threaded? If not, and if your game is CPU-bound, a good improvement might be to have multiple threads. This would be the first step towards a distributed system, too. You could have a client handler / connection pooler and a separate thread that represents the game state and takes actions from the handler and applies them. It's difficult to speculate without knowing more about the structure of your program.

Title: How to rewrite a TCP MMOG server designed to run in a single machine, in a distributed way?

Body: I have a MMOG server running on C++, using winsockets. My server won't support more than 200 players. I had the idea of redesigning it so it will use multiple servers instead of one, so, maybe, for example, each server could take care of a number of players, and, if it was too laggy, it could transfer the responsability of that player to other server. I'm not sure of how to program a consistent game logic like that, though. Are there techniques for this?</p>


问:
Designing a Business Rule Engine
I have a requirement where there are 10 Rules to be applied on data in excel.
If Rule 1 and Rule 2 fails rest of the rules are not checked. But if Rule 1 and Rule 2 passes the rest of all the Rules should be verified and if any errors found- they should be logged. Is there any design pattern which I can use to keep this Rule Engine flexible for adding these 10 rules and Closed for any additional chains in the Current Rule. I was thinking of something like a Decorator Pattern. Will this help me achieve that?</p>

答:
Thinking out loud here.

Imagine you have different states and commands.

For example:

DepositedState

RegisteredState

LoggedInState

You can represent those are enums or classes.

You then have commands:

DisplayTwoForOnePromotion

Display20PctOffPromotion

Commands can be classes that would encapsulate some logic and have a single "run" method.

You can then start modelling your rules by selecting states and assigning appropriate commands to those states.

I was always excited about using patterns and best practices, but unless you can think of the right pattern for the job in first few minutes, than you are probably over-engineering something.

Title: Designing a Business Rule Engine


问:
"Best fit" to avoid reuse of object instances in a collection
Imagine I have a collection of object instances which represent activities for a user to undertake.  Dependent on user attributes, I have to randomly select instances to present activities to the user.

For some users, I need to present more activities to them than there are available activities in which case, I want to use the following algorithm.

If all available activities have already been presented to the user, then re-select a "used" activity, selecting the earliest presented activity ordered by frequency of use.  In other words, try to reduce repetition and where repetition is unavoidable, use the instances which have been repeated less often and were presented furthest back in time.

Before I go on to code that algorithm, I wondered if there is some existing pattern I can re-use?

[EDIT]  "Furthest back in time" is not relevant as I will pass the algorithm an ordered collection of used instances where the first entry is the first presented.

答:
There are users and activities.

Activities are displayed to users depending on user's attributes.

Fundamentally, you have an algorithm (strategy) for displaying activities to the user.

First step is to encapsulate your algorithm somewhere. I propose to create a class called UserActivityStrategy for storing this algorithm.

You then get your user, get their previous activities and pass those objects to the strategy which will execute your algorithm and return relevant data.

```<code>var user = new User();
var previousActivities = new ActivityRepository().GetPreviousActivitiesForUser(user);

var proposedActivities = new UserActivityStrategy(previousActivities, user).GetActivities();
</code>```

I don't like the fact that I'm passing both previousActivities and user to the strategy. You could refactor this by encapsulating both in a separate class called UserActivityHistory. This class would encapsulate user and their previous activities.

This one of many ways of solving this problem.

Body:
There are users and activities.

Activities are displayed to users depending on user's attributes.

Fundamentally, you have an algorithm (strategy) for displaying activities to the user.

First step is to encapsulate your algorithm somewhere. I propose to create a class called UserActivityStrategy for storing this algorithm.

You then get your user, get their previous activities and pass those objects to the strategy which will execute your algorithm and return relevant data.

var user = new User();
var previousActivities = new ActivityRepository().GetPreviousActivitiesForUser(user);

var proposedActivities = new UserActivityStrategy(previousActivities, user).GetActivities();

I don't like the fact that I'm passing both previousActivities and user to the strategy. You could refactor this by encapsulating both in a separate class called UserActivityHistory. This class would encapsulate user and their previous activities.

This one of many ways of solving this problem.


答:
If your rules look something like this:

```<code>interface Rule {
    var isCritical:Bool;
    function verify(data:Data):Null<Error>;
}
</code>```

Then applying them looks something like this:

```<code>for (rule in rules) {
    var error = rule.verify(data);
    if (error != null) {
        if (rule.isCritical) return error;
        else report(error);
    }
}
return null;//no critical error
</code>```

You can implement as many rules as you wish.

Title: Designing a Business Rule Engine

Body:
I have a requirement where there are 10 Rules to be applied on data in excel.
If Rule 1 and Rule 2 fails rest of the rules are not checked. But if Rule 1 and Rule 2 passes the rest of all the Rules should be verified and if any errors found- they should be logged. Is there any design pattern which I can use to keep this Rule Engine flexible for adding these 10 rules and Closed for any additional chains in the Current Rule. I was thinking of something like a Decorator Pattern. Will this help me achieve that?</p>

Body:
If your rules look something like this:

interface Rule {
    var isCritical:Bool;
    function verify(data:Data):Null<Error>;
}

Then applying them looks something like this:

for (rule in rules) {
    var error = rule.verify(data);
    if (error != null) {
        if (rule.isCritical) return error;
        else report(error);
    }
}
return null;//no critical error

You can implement as many rules as you wish.


问:
How get and set accessors work
The standard method of implementing get and set accessors in C# and VB.NET is to use a public property to set and retrieve the value of a corresponding private variable.  Am I right in saying that this has no effect of different instances of a variable?  By this I mean, if there are different instantiations of an object, then those instances and their properties are completely independent right?  So I think my understanding is correct that setting a private variable is just a construct to be able to implement the get and set pattern?  Never been 100% sure about this.</p>

答:
If you look at the Intermediate Language of the setter below:

```<code>private string _bar;
private string Bar
{
    get
    {
        return this._bar;
    }
    set
    {
        this._bar = value;
    }
}
</code>```

Then you'll see:

```<code>.method private hidebysig specialname instance string get_Bar() cil managed
{
    // Irrelevant to this question
}
</code>```

Now if you ignore everything within braces, you'll see that it works similar to normal methods in your class. You can think of getters and setters as sugar syntax.

There is a whole separate discussion of when you should be using properties instead of methods, and what access modifier they should have, but it's out of this question's scope.

Finally, you class is just a blueprint. Once you instantiate an object from your blueprint (class), its logic is encapsulated, therefore accessing properties on this object doesn't affect other objects that have been instantiated from the same class.

Reference: https://stackoverflow.com/questions/4184755/net-il-property-setter

Title: How get and set accessors work

Body:
If you look at the Intermediate Language of the setter below:

private string _bar;
private string Bar
{
    get
    {
        return this._bar;
    }
    set
    {
        this._bar = value;
    }
}

Then you'll see:

.method private hidebysig specialname instance string get_Bar() cil managed
{
    // Irrelevant to this question
}

Now if you ignore everything within braces, you'll see that it works similar to normal methods in your class. You can think of getters and setters as sugar syntax.

There is a whole separate discussion of when you should be using properties instead of methods, and what access modifier they should have, but it's out of this question's scope.

Finally, you class is just a blueprint. Once you instantiate an object from your blueprint (class), its logic is encapsulated, therefore accessing properties on this object doesn't affect other objects that have been instantiated from the same class.

Reference: https://stackoverflow.com/questions/4184755/net-il-property-setter


问:
Are nested classes under-rated?
I'm not trying to say I know something everyone else doesn't but I've been solving more and more designs with the use of nested classes, so I'm curious to get a feeling for the acceptablilty of using this seemingly rarely used design mechanism.

This leads me to the question: am I going down an inherintly bad path for reasons I'll discover when they come back to bite me, or are nested classes maybe something that are underrated?

Here are two examples I just used them for: https://gist.github.com/3975581 - the first helped me keep tightly releated heirarchical things together, the second let me give access to protected members to workers...

答:
In my experience, nested classes

Came back to haunt me

Have been used when I wanted to cut corners

Made testing a nightmare

Had negative impact on separation of concerns and overall design

Had a brief look at your class, and right away I think that:

It's painful to look at it because the class is huge

I can't test "fingers" without pretty much creating entire body

I can't have multiple implementations of torso. Doesn't seem that obvious in a "human body" context, but in a different scenario this would become obvious.

Why not separate your class into multiple classes and give them separate namespaces. E.g.

```<code>WindowsGame1.PhysicalModel.UpperBody
WindowsGame1.PhysicalModel.LowerBody
WindowsGame1.PhysicalModel.UpperBody.Arms
</code>```

Title: Are nested classes under-rated?

Body:
In my experience, nested classes

Came back to haunt me

Have been used when I wanted to cut corners

Made testing a nightmare

Had negative impact on separation of concerns and overall design

Had a brief look at your class, and right away I think that:

It's painful to look at it because the class is huge

I can't test "fingers" without pretty much creating entire body

I can't have multiple implementations of torso. Doesn't seem that obvious in a "human body" context, but in a different scenario this would become obvious.

Why not separate your class into multiple classes and give them separate namespaces. E.g.

WindowsGame1.PhysicalModel.UpperBody
WindowsGame1.PhysicalModel.LowerBody
WindowsGame1.PhysicalModel.UpperBody.Arms


问:
Seeking advice on system documentation
I have a rating engine (it is basically an algorithm) which when I started had no formal documentation. We have created a functional specification/decomposition which is our business level document but now I need something more technical (a technical specification).

What I am struggling to understand is what that document looks like, what format it should be in and to what level of detail we should go into.

We are in the process of commenting all of the code. We also have a rough document called a Blueprint which reflects the flow of the model and is written in pseudo code. Is the combination of this blueprint and the model comments sufficient as a Technical Specification?

答:
Don't write comments just for the sake of it. Comment public API, comment REGEX expression, comment something truly difficult (rare to come across with all the frameworks and tools out there). I don't think that this is a solution to your problem.

Write a document for a person who knows nothing about what you are doing. The document should explain why you are doing this, how you are doing this and how it can be tested (validated).

Find somebody who knows nothing about what you are working on. Give them the document. If it makes perfect sense to them, then you've done a good job, otherwise go back to the drawing board.

Title: Seeking advice on system documentation


问:
Is data integrity possible without normalization?
I am working on an application that requires the storage of location information such as city, state, zip code, latitude, and longitude. I would like to ensure:

Location data is accurate

Detroit, CA

Detroit IS NOT in California

Detroit, MI

Detroit IS in Michigan

Cities and states are spelled correctly

California not Calefornia

Detroit not Detriot

Cities and states are named consistently

Valid:

CA

Detroit

Invalid:

Cali

california

DET

d-town

The D

Also, since city/zip data is not guaranteed to be static, updating this data in a normalized fashion could be difficult, whereas it could be implemented as a de facto location if it is denormalized.

A couple thoughts that come to mind:

A collection of reference tables that store a list of all states and the most common cities and zip codes that can grow over time. It would search the database for an exact or similar match and recommend corrections.

Use some sort of service to validate the location data before it is stored in the database.

Is it possible to fulfill these requirements without normalization, and if so, should I denormalize this data?

答:
You can always implement a value transformer to normalize (or attempt to normalize) the input, similar to how a spell-check would work. Check out Damerau-Levenshtein edit distance if you need ideas on how to get the nearest match for free-form input strings from a list of known strings. As for ensuring data accuracy, once the data is normalized you can simply store your criteria in some sort of associative data structure (a dictionary would suffice here) like you've described.

This way you can still allow free-form input, while still allowing consistency and accuracy within your model. Consider if Google search required normalized input, you would miss tons of matches if your spelling/phrasing isn't 100% accurate.


问:
Should static parameters in an API be part of each method?
I am currently creating a library that is a wrapper for an online API. The obvious end goal is to make it as easy for others to use as possible. As such I am trying to determine the best approach when it comes to common parameters for the API.

In my current situation there are 3 (consumer key, consumer secret, and and authorization token). They are essentially needed in every API call. My question is should I make these 3 parameters required for each method or is there a better way.

I see my current options as being:

Place the parameters in each method call

```<code>public ApiObject callMethod(String consumerKey, String consumerSecret, String token, ...)
</code>```

This one seems reasonable, but seems awfully repetitive to me.

Create a singleton class that the user must initialize before calling any api methods. This seems wrong, and would essentially limit them to accessing one account at a time via the API (which may be reasonable, I dunno).

Make them place them in a properties file in their project. That way I can load the properties that way and store them. This seems similar to the singleton to me, but they would not have to explicitly call something to initialize these values.

Is there another option I am not seeing, or a more common practice in this situation that I should be following?

答:
None of the above!

As part of the API have a context or connection or whatever is most appropriate. Have the consumer specify these tokens on constructing, then the method calls are instance methods on the context.


答:
I think what Telastyn is suggesting is

```<code>public class ConsumerContext { string key; string secret; string token; }
public ApiObject callMethod(ConsumerContext, ...)
</code>```

This is sometimes a way of providing locale information as well - add it to the context.

Title: Should static parameters in an API be part of each method?

Body:
I am currently creating a library that is a wrapper for an online API. The obvious end goal is to make it as easy for others to use as possible. As such I am trying to determine the best approach when it comes to common parameters for the API.

In my current situation there are 3 (consumer key, consumer secret, and and authorization token). They are essentially needed in every API call. My question is should I make these 3 parameters required for each method or is there a better way.

I see my current options as being:

Place the parameters in each method call

```<code>public ApiObject callMethod(String consumerKey, String consumerSecret, String token, ...)
</code>```

This one seems reasonable, but seems awfully repetitive to me.

Create a singleton class that the user must initialize before calling any api methods. This seems wrong, and would essentially limit them to accessing one account at a time via the API (which may be reasonable, I dunno).

Make them place them in a properties file in their project. That way I can load the properties that way and store them. This seems similar to the singleton to me, but they would not have to explicitly call something to initialize these values.

Is there another option I am not seeing, or a more common practice in this situation that I should be following?

Body:
I think what Telastyn is suggesting is

public class ConsumerContext { string key; string secret; string token; }
public ApiObject callMethod(ConsumerContext, ...)

This is sometimes a way of providing locale information as well - add it to the context.


问:
Are non Turing-complete languages considered programming languages at all?
Reading a recent question: Is it actually possible to have a 'useful' programming language that isn't Turing complete?, I've come to wonder whether non Turing-complete programming languages are considered programming languages at all.

Since Turing-completeness means a language has to have variables to store values as well as control structures ( for, while )... Is a language that lacks these features considered a programming language ?

答:
Whether or not you want to call them "programming languages" depends on your definition, but it my view the answer is yes: you can regard a non-turing complete language as a programming langauge.

Consider the following definition (from Wikipedia):

A programming language is an artificial language designed to
  communicate instructions to a machine, particularly a computer.
  Programming languages can be used to create programs that control the
  behavior of a machine and/or to express algorithms precisely.

A non-turing complete DSL could easily meet all of these requirements. You can't necessarily express all algorithms (this would require Turing completeness), but you could express enough algorithms to be useful in the given domain.

Also as a slightly pedantic but philosophically important point - modern computers are actually finite state machines so are not strictly turing complete (Turing completeness actually requires infinite memory....). So in some sense, no language as currently implemented on a modern computer is Turing complete.


答:
This is merely to demonstrate with formatting what I think Telastyn was describing...</p>

```<code>public class ConsumerContext
(
  prop string key
  prop string secret
  prop string token

  # default ctor
  public ConsumerContext(){}

  # parameterized ctor
  public ConsumerContext(string key, string secret, string token)
  {
     this.key = key
     this.secret = secret
     this.token = token
  }

  public void FooWrapper(fooApiSpecificParamList)
  {
     api.foo(this.key, this.secret, this.token, fooApiSpecificParamList)
  }

  public void BarWrapper(barApiSpecificParamList)
  {
     api.bar(this.key, this.secret, this.token, barApiSpecificParamList)
  }

}
</code>```

Body:
This is merely to demonstrate with formatting what I think Telastyn was describing...

public class ConsumerContext
(
  prop string key
  prop string secret
  prop string token

  # default ctor
  public ConsumerContext(){}

  # parameterized ctor
  public ConsumerContext(string key, string secret, string token)
  {
     this.key = key
     this.secret = secret
     this.token = token
  }

  public void FooWrapper(fooApiSpecificParamList)
  {
     api.foo(this.key, this.secret, this.token, fooApiSpecificParamList)
  }

  public void BarWrapper(barApiSpecificParamList)
  {
     api.bar(this.key, this.secret, this.token, barApiSpecificParamList)
  }

}


答:
Yes, of course you can do data integrity on an unnormalized database.  How do you think they did things before the normal forms were discovered?

However, the reason that normalization became standard procedure is that it made everything, including data integrity, SIMPLER.

Title: Is data integrity possible without normalization?

Body:
I am working on an application that requires the storage of location information such as city, state, zip code, latitude, and longitude. I would like to ensure:

Location data is accurate

Detroit, CA

Detroit IS NOT in California

Detroit, MI

Detroit IS in Michigan

Cities and states are spelled correctly

California not Calefornia

Detroit not Detriot

Cities and states are named consistently

Valid:

CA

Detroit

Invalid:

Cali

california

DET

d-town

The D

Also, since city/zip data is not guaranteed to be static, updating this data in a normalized fashion could be difficult, whereas it could be implemented as a de facto location if it is denormalized.

A couple thoughts that come to mind:

A collection of reference tables that store a list of all states and the most common cities and zip codes that can grow over time. It would search the database for an exact or similar match and recommend corrections.

Use some sort of service to validate the location data before it is stored in the database.

Is it possible to fulfill these requirements without normalization, and if so, should I denormalize this data?


问:
Scripting custom drawing in Delphi application with IF/THEN/ELSE statements?
I'm building a Delphi application which displays a blueprint of a building, including doors, windows, wiring, lighting, outlets, switches, etc. I have implemented a very lightweight script of my own to call drawing commands to the canvas, which is loaded from a database. For example, one command is ELP 1110,1110,1290,1290,3,8388608 which draws an ellipse, parameters are 1110x1110 to 1290x1290 with pen width of 3 and the color 8388608 converted from an integer to a TColor.

What I'm now doing is implementing objects with common drawing routines, and I'd like to use my scripting engine, but this calls for IF/THEN/ELSE statements and such. For example, when I'm drawing a light, if the light is turned on, I'd like to draw it yellow, but if it's off, I'd like to draw it gray. My current scripting engine has no recognition of such statements. It just accepts simple drawing commands which correspond with TCanvas methods.

Here's the procedure I've developed (incomplete) for executing a drawing command on a canvas:

```<code>function DrawCommand(const Cmd: String; var Canvas: TCanvas): Boolean;
type
  TSingleArray = array of Single;
var
  Br: TBrush;
  Pn: TPen;
  X: Integer;
  P: Integer;
  L: String;
  Inst: String;
  T: String;
  Nums: TSingleArray;
begin
  Result:= False;
  Br:= Canvas.Brush;
  Pn:= Canvas.Pen;
  if Assigned(Canvas) then begin
    if Length(Cmd) > 5 then begin
      L:= UpperCase(Cmd);
      if Pos(' ', L)> 0 then begin
        Inst:= Copy(L, 1, Pos(' ', L) - 1);
        Delete(L, 1, Pos(' ', L));
        L:= L + ',';
        SetLength(Nums, 0);
        X:= 0;
        while Pos(',', L) > 0 do begin
          P:= Pos(',', L);
          T:= Copy(L, 1, P - 1);
          Delete(L, 1, P);
          SetLength(Nums, X + 1);
          Nums[X]:= StrToFloatDef(T, 0);
          Inc(X);
        end;
        Br.Style:= bsClear;
        Pn.Style:= psSolid;
        Pn.Color:= clBlack;
        if Inst = 'LIN' then begin
          Pn.Width:= Trunc(Nums[4]);
          if Length(Nums) > 5 then begin
            Br.Style:= bsSolid;
            Br.Color:= Trunc(Nums[5]);
          end;
          Canvas.MoveTo(Trunc(Nums[0]), Trunc(Nums[1]));
          Canvas.LineTo(Trunc(Nums[2]), Trunc(Nums[3]));
          Result:= True;
        end else
        if Inst = 'ELP' then begin
          Pn.Width:= Trunc(Nums[4]);
          if Length(Nums) > 5 then begin
            Br.Style:= bsSolid;
            Br.Color:= Trunc(Nums[5]);
          end;
          Canvas.Ellipse(Trunc(Nums[0]),Trunc(Nums[1]),Trunc(Nums[2]),Trunc(Nums[3]));
          Result:= True;
        end else
        if Inst = 'ARC' then begin
          Pn.Width:= Trunc(Nums[8]);
          Canvas.Arc(Trunc(Nums[0]),Trunc(Nums[1]),Trunc(Nums[2]),Trunc(Nums[3]),
            Trunc(Nums[4]),Trunc(Nums[5]),Trunc(Nums[6]),Trunc(Nums[7]));
          Result:= True;
        end else
        if Inst = 'TXT' then begin
          Canvas.Font.Size:= Trunc(Nums[2]);
          Br.Style:= bsClear;
          Pn.Style:= psSolid;
          T:= Cmd;
          Delete(T, 1, Pos(' ', T));
          Delete(T, 1, Pos(',', T));
          Delete(T, 1, Pos(',', T));
          Delete(T, 1, Pos(',', T));
          Canvas.TextOut(Trunc(Nums[0]), Trunc(Nums[1]), T);
          Result:= True;
        end;
      end else begin
        //No space found, not a valid command
      end;
    end;
  end;
end;
</code>```

What I'd like to know is what's a good lightweight third-party scripting engine I could use to accomplish this? I would hate to implement parsing of IF, THEN, ELSE, END, IFELSE, IFEND, and all those necessary commands. I need simply the ability to tell the scripting engine if certain properties meet certain conditions, it needs to draw the object a certain way.

The light example above is only one scenario, but the same solution needs to also be applicable to other scenarios, such as a door being open or closed, locked or unlocked, and draw it a different way accordingly. This needs to be implemented in the object script drawing level. I can't hard-code any of these scripting/drawing rules, the drawing needs to be controlled based on the current state of the object, and I may also wish to draw a light a certain shade or darkness depending on how dimmed the light is.

答: Have a look at DWS.  It's essentially Delphi scripting in Delphi.  (Or fairly close.  It's its own dialect of Object Pascal, but the author's done an impressive job of it.)</p>


答: If they can't write well, how can they convince you that they are good programmers?

Title: Do poor writers make poor programmers?

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

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


问:
Is conditional return type ever a good idea?
So I have a method that's something like this:

```<code>-(BOOL)isSingleValueRecord
</code>```

And another method like this:

```<code>-(Type)typeOfSingleValueRecord
</code>```

And it occurred to me that I could combine them into something like this:

```<code>-(id)isSingleValueRecord
</code>```

And have the implementation be something like this:

```<code>-(id)isSingleValueRecord {
    //If it is single value
    if(self.recordValue = 0) {

        //Do some stuff to determine type, then return it
        return typeOfSingleValueRecord;
    }
    //If its not single value
    else {
        //Return "NO"
        return [NSNumber numberWithBool:NO];
    }
}
</code>```

So combining the two methods makes it more efficient but makes the readability go down. In my gut, I feel like I should go with the two-method version, but is that really right? Is there any case that I should go with the combined version?

答:
What if you throw out both solutions and come up with a different design? For example, you could provide a single method like:

```<code>- (NSArray*)recordTypes;
</code>```

If the record is a single-value record the returned array contains one type. If it's a multi-value record, the array contains more than one type.

I'm assuming here that coming up with the record itself is difficult or time consuming. If it's not, you could instead just provide the record itself, and let the client query it for it's type or types.

Body:
What if you throw out both solutions and come up with a different design? For example, you could provide a single method like:

- (NSArray*)recordTypes;

If the record is a single-value record the returned array contains one type. If it's a multi-value record, the array contains more than one type.

I'm assuming here that coming up with the record itself is difficult or time consuming. If it's not, you could instead just provide the record itself, and let the client query it for it's type or types.


答:
I'm a Java developer, but in Java I would never combine those two.

Because a method called is* suggests that you return a boolean value, while one that's called typeOf* suggests to return a certain type.

But you may use the one in the other to avoid code duplication, e.g. in typeOfSingleValueRecord do something like (pseudo code) if(isSingleValueRecord) return "type of record"

Title: Is conditional return type ever a good idea?

Body:
So I have a method that's something like this:

```<code>-(BOOL)isSingleValueRecord
</code>```

And another method like this:

```<code>-(Type)typeOfSingleValueRecord
</code>```

And it occurred to me that I could combine them into something like this:

```<code>-(id)isSingleValueRecord
</code>```

And have the implementation be something like this:

```<code>-(id)isSingleValueRecord {
    //If it is single value
    if(self.recordValue = 0) {

        //Do some stuff to determine type, then return it
        return typeOfSingleValueRecord;
    }
    //If its not single value
    else {
        //Return "NO"
        return [NSNumber numberWithBool:NO];
    }
}
</code>```

So combining the two methods makes it more efficient but makes the readability go down. In my gut, I feel like I should go with the two-method version, but is that really right? Is there any case that I should go with the combined version?


答:
It looks like you are trying to return more than one thing from a single method, which is not an unusual thing. An unusual (and usually bad) thing is that you are trying to combine both items in a single value, which must be interpreted by the caller in a non-intuitive way (similar to the infamous "yes/no/file-not-found" mix-up).

A better signature for your method would separate the two values it returns as follows:

```<code>-(BOOL)tryGetSingleValueRecordType:(Type**)typePtr {
    if (self.recordValue = 0) {
        *typePtr = typeOfSingleValueRecord;
        return YES;
    } else {
        return NO;
    }
}
</code>```

Now the caller would be able to call your API like this:

```<code>Type *srType;
if ([record tryGetSingleValueRecordType:&srType]) {
    NSLog("Single record type: %@", srType);
} else {
    NSLog("Not a single record");
}
</code>```

The two items returned by your API, i.e. the YES/NO answer and the actual type, are returned through two separate mechanisms, without losing readability, efficiency, or type safety.

Body:
It looks like you are trying to return more than one thing from a single method, which is not an unusual thing. An unusual (and usually bad) thing is that you are trying to combine both items in a single value, which must be interpreted by the caller in a non-intuitive way (similar to the infamous "yes/no/file-not-found" mix-up).

A better signature for your method would separate the two values it returns as follows:

-(BOOL)tryGetSingleValueRecordType:(Type**)typePtr {
    if (self.recordValue = 0) {
        *typePtr = typeOfSingleValueRecord;
        return YES;
    } else {
        return NO;
    }
}

Now the caller would be able to call your API like this:

Type *srType;
if ([record tryGetSingleValueRecordType:&srType]) {
    NSLog("Single record type: %@", srType);
} else {
    NSLog("Not a single record");
}

The two items returned by your API, i.e. the YES/NO answer and the actual type, are returned through two separate mechanisms, without losing readability, efficiency, or type safety.


问:
Custom HTML Tags: Are there any specifications stating a standard way to handle them?
It seems like for years they've just been given default styling and inline display. Is there a spec somewhere that has dictated this? I've looked over the RFC's but I'm not particularly good with RFC-ese, and I didn't notice anything anywhere.

For example

```<code><body>
   Some content <mycustomtag>something else</mycustomtag> more content.
</body>
</code>```

I can still style it with CSS, and the browser doesn't outright vomit... so it seems like there is some sort of expected behavior. Was that dictated by a specification?

答:
Jukka's answer covers the existing specs nicely, just for completeness sake I'd like to mention that the very recent "Introduction to Web Components" W3C draft includes custom HTML elements (the proper name is elements, "tag" refers to the opening and closing tag).

From the draft:

2 Introduction

The component model for the Web (also known as Web Components) consists of four pieces designed to be used together to let web application authors define widgets with a level of visual richness not possible with CSS alone, and ease of composition and reuse not possible with script libraries today.

These pieces are:

templates, which define chunks of markup that are inert but can be activated for use later;

decorators, which apply templates to let CSS affect rich visual and behavioral changes to documents;

custom elements, which let authors define their own elements, including new presentation and API, that can be used in HTML documents; and

shadow DOM which defines how presentation and behavior of decorators and custom elements fit together in the DOM tree.

...

5 Custom Elements

Custom elements are new types of DOM elements that can be defined by authors.

Custom elements can define presentation aspects like decorators. Unlike a decorator, which can be applied or unapplied to a given element, the element's type is fixed. So custom elements can also define new state and behavior, which decorators can't do because of their ephemeral nature.

The element element defines a custom element. It specifies the type of element it's a refinement of using the extends attribute:

```<code>   <element extends="button" name="x-fancybutton">
       …
   </element>
</code>```

You can monitor the draft's status here. The project is spearheaded by the Google Chrome development team:

The Web Components project , led largely by the Google Chrome development team, aims to help solve a simple problem: Building Web applications is more complicated than it used to be. Worse, it's more complicated than it should be.

Modern Web apps have rich, interactive UIs, driven largely by client-side code. Today we generally build such UIs using JavaScript frameworks and UI toolkits, such as Dojo/Dijit, jQuery UI, and YUI. That's both good and bad. It's good because it means it's now easier to build rich Web UIs than ever before. It's bad because it needlessly shifts the balance of control over Web development from designers to programmers.

Body:
Jukka's answer covers the existing specs nicely, just for completeness sake I'd like to mention that the very recent "Introduction to Web Components" W3C draft includes custom HTML elements (the proper name is elements, "tag" refers to the opening and closing tag).

From the draft:

2 Introduction

The component model for the Web (also known as Web Components) consists of four pieces designed to be used together to let web application authors define widgets with a level of visual richness not possible with CSS alone, and ease of composition and reuse not possible with script libraries today.

These pieces are:

templates, which define chunks of markup that are inert but can be activated for use later;

decorators, which apply templates to let CSS affect rich visual and behavioral changes to documents;

custom elements, which let authors define their own elements, including new presentation and API, that can be used in HTML documents; and

shadow DOM which defines how presentation and behavior of decorators and custom elements fit together in the DOM tree.

...

5 Custom Elements

Custom elements are new types of DOM elements that can be defined by authors.

Custom elements can define presentation aspects like decorators. Unlike a decorator, which can be applied or unapplied to a given element, the element's type is fixed. So custom elements can also define new state and behavior, which decorators can't do because of their ephemeral nature.

The element element defines a custom element. It specifies the type of element it's a refinement of using the extends attribute:

   <element extends="button" name="x-fancybutton">
       …
   </element>

You can monitor the draft's status here. The project is spearheaded by the Google Chrome development team:

The Web Components project , led largely by the Google Chrome development team, aims to help solve a simple problem: Building Web applications is more complicated than it used to be. Worse, it's more complicated than it should be.

Modern Web apps have rich, interactive UIs, driven largely by client-side code. Today we generally build such UIs using JavaScript frameworks and UI toolkits, such as Dojo/Dijit, jQuery UI, and YUI. That's both good and bad. It's good because it means it's now easier to build rich Web UIs than ever before. It's bad because it needlessly shifts the balance of control over Web development from designers to programmers.


问:
What methodology to use for planning/developing a Language conversion project?
I am trying to help my friend by creating a part of his on-going project.

What I'm going to do is create a Java parser to break up the Java code into operators, parameters etc to build XML representation.

Next I want to create a code generator to convert the parsed java code to XML conforming to the schema I've created.

Finally I want to use an XML style-sheet to transform the XML into another programming language type.

Basically I just wanted some advice on which methodology/model I should use for planning and developing this project. Is there some benefit to using Agile etc for instance?

答:
Rather than use XML here why not reverse engineer the language translation from the byte code. That is a much more flexible intermediate format.

Be warned, what you are attempting to do here is extremely hard.

Usually it is cheaper to hire an expert in the target language to rewrite the code. And for that you will need tests. Lots of tests.


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

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

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

答:
I had the same problem you did. I wanted to support as many versions as possible in my application.

After a while I figured out I couldn't use all the cool things Android 4 had to offer me so I had to go up a minSDKVersion (and again, and again).

now I'm stuck at 2.3.3 with what I'm rather happy, looking at the distibution of versions: Current Version Distribution

Looking at that you'll target a great number of people if you set your minSDKVersion to 2.3.3.

Regarding your problems with Action Bars which you can't use, have you looked into ActionBarSherlock

Title: Supporting early versions of Android


答:
As all other answers said, your problem is really hard. But since you asked for a methodology, that questions is easier to answer.

First of all, the methodology you use depends a lot on the organization you are in. Some organizations simply follow waterfall development methodologies (i.e Military) and there is nothing you can do. On the other end there are organizations that only develop projects using agile methodologies. You must take this into account before taking any decision.

Second, agile methodologies are being used more and more these days because they produce better products (although there is no clear scientific evidence of this, most project that have moved to agile are very happy after the change). I would also recommend agile development (short iterations, working product, automatic tests, etc...). You can mix this with TDD to get more robustness, but it is not a must.

Last, but not least, even if you are doing agile, you still need to define your requirements in an exact way. Agile is NOT a synonym to not having defined requirements! it means that you implements the requirements step by step. With the complexity of what you are trying to achieve, you MUST define your requirements very well. If you don't have good requirements not event testing will help you (sorry for repeating myself, but I find this is a very important point).

And good luck.

Title: What methodology to use for planning/developing a Language conversion project?

Body:
I am trying to help my friend by creating a part of his on-going project.

What I'm going to do is create a Java parser to break up the Java code into operators, parameters etc to build XML representation.

Next I want to create a code generator to convert the parsed java code to XML conforming to the schema I've created.

Finally I want to use an XML style-sheet to transform the XML into another programming language type.

Basically I just wanted some advice on which methodology/model I should use for planning and developing this project. Is there some benefit to using Agile etc for instance?


问:
How do you check bugs on your client's PC's?
It seems like there are a plethora of methods for dialing in and checking out what's going on on a client's PC.  But they seem to boil down to just 2. Dialing in and checking it out with VNC and Remote Desktop.

VNC seems abysmal with more graphics laden OS's and it sometimes is too much to ask to get a access to a terminal server (especially when the client doesn't have one).

What other methods are out there for connecting with clients to diagnose and fix bugs they they can reproduce, but may not necessarily be able to adequately describe over the phone.

Alternatives to VNC and Remote Desktop are appreciated, but really looking for a better way to do it than just to dial in and check it out - or the most effective way to use VNc and Remote Desktop.

答:
I have developed my own diagnostic logic and form:

Press CTRL-ALT-F12. This will open a diagnostic window containing the screenshot of the screen you were in, detailed log files, application state, computer info.

If you have access to the internet, click on the "Send" button. The content of what you see will be sent to us directly

If you don't have access to the internet, click save as and send us the file by email

If the above doesn't work, I use either TeamViewer (nothing to install and pass trought firewalls) or LogMeIn (must be installed, but works fine in controlled environment)


问:
Why did memory-managed languages like Java, Javascript, and C# retain the `new` keyword?
The new keyword in languages like Java, Javascript, and C# creates a new instance of a class.

This syntax seems to have been inherited from C++, where new is used specifically to allocate a new instance of a class on the heap, and return a pointer to the new instance.  In C++, this is not the only way to construct an object. You can also construct an object on the stack, without using new - and in fact, this way of constructing objects is much more common in C++.

So, coming from a C++ background, the new keyword in languages like Java, Javascript, and C# seemed natural and obvious to me.  Then I started to learn Python, which doesn't have the new keyword.  In Python, an instance is constructed simply by calling the constructor, like:

```<code>f = Foo()
</code>```

At first, this seemed a bit off to me, until it occurred to me that there's no reason for Python to have new, because everything is an object so there's no need to disambiguate between various constructor syntaxes.

But then I thought - what's really the point of new in Java?  Why should we say Object o = new Object();?  Why not just Object o = Object();?  In C++ there's definitely a need for new, since we need to distinguish between allocating on the heap and allocating on the stack, but in Java all objects are constructed on the heap, so why even have the new keyword?  The same question could be asked for Javascript.  In C#, which I'm much less familiar with, I think new may have some purpose in terms of distinguishing between object types and value types, but I'm not sure.

Regardless, it seems to me that many languages which came after C++ simply "inherited" the new keyword - without really needing it.  It's almost like a vestigial keyword.  We don't seem to need it for any reason, and yet it's there.

Question: Am I correct about this?  Or is there some compelling reason that new needs to be in C++-inspired memory-managed languages like Java, Javascript and C# but not Python?

答:
Actually in Java there is a difference when using Strings:

```<code>String myString = "myString";
</code>```

is different from

```<code>String myString = new String("myString");
</code>```

Supposing the string "myString" has never been used before, the first statement creates a single String object in the String pool (a special area of the heap) while the second statement creates two objects, one in the normal heap area for objects and other in String pool. It is pretty obvious that the second statement is useless in this particular scenario, but is allowable by the language.

This means that new assures that the object is created in that special area of the heap, allocated for normal object instantiation, but there may be other ways of instantiating objects without it; the above one is an example, and there is room left for extensibility.

Body:
Actually in Java there is a difference when using Strings:

String myString = "myString";

is different from

String myString = new String("myString");

Supposing the string "myString" has never been used before, the first statement creates a single String object in the String pool (a special area of the heap) while the second statement creates two objects, one in the normal heap area for objects and other in String pool. It is pretty obvious that the second statement is useless in this particular scenario, but is allowable by the language.

This means that new assures that the object is created in that special area of the heap, allocated for normal object instantiation, but there may be other ways of instantiating objects without it; the above one is an example, and there is room left for extensibility.


问:
Writing jenkins plugin: where is the documentation?
On my current project we're using Jenkins to monitor our builds.
Now they want me to write a Jenkins plugin to add some more monitoring parameters.

I've taken a look at how the status monitor plugin works, and I can't figure some things out. I've tried to look for documentation for writing a plugin, but that seems to be sorely lacking. (the site only mentions how to generate the base project, and refers to a tutorial that's not that informative)

What I'm trying to do is just add some options to each build, add a link, and a monitoring page. Adding to the main page is apparently done by adding the action, but I'm still trying to figure out the rest. And how it all ties in.

Does anyone have any pointers, or a place where I can find some decent documentation?

答:
I had the same difficulties while I was developping Jenkins plugin for the first time.
Let me give you some advice :

Read the Wiki. Although lack of information, You can "try" to understand the core concepts in Jenkins : https://wiki.jenkins-ci.org/display/JENKINS/Extend+Jenkins

Second advise, go to UISamples plugin. This plugin contains a lot of demonstration code and shows examples of the concepts that you read on the wiki. I had difficulties understand Describable/Descriptor relationship until I went to the UI plugin to see how it works. It's much easier than reading the Wiki.You can find it this address : https://github.com/jenkinsci/ui-samples-plugin.

Search if there is no  plugin that does the same thing or has similar functionalities that you want to develop. If you find one,  install it and see how it behaves. Loofk at the GitHub project page of this plugin. The plugin list can be found in this address : https://github.com/jenkinsci


答:
There are occasions where returning different types is OK - those occasions are when you want to take advantage of polymorphism or some other mechanism that amounts to "the types you return will respond to the same operations" (templates, duck-typing, etc.)

Your example above does not fit that category. In this case you are creating an interface that is only more efficient for you, but has not saved the client of your class any work. A caller must still determine if it is dealing with a singleValueRecord.

There are a couple better options.

Use a structure or tuple to combine the boolean and Type in a single return value.

As mentioned by others, provide a boolean return value and an output parameter for the function that would hold the type information.

If it is very unusual for you to return NO, you could throw an exception

Try to think about what is going to make life easiest for the calling code, not what looks best in the implementation.


答:
What you describe has nothing to do with normalization but with validation.

You can simply have a source somewhere with the valid values. Then just validate before storing the information in your database.


问:
Being productive during downtime
Lets say you are somewhere where coding and getting online isn't possible (On a busy flight, for example)what do you do to stay productive?

Things I would do are read whatever tech book I am currently slogging through and maybe doodle some UI stuff or workflows.  What else could I be doing?

答:
offline != down.

I keep a full deployment on my own machine, so that I do not need to be online to develop.  This allowed me to do a fair amount of development work while commuting via train before the trains in this area started supporting wifi.

Title: Being productive during downtime


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

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

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

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

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

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

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

Package b has the concrete classes that extend from ClassA:

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

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

Package a and b have a cyclic dependency.

答:
You should be aware, that by implementing visitor, you are severely limiting yourself in how and where you can subclass root of the hiearchy. Your problems are results of such limitations.

Maybe you could make abstract BBase and CBase classes in module X and derive B and C classes from those. Then the whole visitor hiearchy can be in module X and module Y will only have concrete implementation of B and C classes. But this solution is also limited, because your visitor cannot work with any types, that are referenced in Y but not in X.


问:
Using dot to Access Object Attribute and Proper abstraction
I have been programming in python and Java for quite a number of years and one thing I find myself doing is using the setters and getters from Java in Python but a number of blogs seem to think using the dot notation for access is the pythonic way.

What I would like to know is if using dot to access methods does not violate abstraction principle?

If for example I implement an attribute as a single object and use dot notation to access,  if I wanted to change the code later so that the attribute is represented by a list of objects, that would require quite some heavy lifting which violates abstraction principle.

答: It depends :-).  If you treat the . notation as a shortcut for a public getter, then personally I have no issue with that. However, having everything publicly accessible via the . notation by default in my opinion is a mistake. Not all fields should be automatically visible to the outside world.</p>