问:
Pattern / methodology for representing large database records as objects
A bit of background information: We have an old database application written in Access that lets users monitor their workload, and the code is... 'procedural' might be too kind. The vast majority of code is hard-wired to form events, there's a lot of duplication, and little to no abstraction. If it needs to fetch data from the database, it'll just do it right there and then, even if that means roughly the same bit of code repeated 6 times for 6 similar buttons (and 6 practically identical database requests). It's not pretty.

I want to rebuild the application in VB.NET, but I'm hitting a bit of a design snag when it comes to writing classes to represent database records as objects - I don't have a huge amount of experience in OO programming (written a few small apps, read lots of books and material, regular SE lurker), so this is my first OO database application.

The problem is that a given 'job' for a user has a lot of fields on the database. About 30 or so - ID, Title, Requestor, Request Date, Target Date, Priority, Type, Approval... and so on. First pass: Whack everything into a dirty great Job class:

```<code>Public Class Job
    Private mID As String
    Private mTitle As String
    Private mRequestorName As String
    Private mRequestorEmail As String
    ...

    Public Property ID() As String
        Get
            Return mID
        End Get
        Set(value As String)
            Me.mID = value
        End Set
    End Property
    ...
End Class
</code>```

Yikes. I'm sure you can see my hesitance at having such an enormous class sitting front-and-center of the application. All those properties seem to be violating encapsulation too - the Private members might as well be Public, but conversely I need to be able to alter fields and later write back to the database.

Second pass: There's a few things in here that could be extracted and situated elsewhere: for example, all those Requestor___ members could sit in a Requestor class

```<code>Public Class Job
    Private mID As String
    Private mTitle As String
    Private mRequestor As Requestor
    ...
End Class

Public Class Requestor
    Private mName As String
    Private mEmail As String
    ...
End Class
</code>```

So now I have half a dozen of these. Smaller classes? Feels nice. But it feels like all I've really achieved is essentially database normalisation, which doesn't feel like it should live in the application. And the only real change to the structure is that it takes more steps to get to data items.

And I still have all those properties (which are forcing me to use hungarian notation on my private members, which I'm not a fan of, but VB.NET isn't case-sensitive so I can't use the same names), which still aren't sitting right with me.

Is there a standard pattern or methodology for moving large data items to and from a database? My current best idea is the above with commit() and read() methods in the Job class - alterations are made to the objects and then later commited to the database.

答:
If you're taking the time to re-write the code in another language, take the time to clean up the database. While your normalization steps may seem like they haven't accomplished much, I can assure you that steps like this will pay enormous dividends. If you have a poorly designed database schema, you will have to support that poor design in your source code. </p>

<p>If you can't re-design the database, then it's probably still worth designing the persistence layer correctly in your source code and then have a light-weight layer in your code that can interact with the poorly-designed database. </p>

Body:
If you're taking the time to re-write the code in another language, take the time to clean up the database. While your normalization steps may seem like they haven't accomplished much, I can assure you that steps like this will pay enormous dividends. If you have a poorly designed database schema, you will have to support that poor design in your source code.

If you can't re-design the database, then it's probably still worth designing the persistence layer correctly in your source code and then have a light-weight layer in your code that can interact with the poorly-designed database.


问:
How can I organize personal Git repositories?
I'm in the process of setting up a GitHub account with the plan of making a pair of libraries I developed as parts of some recent iOS projects freely available for other iOS devs to use.

I don't currently have off-site backup for most of my code, so as part of this, I originally thought I would upload all of my personal projects, or at least all of my iOS projects, to a private GitHub-hosted repository.  However, I have a lot of projects sitting around, many of which are fairly low-value (i.e., adapted from books and written for the learning experience).  Not only does GitHub charge by the private repository, it doesn't seem to have any way of organizing repositories hierarchically.

Is there something I'm missing that would allow me to use a git repository with a hierarchy and check out pieces as I need them / work with them, the way I currently do with SVN?

Does GitHub (or a competitor, like BitBucket) have some project organization features that I'm missing?

Failing that, what's the generally accepted "Git way" of handling this situation (discard projects not intended for release, store them offline, bundle them together somehow, etc., etc.)?

As far as I can tell, my options are:

Put libraries on GitHub, continue hosting my own SVN for all other projects, use a non-VCS solution for off-site backup (blech),

Put libraries and software I plan to release on GitHub (as public and private, respectively), continue hosting my own SVN for projects I don't care about as much and am only likely to revisit to refresh my memory on how to implement XYZ, decide that I'm willing to write them off if my house implodes (double blech),

Put everything on [GitHub and/or BitBucket], deal with having some ridiculous number of repositories by searching for what I need / maintaining some offline set of pointers into my [GitHub and/or BitBucket] account (triple blech)

答:
Short answer ...

My suggestion: Start with public accounts on GitHub and/or Bitbucket (other?). Throw up a few public projects and start using the tools/interfaces. Once you've got a feel for the services, then you should have a grasp as to what the limitations, advantages and disadvantages of each service are. From there, you should be able to choose the best path to version control enlightenment. :)

Long answer ...

I don't currently have off-site backup for most of my code, so as part of this, I originally thought I would upload all of my personal projects, or at least all of my iOS projects, to a private GitHub-hosted repository. However, I have a lot of projects sitting around, many of which are fairly low-value (i.e., adapted from books and written for the learning experience).

Have you considered installing your own Git client? If you're already paying for web hosting, then it might make sense to use that host for your own Git setup.

For example, my host is WebFaction (no affiliation):

Installing the Git Web Application

Heading this route might allow you to save some $$$, esp. if you're already paying for hosting.

Not only does GitHub charge by the private repository,

Just to clarify for others (again, no business affiliation to GitHub or BitBucket):

GitHub: Plans & Pricing

$7/mo. for up to 5 private repositories, unlimited everything else.

$12/mo. for up to 10 private repositories, unlimited everything else.

$12/mo. for up to 20 private repositories, unlimited everything else.

Note that "Business Plans" pricing is different.

Pricing for Git and Mercurial repo hosting for Bitbucket by Atlassian

As stated in by Andrew in the other answer, Bitbucket touts unlimited private repos.

5 users: Free

10 users: $10/mo.

25 users: $25/mo.

50 users: $50/mo.

100 users: $100/mo.

Unlimited $200/mo.

it doesn't seem to have any way of organizing repositories hierarchically.

Not sure exactly what you mean by "hierarchically" (probably because I'm not familiar with SVN).

I'm not sure if this would help, but you could look at this comparison table to see how the commands compare/differ:

Hyperpolyglot: Version Control

Is there something I'm missing that would allow me to use a git repository with a hierarchy and check out pieces as I need them / work with them, the way I currently do with SVN?

Branching?

A successful Git branching model (a.k.a., git-flow)

GitHub Blog: GitHub Flow in the Browser

Does GitHub (or a competitor, like BitBucket) have some project organization features that I'm missing?

Not sure if this will help, but you might take a look at:

GUI Clients

Git comes with built-in GUI tools for committing (git-gui) and browsing (gitk), but there are several third-party tools for users looking for platform-specific experience.

... again, not sure if any of those tools could help you to get a feel for what's possible.

To be clear, I'm not sure of you Git skill level ... if you're new to Git/GitHub, using a GUI might be a quick/easy way for you to get a feel for things. I personally like using the official GitHub for Mac/Windows apps.

Failing that, what's the generally accepted "git way" of handling this situation (discard projects not intended for release, store them offline, bundle them together somehow, etc., etc.)?

If I were you, I'd be using repositories.

How many private repositories do you need?

If you want to use GitHub, one solution might be to get the cheapest plan and utilize a few private repos to hold all of your test/non-public code. You could just use a folder structure on your main branch to maintain a hierarchical structure, or you could use multiple branches to keep things more separate.

Tip: If you're using a more recent version of Git, you can pull specific branches using git clone -b mybranch --single-branch git://sub.domain.com/repo.git:

Clone only one branch

How to clone a single branch in git?

I have to warn you though, using branches to organize code (like folders) isn't really the best way to do things (though, there's nothing that says you can't head this route).

(Seem my answer here for related info in regards to GitHub branches.)

Again, I think multiple repos are the way to go.

You might ask yourself if your code is really needing to be private; is it possible that you could go public with said code without any repercussions?

Put libraries on GitHub, continue hosting my own SVN for all other projects, use a non-VCS solution for off-site backup (blech),

If you head this route, Dropbox (or similar) might be a good way to get some form of version control and syncing for your off-site backup.

Put libraries and software I plan to release on GitHub (as public and private, respectively), continue hosting my own SVN for projects I don't care about as much and am only likely to revisit to refresh my memory on how to implement XYZ, decide that I'm willing to write them off if my house implodes (double blech),

This takes me back to the question "Do you already pay for hosting? If so, you could install your own Git host"; the advantage being, you could have all source code under the Git umbrella, even if it's not all on the same host (i.e., use GitHub for the public stuff you want to show off).

Put everything on [GitHub and/or BitBucket], deal with having some ridiculous number of repositories by searching for what I need / maintaining some offline set of pointers into my [GitHub and/or BitBucket] account (triple blech)

---> See my short answer above. ^^^^^^

ContentLicense: CC BY-SA 3.0


问:
What are the pros and cons for the employer of code questions during an interview?
The Joel Test question #11 is: "Do new candidates write code during their interview?". What are arguments for and against to ask new candidates to write code during the interview and to make a decision upon it?</p>

答:
You judge a bird by its feathers and a programmer by his/her code.

When I started with the current company I'm working for they asked me to write some C code that generates or checks the parity bit of some binary input (depending on whether you are encoding or decoding). This was an interview question exactly because these kinds of problems are solved during work. Of course I'm thinking of not parity checking but rather working on a low-level.

ContentLicense: CC BY-SA 2.5


问:
How do you decide how much business requirements documentation you need and how to structure it?
In the past couple of years, I've worked on two projects.

The first one, we used a very agile methodology. It was very much developer driven. As such, changes were very quick and rapid. Code quality was high becuase it was a new system. There was an emphasis on group ownership of the project and knowledge sharing. Most knowledge transfer with new staff etc. was conducted just by walking someone through the code or system and most staff members on the project knew enough of the project to do that.

The project I thought was successful but one of the regrets I have is the amount of documentation was probably inadequate long term. We had a bunch of user stories which were short term specs only relevant for the sprint, and a a bunch of master specs outlining the business processes that was long term which we would keep up to date. We had no tech specs other than a oneNote page with user logins and links to test envrionments/servers etc.

The problem was keeping a balance between putting enough in there so that it would be helpful and not so much that no one will want to read it and be a burden to maintain. I don't think we ever found that balance. The master specs were probably too generic to be useful to someone that wants to understand the system.

The second project is completely opposite. It's an old system and it's very big. We use a waterfall methodology. This project is very much tester driven. As such we have probably too much documentation - there are thousands of pages in hundreds of word documents and there is duplication everywhere. (eg. documents with the same or very similar introduction texts)

There is a big emphasis on keeping this mammoth of documentation perfect. Creating a simple change to the system requires identifying which documents is affected and making minor changes to all of them.

We document things to levels that's probably not neccessary (eg. I found a doco the other day where the File Save dialog in IE was documented) and there is an emphasis on being correct over being readable.

In short, we have half a dozen Business Analysts and their job consists more of keeping the documentation up to date than of actual analysis.

I think both of these projects have bad practices and what would be optimal is somewhere in between the two. This balance probably depends on the system as well, so how do you decide how much documentation you need and also how to structure it so that maintaining doesn't become more cost than benefit.

EDIT - Hi, sorry should've mentioned it before all the answers came along (I only was just able to check). I'm primarily focused on non-technical business requirements here - those that can be consumed not just by developers (audiences may include BAs, managers, testers, stakeholders etc.)

答:
I don't think there is any "correct" answer to this question. Really documentation needs to be succinct and as simple as possible for the target user group.

Also it pays to think of how the system might grow during the planning process and make changes to the documentation structure clear from the beginning and also ensure all people contributing to the docs follow a particular pattern (templates etc).

Think of it like good code, make really broad top-level sections that can be drilled into for progressively more and more information

Hope this helps!


问:
Casual projects on Github omit error checking, logging, etc., for the sake of clarity?
I just started using GitHub to socialize some projects for simple chat and peer-to-peer apps. With respect to coding, is it customary to omit exception handling, error checking, logging, etc., to promote easy-to-understand and 'clean'-looking code, if those additions are not completely necessary to actually run the code?

For instance, here's two extreme examples:

   if( msg != null){
      NodeEvent event = NodeEvent.valueOf(msg.getAction());
      switch (event) {
        case NODE_CONNECTING:
          if( nodeName.isInvalid())
             Utils.log("Invalid node name, ignoring...");
          else{
             String existingNodeAddress = _nodeNameAddressMap.get(nodeName);
             if( existingNodeAddress != null)
                Utils.log("Node address for '" + nodeName + "' updated");
             else
                Utils.log("New node '" + nodeName + "' connected");

             _nodeNameAddressMap.put(nodeName, nodeAddress);
          }
    }
```

<p>Here's the same snippet minus the fluff, although this version can easily crash if fed bad data, but otherwise it will compile and run fine:</p>

<pre class="lang-java prettyprint-override"><code>   NodeEvent event = NodeEvent.valueOf(msg.getAction());
   switch (event) {
     case NODE_CONNECTING:
        _nodeNameAddressMap.put(nodeName, nodeAddress);
</code>```

The clean version is easier to read, obviously, but is brittle. The verbose version is safer, it just looks cluttered.

I'm just curious to know if it's more effective for a social projects to go for the cleaner look at the expense of fragility, allowing those who fork the project to fill in the blanks. A quick survey of github projects and it's clear most go for the clean look.

答:
I think you are confusing writing books that talk about code vs. writing code that is meant to be executed by an actual computer.

"for brevity" is something a book author says when he wants to illustrate a point and the reason why the author says that is so that when you read that book, you focus on his intended point, but you also understand that this code is incomplete and SHOULD NOT be taken as a direct example of how one should write code.

When I start a project, almost the very first thing I do is define standard logging scheme and make sure there is a convention in place for handling errors.  I'm not doing it "to be complete" but because when I write code, I will introduce bugs and even if I don't, things will go wrong.  Personally, I'd rather spend 4-8 hours upfront ensuring I have a log file maybe even with ability to change logging level, than write a whole bunch of code only to stumble upon a bug and realize that everything I've written is a black box and I have no idea where it is failing or even where to start looking.

And if you don't have error handling, that means instead of identifying stack traces where the error/crash occurred and actually calling out places that failed (i.e. that system call that didn't return a resource), your app will go on only to crash/fail elsewhere, potentially masking the real problem in the process

Logging/error handling is only there to help you go faster in the long run.  But in the end, it's completely up to you. If you believe you can accomplish a project faster and meet some kind of quality standard (i.e. "is your app actually usable" would be a standard)  without handling errors, then go for it.  Logging/error handling are only tools to help you get there faster with less effort, but just like with any tool, you decide if they are worth it.  But from my experience, in just about every project I've ever done, they absolutely were.


问:
How to create a lightweight WPF application including .NET Framework 4.5?
I want to create an application which is dependent on .NET Framework 4.5.

If I am binding the framework with application setup the size of application increases to much but I need to bind the .NET Framework 4.5 with my setup.

Is there any other option to bind the framework with application setup besides downloading it from the website during installation?

答:
To deploy your application, you can use either:

ClickOnce, a proprietary technology made by Microsoft to provide seamless way to install and update .NET Framework applications. ClickOnce can contain among its prerequisites .NET Framework itself, which means that you simply need to check the correct version of .NET Framework in the prerequisites window.

Different tools for setup packages (which produce .msi files). They also often have the prerequisites part in them. It was, for sure, the case in Visual Studio 2010. If I remember well, the component was later removed in Visual Studio 2012, but I suppose that third party tools have the same feature as well.

Note: at any moment you should embed .NET Framework in your application, nor there is a need to. Microsoft provides servers and bandwidth for the deployment of .NET Framework, so use it; also, as a customer, I wouldn't especially trust an application which deploys .NET Framework from somewhere else than the official Microsoft website: what if .NET Framework was altered and doesn't do what it is expected to do (or is doing what it is not expected to do).


问:
Writing my problem solving approach on paper?
I'm a freshman Computer Science student and we just started doing some actual projects in Python. I have found I'm very efficient when I use the pen and paper method that my professor suggested in class. But when I can't write my problem down and work my algorithms out on paper I am really slow. During labs, I always seem to have to take the assignment back to my dorm. When I get there and write it out I solve the problem that took me the whole class in like 5 minutes.

Maybe it's because I get stressed seeing people solving labs before me. Or maybe it's the pen and paper method.

I was browsing through forums and someone wrote that if you have to write your programs on paper then you shouldn't be a programmer. I'm really worried because I'm so much better when I can see what the program is doing and track my way through it before typing actual code. Am I doing something wrong?

Edit: Sorry for being unclear, but when I said writing on paper I meant my problem solving approach (e.g writing examples, making tables with values, etc.) not my actual code. I just use the paper to get my ideas out.

答:
There is nothing wrong with what you are doing, I learned to program using paper and pen as well.

As others have suggested do what works for you. I remember the first Java program I wrote was mainly on paper and then I spent two hours typing it up and fifteen minutes crying when I saw 200+ compiler errors. There were more but the compiler would only show the first 200! The point I'm making though is that by writing the code on paper I was able to think through the basic algorithm and functionality for what the program needed to do. The compiler pointed out the reasons why my program wouldn't run. 90% of the problems were out of bounds exceptions with arrays.

As you gain more experience and confidence you'll find yourself using pen and paper less. You'll already know how to use basic concepts such as for loops and so on. You'll have examples in other programs, which you can re-use. You'll use the compiler and an IDE to find obvious bugs during the writing of the program. Right now though you don't have that experience.

Reading through your question I wonder if some of your problems might be due to focus. If using a pen and paper in a quiet environment helps you focus then great.

You're still at college and you're still learning. Ultimately, all you're doing is what works for you. If by using paper and pen you are ordering your thoughts and thinking clearly and calmly then you are programming.


问:
Using Java Reflection to decouple code modules
I'm involved in a project with several modules. I found that programmers have designed one module to be easily decoupled from its dependent modules using Java Reflection. If other modules need to call a method in this module, the programmers are expecting them to use reflection to call it. This has resulted in a lot of places with hard-coded reflection calls. By hard-coded, I mean the class and method names are permanently fixed as Strings, which kind of defeats the purpose of reflection which is supposed to be for dynamic programming.

How can this be justified? I feel they are being novice about it and misusing the reflection API. I think polymorphism is the right way to decouple a module from another without breaking functionality. (Unfortunately, changing the entire code base to polymorphism is way too much maintenance.)

答:
Reflection for decoupling is always a bad idea. Interfaces are the way to go.
You can dynamically detect implementations using SPI and/or OSGi or similar. Use a factory to hide the lookup details.


问:
Is spying on tested class bad practice?
I am working on a project where class internal calls are usual but the results are many times simple values. Example (not real code):

```<code>public boolean findError(Set<Thing1> set1, Set<Thing2> set2) {
  if (!checkFirstCondition(set1, set2)) {
    return false;
  }
  if (!checkSecondCondition(set1, set2)) {
    return false;
  }
  return true;
}
</code>```

Writing unit tests for this type of code is really hard as I just want to test the condition system and not the implementation of the actual conditions. (I do that in separate tests.) In fact it would be better if I passed functions that implement the conditions and in tests I simply provide some mock. The issue with this approach is the noisiness: we use generics a lot.

A working solution; however, is to make the tested object a spy and mock out the calls to the internal functions.

```<code>systemUnderTest = Mockito.spy(systemUnderTest);
doReturn(true).when(systemUnderTest).checkFirstCondition(....);
</code>```

The concern here is that the SUT's implementation is effectively changed and it may be problematic to keep the tests in sync with the implementation. Is this true? Is there best practice to avoid this havoc of internal method calls?

Note that we are talking about parts of an algorithm, so breaking it out to several classes may not be a desired decision.

答: If both findError() and checkFirstCondition() etc. are public methods of your class, then findError() is effectively a facade for functionality that is already available from the same API. There's nothing wrong with that, but it means that you have to write tests for it that are very similar to already existing tests. This duplication simply reflects the duplication in your public interface. That is no reason for treating this method any differently from others.

Title: Is spying on tested class bad practice?


答:
I don't see the cons. An interview has many parts, and a candidate should be endorsed 'up the chain' a few times.

I interview ~10 people weekly. I really, really, REALLY appreciate the fact that HR has done all of the background work and presented me with plenty of notes. By the time they get to me, it's time for me to score their tests.

The tests depend entirely on the position. Generally, I try to probe:

General programming skill. Can you use operators effectively? Can you conceive a numerical system that has a radix which is not 10?

Do you know how to do what we're hiring you to do?

Evaluation of your contributions to any open source projects that you listed

I try to keep it short, and fun. When I go into the office, I grab the answers, look them over and then conduct a secondary interview. To get hired, you typically have to get through three interviews.

I also gauge how well you will blend in with the team that will be receiving you. That team counts on me to do that effectively.

It is one thing to answer questions in meta form, it is another to actually produce code. If I'm going to hire you, I really need to see you produce code.

Title: What are the pros and cons for the employer of code questions during an interview?

Body: The Joel Test question #11 is: "Do new candidates write code during their interview?". What are arguments for and against to ask new candidates to write code during the interview and to make a decision upon it?</p>


问:
Stepping between learning about programming and actually programming a small project (C#)
I'm a Games Design Student, aware of the frequent advice that I should be good at something else as well (Programming/Art) so I'm useful when a designer is not required and also for the sake of being more useful - generally as a wish to increase my employability, value in group projects and make me capable of individual projects (which would require Design AND programming AND Art all stemming from what I can produce). As such I wish to complete some minor C# projects. In particular, I wish to write a simple Pong clone over this weekend before term starts up again on Monday.

The problem is, when ever I try to write a program, unless it's blindly following instructions (which is simply parroting) I am unable to establish a workflow that moves me forward. If I have an idea or mechanic I wish to document I have some templates I refer to and fill out. If I wanted to produce an art asset I'd consider what asset is (a car, a person) the graphical style (pixel art or drawing or 3d), the technical constraints (resolution/file formats).

For a programming workflow I'm under the impression I have my pseudo-code of what I want to make, I go through each item and check a scripting reference to see how I make each step and break them down further as required. However I have, say, "Draw Paddle_1, Move Paddle1 up/down in relation to input,..." and I cannot progress.

I've been given modules in different languages over the past two years (which I've passed all of - since it just involves parroting instructions) however I am at a loss for picking something to do, how to do it then doing it.

How do I make this leap between loose knowledge of programming and knowing basics of structure and the vocabulary towards actually being able to write something (short of copy/pasting bodies of code from googling them - after doing that dozens of times I only end up frustrated and angry and walk away from programming for months, until it comes up again)?

答:
My advice

If you really want to program, you need to learn it properly.

You are simply not trying systematically enough. By copy/pasting from Google, you are programming by coincidence, which is not a good thing to do. It is also bad that you set yourself overly optimistic targets when you're having trouble getting anything at all done in the first place.

Pick a language and learn it properly, with the help of a good book. Follow the examples of the book and make sure that you actually understand them.

For your first working program, pick a subject you really, totally understand. In this way your doubts about the subject won't distract you from your doubts about programming. Start with a very easy task, and then increase its complexity. But not before you made the easy task program actually work.

My experience

I began programming when I was a child, using BASIC. I would write programs such as:

```<code>10 CLS
20 PRINT "Hello, world!"
30 PRINT "I'm learning about commands in BASIC."
40 PRINT "This text is being printed via the PRINT command."
50 PRINT "On the next line, I'll use CLS."
60 CLS
70 PRINT "Finally, on line 80, I'll use END."
80 END
90 PRINT "Now my program is over."
</code>```

Later I started manipulating variables. I learnt how to declare a variable, initialize it, assign to it, etc.

Even before ever using functions (BASIC didn't have them), I managed to build a simulation of a football round-robin tournament in which match results were decided randomly. This was a subject I enjoyed and understood well. This made the programming easier and more fun.

I started with very small tournament and eventually I entered the code so that 20 teams could compete, as in the Spanish league.

Later, I learnt that languages have functions (and that with them, you didn't need line numbers anymore). Even later, I learnt to work with classes and object-oriented software construction.

But the key was, I think, that at each stage I got things done. If something was (seemed) too difficult, I didn't do it. In that way I got a sense of progress. You need progress, because you're stuck at the first step. And the key to progress is to understand each step you make. They have to be your steps, not someone else's.

OwnerDisplayName: Jon Watson

Body:
My advice

If you really want to program, you need to learn it properly.

You are simply not trying systematically enough. By copy/pasting from Google, you are programming by coincidence, which is not a good thing to do. It is also bad that you set yourself overly optimistic targets when you're having trouble getting anything at all done in the first place.

Pick a language and learn it properly, with the help of a good book. Follow the examples of the book and make sure that you actually understand them.

For your first working program, pick a subject you really, totally understand. In this way your doubts about the subject won't distract you from your doubts about programming. Start with a very easy task, and then increase its complexity. But not before you made the easy task program actually work.

My experience

I began programming when I was a child, using BASIC. I would write programs such as:

10 CLS
20 PRINT "Hello, world!"
30 PRINT "I'm learning about commands in BASIC."
40 PRINT "This text is being printed via the PRINT command."
50 PRINT "On the next line, I'll use CLS."
60 CLS
70 PRINT "Finally, on line 80, I'll use END."
80 END
90 PRINT "Now my program is over."

Later I started manipulating variables. I learnt how to declare a variable, initialize it, assign to it, etc.

Even before ever using functions (BASIC didn't have them), I managed to build a simulation of a football round-robin tournament in which match results were decided randomly. This was a subject I enjoyed and understood well. This made the programming easier and more fun.

I started with very small tournament and eventually I entered the code so that 20 teams could compete, as in the Spanish league.

Later, I learnt that languages have functions (and that with them, you didn't need line numbers anymore). Even later, I learnt to work with classes and object-oriented software construction.

But the key was, I think, that at each stage I got things done. If something was (seemed) too difficult, I didn't do it. In that way I got a sense of progress. You need progress, because you're stuck at the first step. And the key to progress is to understand each step you make. They have to be your steps, not someone else's.

OwnerDisplayName: Daniel Daranas


答:
First, recognise that programming is hard. Sure, it can be fun, but it isn't as easy as it looks. Now, learning C# is relatively easy - you get to know the syntax and you can make small chunks of code work. But, knowing what chunks of code to make and how to combine those is much, much harder. The reason for this is that the language consists of a finite set of simple elements. On the other hand, those elements can be combined in an infinite number of different ways, and managing the resultant complexity is genuinely challenging. So, go easy on yourself, and don't expect overnight success.

Now, something like Pong is a great first project for someone interested in games, but it really is too much to take on the whole thing all at once. I would recommend starting with one small component of the game and getting that working, then building on that and so on. Personally, I'd start with sub-goals like the following.

Draw a square ball in the centre of the screen.

Make the ball move.

Make the ball bounce off the edges of the screen.

Draw one static bat

Make the ball bounce off it as well as the edges of the screen

Make the bat move in response to user input

... and so on.

Things you really don't need to worry about are colours, scores, fancy graphics etc. You just want something that has the game dynamics you're looking for.

Now, the hardest of the sub-goals is the first one, as you've got to get a lot of things in place to get this to work. You've got to get Visual Studio working, start a project, write something that runs, initialize a drawing surface and do the drawing... Because this is the hardest part, this is the one place where you're allowed to "cheat" and copy code wholesale from somewhere else.

Once you do, do your best to understand what is going on. Start tweaking the code and re-running it to see if your understanding is correct.

From here on in, don't copy code whole-sale from Google. Instead, if you find bits that relevant to you, take the ideas and apply the principles to what you've done already. Never add any code to your project unless you really understand it.

Once you get that far, the next steps will reveal themselves to you.

Title: Stepping between learning about programming and actually programming a small project (C#)

Body:
I'm a Games Design Student, aware of the frequent advice that I should be good at something else as well (Programming/Art) so I'm useful when a designer is not required and also for the sake of being more useful - generally as a wish to increase my employability, value in group projects and make me capable of individual projects (which would require Design AND programming AND Art all stemming from what I can produce). As such I wish to complete some minor C# projects. In particular, I wish to write a simple Pong clone over this weekend before term starts up again on Monday.

The problem is, when ever I try to write a program, unless it's blindly following instructions (which is simply parroting) I am unable to establish a workflow that moves me forward. If I have an idea or mechanic I wish to document I have some templates I refer to and fill out. If I wanted to produce an art asset I'd consider what asset is (a car, a person) the graphical style (pixel art or drawing or 3d), the technical constraints (resolution/file formats).

For a programming workflow I'm under the impression I have my pseudo-code of what I want to make, I go through each item and check a scripting reference to see how I make each step and break them down further as required. However I have, say, "Draw Paddle_1, Move Paddle1 up/down in relation to input,..." and I cannot progress.

I've been given modules in different languages over the past two years (which I've passed all of - since it just involves parroting instructions) however I am at a loss for picking something to do, how to do it then doing it.

How do I make this leap between loose knowledge of programming and knowing basics of structure and the vocabulary towards actually being able to write something (short of copy/pasting bodies of code from googling them - after doing that dozens of times I only end up frustrated and angry and walk away from programming for months, until it comes up again)?

OwnerDisplayName: Kramii


问:
Equivalence partitioning understanding A<5 and B<5
I do not understand the following example. It says that a function X will be executed if either of A and B variables will be lower than 5. The go on and explains that there are three valid equivalence classes for inputs:

```<code>A<5, B<5
A=>5 B<5
B>=5 A<5
</code>```

Why there is no class for A>5 and B>5? Is it because this would not be valid class? But why A<5 and B>5 is valid, is it because the function is still dependent on that?

答:
They seem to be assuming only positive tests.

```<code>A < 5, B < 5
A >= 5, B < 5
A < 5, B >= 5
</code>```

all result in the function being run so there is some outcome you can test.
I wonder if the phrase "three valid equivalence classes for inputs" should rather be "three equivalence classes for valid inputs".

As you note there is also an equivalence class you can form for the invalid inputs a >= 5, b >= 5 which could be used in a negative test (i.e. testing X does not run when an input in this class is given)

Body:
They seem to be assuming only positive tests.

A < 5, B < 5
A >= 5, B < 5
A < 5, B >= 5

all result in the function being run so there is some outcome you can test.
I wonder if the phrase "three valid equivalence classes for inputs" should rather be "three equivalence classes for valid inputs".

As you note there is also an equivalence class you can form for the invalid inputs a >= 5, b >= 5 which could be used in a negative test (i.e. testing X does not run when an input in this class is given)


问:
Java desktop application using MVC + Hibernate
I'm developing a Java desktop application. I'm planning to use MVC architecture described at Oracle site: Java SE Application Design With MVC.

I need to store data in database so I decide to use Hibernate as it is very simple
but there is any tutorial that use Swing+MVC+Hibernate.

It is possible to use them together?

答:
Why wouldn't it be possible?

Java Swing is a GUI toolkit, so you'll utilize that framework as part of your View layer.

Hibernate is a persistence layer, so you'll utilize that framework as part of your Model layer.

Sounds like a good combination of frameworks aligning with the MVC pattern.  And by following the MVC pattern, you'll be setup to change out or modify those frameworks or layers more easily.

The other advantage of MVC is you can focus on each layer, one at a time.  You mentioned looking for a tutorial on Swing+MVC+Hibernate but you don't need one.  Follow the MVC tutorials you already mentioned and plugin those frameworks at their appropriate layer.


答:
Unit tests should test the contract; it is the only important thing, for them.  Testing anything that isn't part of the contract is not only a waste of time, it is a potential source of error.  Any time you see a developer changing the tests when he changes an implementation detail, alarm bells should ring; that developer may be (whether intentionally or not) hiding his mistakes.  Deliberately testing implementation detail forces this bad habit, making it more likely that errors will be masked.

The internal calls are an implementation detail and should only be of interest in measuring performance.  Which is not usually the job of unit tests.

Title: Is spying on tested class bad practice?

Body:
I am working on a project where class internal calls are usual but the results are many times simple values. Example (not real code):

```<code>public boolean findError(Set<Thing1> set1, Set<Thing2> set2) {
  if (!checkFirstCondition(set1, set2)) {
    return false;
  }
  if (!checkSecondCondition(set1, set2)) {
    return false;
  }
  return true;
}
</code>```

Writing unit tests for this type of code is really hard as I just want to test the condition system and not the implementation of the actual conditions. (I do that in separate tests.) In fact it would be better if I passed functions that implement the conditions and in tests I simply provide some mock. The issue with this approach is the noisiness: we use generics a lot.

A working solution; however, is to make the tested object a spy and mock out the calls to the internal functions.

```<code>systemUnderTest = Mockito.spy(systemUnderTest);
doReturn(true).when(systemUnderTest).checkFirstCondition(....);
</code>```

The concern here is that the SUT's implementation is effectively changed and it may be problematic to keep the tests in sync with the implementation. Is this true? Is there best practice to avoid this havoc of internal method calls?

Note that we are talking about parts of an algorithm, so breaking it out to several classes may not be a desired decision.


问:
Is it feasible to change model relationship mappings and properties in Entity Framework CodeFirst at runtime?
Here's the situation. I have an enterprise application that uses EF Codefirst to map POCOs to an existing database. This has been working fine so far. In fact I would say that it's been working really well.

A situation has been introduced (out of my hands) that involves adding new tables to the database and/or new columns to tables when a customer has purchased an add-on.

There aren't clear domain boundaries. So, I find myself in a difficult position because I need to support an entity at the base product level, but then I need to support the same entity (emphasis on this entity being considered the same) with a few new columns. Additionally, the entity may have new relationships to new tables.

It appears that it is possible to add entities to a schema (see http://romiller.com/2012/03/26/dynamically-building-a-model-with-code-first/ for a general approach) but it doesn't address properties and relationships. Is it possible or even feasible to change a DbContext's schema and models at runtime?

The application is using ASP.NET MVC WebAPI with a repository pattern. So, as a last resort I am considering the possibility that I'll need to stop using EF and replace it with ADO.NET instead, but that (of course) will be a very labor and time intensive process.

Thanks for any help.

答:
It seems to me that changing things at runtime is going to land you in several nested worlds of hurt.

The question I would be asking is whether this is the best way to implement these add-ons. I can see two useful alternatives:

If the add-ons are standard, then you could use Table Per Heirarchy inheritance to represent the different versions of the table. In the data store you would have a single larger table with all the columns, but depending on the user's requirements you could choose different entities that include or exclude the extra data.

If the add-ons are non-standard then you will need different underlying code regardless. In this case different customers will require different implementations entirely and you might use a Dependency Injection container to allow you to switch between options for any given deployment.


问:
Git temporary code-change
My program interacts with another application via a socket communication. The current public version of this application does not support a specific command while the newest trunk does. To be compatible with the current public release, I just need to re-write few lines of code. From the current point on, development must continue with this changed code, but in the future the original code should be used again.

Is it possible to make a partial change to a file temporary with Git? I could create a branch, for instance, and continue developing in this branch. However, when I merge the branch into the master, I want the changed code mentioned above to be reverted to its original code.

Note: I am well aware that I could distinguish between versions of the software, however the changes have also effect on GUI resource files which I can not affect from code other than simply loading a different resource file.

答:
I have been in such a situation for most of the time I've used git. That is, I need some local changes e.g. set some paths in configuration files, that are otherwise commited to version control. Here is my workflow.

I make a commit or a couple of commits with the changes "Local Configuration", "temp", "in progress" etc. Then, when I have finished a feature, I fetch, then rebase, putting

new remote commits at the bottom (this happens by default in a rebase)

my local commits over them

my temporary commits on the top.

Then I can do git push HEAD~2, considering I have two temporary commits. Or better still, use the last meaningful commit's SHA.

Title: Git temporary code-change


答:
Unit tests should treat the classes they test as black boxes. The only thing which matters is that its public methods behave the way it is expected. How the class achieves this through internal state and private methods does not matter.

When you feel that it is impossible to create meaningful tests this way, it is a sign that your classes are too powerful and do too much. You should consider to move some of their functionality to separate classes which can be tested separately.

Title: Is spying on tested class bad practice?


问:
How do I alter an open source library for my own use?
I'm programming in Objective-C. I want to include a camera library, DLCImagePicker, in my project. There is a variable I need to change, but it is private and I have no access to it.

I've thought of a few way to get around this, but am not sure on the best practice way to do it.

I can just copy the code into my own class and alter the variable.

I can alter it directly in the original class. However, I have included this code as a git submodule and I'm thinking that touching the source code is a bad idea in this case, and in general.

Subclassing. I can't imagine how this would work, as the variable is private.

I can perform some action with git that would create my own fork/branch of the project, and alter it there. I have never done this and am very primitive with git.

答:
You're kind of missing the point of open source, which is that in exchange for your use of software you find helpful, you're encouraged to contribute improvements back for everyone to benefit.

So fork the software on github, then make the changes as you would if you owned it.  That means not just exposing a variable to make it easier to hack in external code, but employing proper encapsulation and adding whatever improved methods you need.

Then submit a pull request.  Github has good tutorials on how to do this.  The author will provide suggestions for improvement, then most likely merge it in, which benefits you by not requiring you to maintain a fork and benefits him by getting useful improvements to the code.  In the unlikely event he doesn't accept the change, you have a fork available for your personal use.  Also, most open source licences encourage if not outright require publishing changes, and your github fork fulfills that requirement.


答:
Based on the criteria, " a function X will be executed if either of A and B variables will be lower than 5", only two test need to be made.

```<code>if A < 5 then execute X
elseif B < 5 then execute X
</code>```

There are four cases:

A < 5 and B < 5

A < 5, B >= 5

B < 5, A >= 5

A >= 5 and B >= 5

Title: Equivalence partitioning understanding A<5 and B<5

Body:
I do not understand the following example. It says that a function X will be executed if either of A and B variables will be lower than 5. The go on and explains that there are three valid equivalence classes for inputs:

```<code>A<5, B<5
A=>5 B<5
B>=5 A<5
</code>```

Why there is no class for A>5 and B>5? Is it because this would not be valid class? But why A<5 and B>5 is valid, is it because the function is still dependent on that?

Body:
Based on the criteria, " a function X will be executed if either of A and B variables will be lower than 5", only two test need to be made.

if A < 5 then execute X
elseif B < 5 then execute X

There are four cases:

A < 5 and B < 5

A < 5, B >= 5

B < 5, A >= 5

A >= 5 and B >= 5


问:
Best practices for refactoring parameter file structure in multiple environments
Background info and what I've tried

Within each of two mostly distinct environments, say 'Research' and 'Production', there is a need for a structured parameter file. The file contains things like database connections, tables, and some other parameters, nothing unusual.

The current approach is to have two distinct parameter files, say "params.txt" and "params_prod.txt" (for production). (Also, in case it helps, we're not actually using .txt for this, we're using a markup language, but the details of that don't really matter for this question.)

Most of the information is duplicated between these two files, leading to lots of copy/paste. Plus, in version control, everyone has to manually make changes to two files and we have to trust that they are propagating changes if checking things in.

Needless to say, this leads to headaches to resolve when some divergence happens between the files. We have tried workarounds, like writing tests to check that the files are identical in all the ways they need to be, but this is not a perfect science since the structure of the files can change and the definition of what, exactly, must be identical between them changes too.

I have had one idea:

Just use a single file, but create sub-sections within the file. There can be a sub-section for general parameters that are always shared, another section for things that should be treated as the 'default' parameters (the 'Research' environment settings) and then another section for the 'Production' environment settings.

We already have code that parses the parameter files and instantiates objects, loads data, etc. etc., based on the parameters. We could go back and add some options to that code, such that it loads data according to which sub-section of the parameter file it is told to use and ignores parameters from the other section.

This has some benefits: (1) everything is in one file, so there's no "just trusting" that people are propagating changes. (2) It also does not require copy/paste code since anything that is shared between both environments needs to only appear in one section at the top of one parameter file. (3) If anything, this should make the parameter files themselves more modular and easier to use. (4) We save time/cost that would have been spent creating complicated test-based work-arounds that check whether the files are being propagated together during check-ins with version control. We don't need to do that in this case.

It does have costs too: (1) time spent making the newly formatted parameter file specifications in XSD so we can validate it and ensure it is backwards compatible; (2) costs if we do need to re-code and make our software-that-interfaces-with-parameter-files have options for whether to use 'Research' or 'Production'. (3) If any of the properties that are currently considered to be in the sub-section that is shared, but which suddenly become things where we want to have different options between 'Research' and 'Production', we would then have to refactor all parameter files to move that item down into the other sections.

(3) Seems like the biggest worry, but it also forces us to constantly re-factor these parameter files, which is a good thing in my view. Besides, if we want flexibility about re-assigning a parameter from one sub-section to another, there ought to be better ways to achieve it than duplicating the entire file.

Question

Are there any significant pitfalls that I am failing to realize about the proposed idea regarding don't-repeat-yourself vs. build-in-flexibility trade-offs in parameter file design?

答:
another option is to use a hierarchy of files:

there is a param_prod.txt where all parameters specific to production is set

then there is a param.txt where general parameters are set

to find a parameter you first go into param_prod.txt and if you don't find it there you then check param.txt (if not found there then either use arbitrary default or error)

pros: DRY, easily create another branch, extensible to multiple levels by keeping a list of which files to search

con: not immediately clear where a certain parameter is defined, need to create new format where parameters can be left out (maybe), searching through all files can be slow (use caching for speedup)


问:
Why is "tight coupling between functions and data" bad?
I found this quote in "The Joy of Clojure" on p. 32, but someone said the same thing to me over dinner last week and I've heard it other places as well:

[A] downside to object-oriented programming is the tight
  coupling between function and data.

I understand why unnecessary coupling is bad in an application.  Also I'm comfortable saying that mutable state and inheritance should be avoided, even in Object-Oriented Programming.  But I fail to see why sticking functions on classes is inherently bad.

I mean, adding a function to a class seems like tagging a mail in Gmail, or sticking a file in a folder.  It's an organizational technique that helps you find it again.  You pick some criteria, then put like things together.  Before OOP, our programs were pretty much big bags of methods in files.  I mean, you have to put functions somewhere.  Why not organize them?

If this is a veiled attack on types, why don't they just say that restricting the type of input and output to a function is wrong?  I'm not sure whether I could agree with that, but at least I'm familiar with arguments pro and con type safety.  This sounds to me like a mostly separate concern.

Sure, sometimes people get it wrong and put functionality on the wrong class.  But compared to other mistakes, this seems like a very minor inconvenience.

So, Clojure has namespaces.  How is sticking a function on a class in OOP different from sticking a function in a namespace in Clojure and why is it so bad?  Remember, functions in a class don't necessarily operate just on members of that class.  Look at java.lang.StringBuilder - it operates on any reference type, or through auto-boxing, on any type at all.

P.S. This quote references a book which I have not read: Multiparadigm Programming in Leda: Timothy Budd, 1995.

答:
In Java and similar incarnations of OOP, instance methods (unlike free functions or extension methods) can't be added from other modules.

This becomes more of a restriction when you consider interfaces which can only be implemented by the instance methods. You can't define an interface and a class in different modules and then use code from a third module to bind them together. A more flexible approach, like Haskell's type classes should be able to do that.


答:
Doing marginal changes to open source software for your own needs is possible, but it can easily result in a maintenance nightmare.

Whenever the library updates, you have two options:

ignore the update and all the improvements and bugfixes it brings

merge your change into the new version of the new library

This merging can become more and more complicated should the codebase of the library evolve.

Another option would be to do what Karl Bielefeldt suggests and ask upstream to merge your change and put it into the official version. This, however, would only work under the premises that:

The change is useful for everyone, not just for you (did you consider to implement a setter-method for the private variable instead of just changing the hardcoded value?)

The change follows the conventions and long-term strategy of the project

The library is a bazaar-style project which accepts contributions from anyone without involving lots and lots of red tape. Most larger OSS projects unfortunately do not fall into this category.

Title: How do I alter an open source library for my own use?

Body:
I'm programming in Objective-C. I want to include a camera library, DLCImagePicker, in my project. There is a variable I need to change, but it is private and I have no access to it.

I've thought of a few way to get around this, but am not sure on the best practice way to do it.

I can just copy the code into my own class and alter the variable.

I can alter it directly in the original class. However, I have included this code as a git submodule and I'm thinking that touching the source code is a bad idea in this case, and in general.

Subclassing. I can't imagine how this would work, as the variable is private.

I can perform some action with git that would create my own fork/branch of the project, and alter it there. I have never done this and am very primitive with git.


问:
How to indicate that a class might implement an interface?
Say I have a class User and an interface Administrator. Some users are administrator and can thus implement the interface. Most aren't, however, so it's false to say that "User implements Administrator".

How can I represent that in a class diagram? Should I use the classic implementation arrow, or is there an existing stereotype for a class that can implement an interface?

答:
It makes no sense to say that a class can implement an interface.  Either it does or it doesn't, and that's determined as the code is written.  Specific instances (users) can't make that decision for themselves, although they can set an IsAdministrator flag instead.

If the IsAdministrator flag is insufficient, then (as @superM said) the design you want is subclassing.  A User has some properties.  Some User are actually Administrator, which has additional properties.  Therefore Administrator inherits from User, and should be represented as such.


答:
Object Orientation is fundamentally about Procedural Data Abstraction (or Functional Data Abstraction if you take away side-effects which are an orthogonal issue). In a sense, Lambda Calculus is the oldest and most pure Object-Oriented language, since it only provides Functional Data Abstraction (because it doesn't have any constructs besides functions).

Only the operations of a single object can inspect that object's data representation. Not even other objects of the same type can do that. (This is the main difference between Object-Oriented Data Abstraction and Abstract Data Types: with ADTs, objects of the same type can inspect each other's data representation, only the representation of objects of other types is hidden.)

What this means is that several objects of the same type may have different data representations. Even the very same object may have different data representations at different times. (For example, in Scala, Maps and Sets switch between an array and a hash trie depending on the number of elements because for very small numbers linear search in an array is faster than logarithmic search in a search tree because of the very small constant factors.)

From the outside of an object, you shouldn't, you can't know its data representation. That's the opposite of tight coupling.

Title: Why is "tight coupling between functions and data" bad?

Body:
I found this quote in "The Joy of Clojure" on p. 32, but someone said the same thing to me over dinner last week and I've heard it other places as well:

[A] downside to object-oriented programming is the tight
  coupling between function and data.

I understand why unnecessary coupling is bad in an application.  Also I'm comfortable saying that mutable state and inheritance should be avoided, even in Object-Oriented Programming.  But I fail to see why sticking functions on classes is inherently bad.

I mean, adding a function to a class seems like tagging a mail in Gmail, or sticking a file in a folder.  It's an organizational technique that helps you find it again.  You pick some criteria, then put like things together.  Before OOP, our programs were pretty much big bags of methods in files.  I mean, you have to put functions somewhere.  Why not organize them?

If this is a veiled attack on types, why don't they just say that restricting the type of input and output to a function is wrong?  I'm not sure whether I could agree with that, but at least I'm familiar with arguments pro and con type safety.  This sounds to me like a mostly separate concern.

Sure, sometimes people get it wrong and put functionality on the wrong class.  But compared to other mistakes, this seems like a very minor inconvenience.

So, Clojure has namespaces.  How is sticking a function on a class in OOP different from sticking a function in a namespace in Clojure and why is it so bad?  Remember, functions in a class don't necessarily operate just on members of that class.  Look at java.lang.StringBuilder - it operates on any reference type, or through auto-boxing, on any type at all.

P.S. This quote references a book which I have not read: Multiparadigm Programming in Leda: Timothy Budd, 1995.


问:
How to find bottlenecks in an application?
I'm building an application with lots of components, a lot of which are third-party so I only know what I can get from their documentation.

From time to time, by pure luck, I find out one of these components was pretty heavy and had an option to cache stuff.

I can't stop thinking that if I weren't lucky, one of these components would end up killing the performance of my app and I wouldn't have a clue what to do. I would end up adding more hardware like an idiot.

So how do you find these kind of bottlenecks? I mean I wouldn't have a nice report saying "this part is slow", like it happens with the database.

For example, today I found that a serializer I was using was heavy and wasn't being cached. Are there repeatable steps I could have followed to discover that the serializer was slowing things down?

答:
Better late than never:

So how do you find these kind of bottlenecks? I mean I wouldn't have a
  nice report saying "this part is slow"...

Here's how I find them.

Slowness will not always be localized to any "this part", and if it isn't, that doesn't mean you can ignore it.

ADDED: Responding to the comments, I hoped the video would explain it best, but @gnat has a good point.
I've written a lot on this, and there's a more scientific explanation here.

In a nutshell, you can get more stack samples on wall-clock time, for example from a profiler (if it's a good one).
The result of having a large number of samples is you are not allowed to see the rich information in any of them, but only summary measurements, and those are too vague to tell you what you could fix.

For example, there can be something distributed around the code, so it's not concentrated in any particular routine, that, if fixed, saves 20% of the time. If you look at 10 or 20 samples, it will appear on about 2 to 4 of them, or more, and you will see it.
However, if there are 10000 samples, 2000 of them, or more, will be doing that activity,
but since all you get to see are time measurements of routines, you won't see the problem.

StackOverflow is full of questions of the form "what does this profiler output mean?"
So the common response to much profiler output is either "what is this?" or its cousin "there's no way to speed up this code".

When in fact, there is a way, that you would see if you examined a small number of the samples in detail.

That's the price you pay for all those samples.


答:
Would not solve this with git since in the end you want master to be deployable and working. So it is possible but will take time and effort.

If you can detect which version of the other application you are talking to: Just create a method which detects this and selects the right class / method / whatever you use. So duplicate the part which changes and call the right one.

That makes is easily testable, just create a test for both and you will support always both versions.

The issue here arises from an issues which is further in your application likely. Basically the socket is some kind of datasource. In that you should do handle this kind of issues. For example you could have a datasource per version of the other application or handle this in separate classes.

Title: Git temporary code-change

Body:
My program interacts with another application via a socket communication. The current public version of this application does not support a specific command while the newest trunk does. To be compatible with the current public release, I just need to re-write few lines of code. From the current point on, development must continue with this changed code, but in the future the original code should be used again.

Is it possible to make a partial change to a file temporary with Git? I could create a branch, for instance, and continue developing in this branch. However, when I merge the branch into the master, I want the changed code mentioned above to be reverted to its original code.

Note: I am well aware that I could distinguish between versions of the software, however the changes have also effect on GUI resource files which I can not affect from code other than simply loading a different resource file.


答:
What you want is a Decorator.

An Administrator would be a subclass of User, and its primary member attribute would be a User object.

Thus a Student Adminstrator would be an Administrator containing a Student (which is a subclass of User, right?  The Administrator-specific attributes are set in the Adminstrator class, with the User methods passed through from the User object.

Title: How to indicate that a class might implement an interface?

Body:
Say I have a class User and an interface Administrator. Some users are administrator and can thus implement the interface. Most aren't, however, so it's false to say that "User implements Administrator".

How can I represent that in a class diagram? Should I use the classic implementation arrow, or is there an existing stereotype for a class that can implement an interface?


答:
In theory, loose function-data coupling makes it easier to add more functions to work on the same data.  The down side is it makes it more difficult to change the data structure itself, which is why in practice, well-designed functional code and well-designed OOP code have very similar levels of coupling.

Take a directed acyclic graph (DAG) as an example data structure.  In functional programming, you still need some abstraction to avoid repeating yourself, so you're going to make a module with functions to add and delete nodes and edges, find nodes reachable from a given node, create a topological sorting, etc.  Those functions are effectively tightly coupled to the data, even though the compiler doesn't enforce it.  You can add a node the hard way, but why would you want to?  Cohesiveness within one module prevents tight coupling throughout the system.

Conversely on the OOP side, any functions other than the basic DAG operations are going to be done in separate "view" classes, with the DAG object passed in as a parameter. It's just as easy to add as many views as you want that operate on the DAG data, creating the same level of function-data decoupling as you would find in the functional program.  The compiler won't keep you from cramming everything into one class, but your colleagues will.

Changing programming paradigms doesn't change best practices of abstraction, cohesion, and coupling, it just changes which practices the compiler helps you enforce.  In functional programming, when you want function-data coupling it's enforced by gentlemen's agreement rather than the compiler.  In OOP, the model-view separation is enforced by gentlemen's agreement rather than the compiler.


答:
At the very minimum, I would consider documentation of all major functions and classes and the params they take and the methods/properties they use to be a requirement for a completed project.  This can be done most easily as comments within the code base or by using a wiki, or with something similar to PHPdoc where you add special notations to the comment block above the function or class.  It only takes a few minutes to add relevant comments to code, so doing it this way is relatively painless, especially if you make it a requirement that developers working on that code later also update the documentation.  Even the original coder themselves won't remember everything six months after they have finished that project.  The hard part here is getting everyone disciplined to do it, because honestly, few devs like to write documentation.

Specs, wireframes and development notes should always be kept, even if made redundant later (for historical purposes.)  If they can be kept in a digital, searchable format (wiki, website with search functionality, database) then that greatly cuts down the time required to find something.

Btw, I agree that employing six business analysts just to keep documentation up to date seems like a waste of resources, but some projects (especially those paid for with government grants) may require it as a condition of funding.

Title: How do you decide how much business requirements documentation you need and how to structure it?

Body:
In the past couple of years, I've worked on two projects.

The first one, we used a very agile methodology. It was very much developer driven. As such, changes were very quick and rapid. Code quality was high becuase it was a new system. There was an emphasis on group ownership of the project and knowledge sharing. Most knowledge transfer with new staff etc. was conducted just by walking someone through the code or system and most staff members on the project knew enough of the project to do that.

The project I thought was successful but one of the regrets I have is the amount of documentation was probably inadequate long term. We had a bunch of user stories which were short term specs only relevant for the sprint, and a a bunch of master specs outlining the business processes that was long term which we would keep up to date. We had no tech specs other than a oneNote page with user logins and links to test envrionments/servers etc.

The problem was keeping a balance between putting enough in there so that it would be helpful and not so much that no one will want to read it and be a burden to maintain. I don't think we ever found that balance. The master specs were probably too generic to be useful to someone that wants to understand the system.

The second project is completely opposite. It's an old system and it's very big. We use a waterfall methodology. This project is very much tester driven. As such we have probably too much documentation - there are thousands of pages in hundreds of word documents and there is duplication everywhere. (eg. documents with the same or very similar introduction texts)

There is a big emphasis on keeping this mammoth of documentation perfect. Creating a simple change to the system requires identifying which documents is affected and making minor changes to all of them.

We document things to levels that's probably not neccessary (eg. I found a doco the other day where the File Save dialog in IE was documented) and there is an emphasis on being correct over being readable.

In short, we have half a dozen Business Analysts and their job consists more of keeping the documentation up to date than of actual analysis.

I think both of these projects have bad practices and what would be optimal is somewhere in between the two. This balance probably depends on the system as well, so how do you decide how much documentation you need and also how to structure it so that maintaining doesn't become more cost than benefit.

EDIT - Hi, sorry should've mentioned it before all the answers came along (I only was just able to check). I'm primarily focused on non-technical business requirements here - those that can be consumed not just by developers (audiences may include BAs, managers, testers, stakeholders etc.)


答:
In case you didn't know it already take this insight: The concepts of object-oriented and closures are two sides of the same coin.
That said, what is a closure? It takes variable(s) or data from surrounding scope and binds to it inside the function, or from an OO-perspective you effectively do the same thing when you, for example, pass something into a constructor so that later on you can  use that piece of data in a member function of that instance. But taking things from surrounding scope is not a nice thing to do - the larger the surrounding scope, the more evil it is to do this (though pragmatically, some evil is often necessary to get work done).
Use of global variables is taking this to the extreme, where functions in a program are using variables at program scope - really really evil. There are good descriptions elsewhere about why global variables are evil.

If you follow OO techniques you basically already accept that every module in your program will have a certain minimum level of evil. If you take a functional approach to programming, you are aiming for an ideal where no module in your program will contain closure evil, though you may still have some, but it will be a lot less than OO.

That's the downside of OO - it encourages this kind of evil, coupling of data to function through making closures standard (a kind of a broken window theory of programming).

The only plus side is that, if you knew you were going to use lots of closures to start with, OO at least provides you with an idealogical framework to help organise that approach so that the average programmer can understand it. In particular the variables being closed over are explicit in the constructor rather than just taken implicitly in a function closure. Functional programs that use lots of closures are often more cryptic than the equivalent OO program, though not necessarily less elegant :)


问:
Algorithm for determining the order of property resolution
I have a list of properties, that are bound to some string expression:

property z, expression '[x] + [y]'

  property x, expression '[y] + 1'

  property y, expression '1'

So to solve z, I need first to solve x and y.
My current approximation is this:

```<code>var solved = new List<string>();
while (properties.Count() > 0)
{
   var property = properties.Dequeue();
   var dependencies = FindDependencies(property)
         .Where(x => !solved.Contains(x))
         .ToList();

   // no unsolved dependencies, solve it
   if (dependencies.Count == 0)
   {
       property.Solve();
       solved.Add(property.Name);
   }
   // it can't be solved now, add to the end of queue
   else
   {
        properties.Enqueue();
   }
}
</code>```

This approximation has two problems:

a) I think it is not optimal, because not solved property is added to the end, may be it could be solved sooner and in that case on it dependant properties would not postponed also.

b) Could not get any good exit condition, when it is unsolvable (meaning, that there's circular reference).

Does anybody recognize here existing well known algorithm, or has ideas how to optimize it?

答: Your properties are nodes in a directed acyclic graph (DAG), with the dependencies being edges.  Finding a topological sort will give you the order you need to evaluate the properties.  There are other algorithms to detect cycles to enforce the acyclic property when you add a node.</p>


答:
Tight coupling between data and functions is bad because you want to be able to change each independently of the other and tight coupling makes this hard because you can't change one without knowledge of and possibly changes to, the other.

You want different data presented to the function to not require any changes in the function and similarly you want to be able to make changes to the function without needing any changes to the data it is operating on to support those function changes.


答:
It's about type coupling:

A function built into an object to work on that object can't be used on other types of objects.

In Haskell you write functions to work against type classes - so there are many different types of objects any given function can work against, so long as it's a type of the given class that function works on.

Free-standing functions allow such decoupling which you don't get when you focus on writing your functions to work inside of type A because then you can't use them if you don't have a type A instance, even though the function might otherwise be general enough to be used on a type B instance or type C instance.


答:
On Github, many people are marketing their open source project, rather than storing and sharing it. I noticed just yesterday that the recommended use case for one of the networking libraries I use on a day to day basis does not actually check if the server exists before assuming the connection succeeded.

People want their example to seem incredibly simple, so that you pick up their library and do something with it. Error conditions are an afterthought, because if you have to look at a real-world example (which might be several times as long) compared to the provided example, the provided example will always look prettier.

CPAN has always taken somewhat of a different tack with this - generally it's very clear from the docs what the proper usage of the module is, including any error checking required.

Be more like CPAN, and less like the responsive, expressive, agile, dynamic, synergistic frameworks you find on Github.

Title: Casual projects on Github omit error checking, logging, etc., for the sake of clarity?

Body:
I just started using GitHub to socialize some projects for simple chat and peer-to-peer apps. With respect to coding, is it customary to omit exception handling, error checking, logging, etc., to promote easy-to-understand and 'clean'-looking code, if those additions are not completely necessary to actually run the code?

For instance, here's two extreme examples:

   if( msg != null){
      NodeEvent event = NodeEvent.valueOf(msg.getAction());
      switch (event) {
        case NODE_CONNECTING:
          if( nodeName.isInvalid())
             Utils.log("Invalid node name, ignoring...");
          else{
             String existingNodeAddress = _nodeNameAddressMap.get(nodeName);
             if( existingNodeAddress != null)
                Utils.log("Node address for '" + nodeName + "' updated");
             else
                Utils.log("New node '" + nodeName + "' connected");

             _nodeNameAddressMap.put(nodeName, nodeAddress);
          }
    }
```

<p>Here's the same snippet minus the fluff, although this version can easily crash if fed bad data, but otherwise it will compile and run fine:</p>

<pre class="lang-java prettyprint-override"><code>   NodeEvent event = NodeEvent.valueOf(msg.getAction());
   switch (event) {
     case NODE_CONNECTING:
        _nodeNameAddressMap.put(nodeName, nodeAddress);
</code>```

The clean version is easier to read, obviously, but is brittle. The verbose version is safer, it just looks cluttered.

I'm just curious to know if it's more effective for a social projects to go for the cleaner look at the expense of fragility, allowing those who fork the project to fill in the blanks. A quick survey of github projects and it's clear most go for the clean look.


问:
How do you decide how much business requirements documentation you need and how to structure it?
In the past couple of years, I've worked on two projects.

The first one, we used a very agile methodology. It was very much developer driven. As such, changes were very quick and rapid. Code quality was high becuase it was a new system. There was an emphasis on group ownership of the project and knowledge sharing. Most knowledge transfer with new staff etc. was conducted just by walking someone through the code or system and most staff members on the project knew enough of the project to do that.

The project I thought was successful but one of the regrets I have is the amount of documentation was probably inadequate long term. We had a bunch of user stories which were short term specs only relevant for the sprint, and a a bunch of master specs outlining the business processes that was long term which we would keep up to date. We had no tech specs other than a oneNote page with user logins and links to test envrionments/servers etc.

The problem was keeping a balance between putting enough in there so that it would be helpful and not so much that no one will want to read it and be a burden to maintain. I don't think we ever found that balance. The master specs were probably too generic to be useful to someone that wants to understand the system.

The second project is completely opposite. It's an old system and it's very big. We use a waterfall methodology. This project is very much tester driven. As such we have probably too much documentation - there are thousands of pages in hundreds of word documents and there is duplication everywhere. (eg. documents with the same or very similar introduction texts)

There is a big emphasis on keeping this mammoth of documentation perfect. Creating a simple change to the system requires identifying which documents is affected and making minor changes to all of them.

We document things to levels that's probably not neccessary (eg. I found a doco the other day where the File Save dialog in IE was documented) and there is an emphasis on being correct over being readable.

In short, we have half a dozen Business Analysts and their job consists more of keeping the documentation up to date than of actual analysis.

I think both of these projects have bad practices and what would be optimal is somewhere in between the two. This balance probably depends on the system as well, so how do you decide how much documentation you need and also how to structure it so that maintaining doesn't become more cost than benefit.

EDIT - Hi, sorry should've mentioned it before all the answers came along (I only was just able to check). I'm primarily focused on non-technical business requirements here - those that can be consumed not just by developers (audiences may include BAs, managers, testers, stakeholders etc.)

答:
For design/architecture documentation, I recommend the following approach to our architects and developers:

Use the documentation as a contract at team borders and outside world (APIs, database scheme). That should be available before development of the corresponding parts starts. And because it is a contract, no side may change it without agreement of affected parties

don't put anything in the documentation which is in the code or which is better explained as a comment in the code. So don't bloat it with lists of internal methods and their parameters.

But explain everything in the documentation which is NOT in the code. This includes:

system overview - for education of new team members, or just to avoid explaining it again and again

any guidelines or strategies which you want to have followed through by development (Kind of contract for your team)

architecture or design decisions, and why you picked one alternative over others. You probably put a lot of work and thinking in these decisions, and you will want to avoid that someone changes these decisions without knowing the impact. Some of these decisions create technical debt, and it is a good idea to have it written down so you can work on that later.

any deviations from guidelines which you might have in your company, any why. For transparency.

risks you see and their potential impact (e.g. a your system might have a dependency on a component which is not ready yet, or you might loose some key resources). This is especially important if someone else forced you to take these risks.


问:
Casual projects on Github omit error checking, logging, etc., for the sake of clarity?
I just started using GitHub to socialize some projects for simple chat and peer-to-peer apps. With respect to coding, is it customary to omit exception handling, error checking, logging, etc., to promote easy-to-understand and 'clean'-looking code, if those additions are not completely necessary to actually run the code?

For instance, here's two extreme examples:

   if( msg != null){
      NodeEvent event = NodeEvent.valueOf(msg.getAction());
      switch (event) {
        case NODE_CONNECTING:
          if( nodeName.isInvalid())
             Utils.log("Invalid node name, ignoring...");
          else{
             String existingNodeAddress = _nodeNameAddressMap.get(nodeName);
             if( existingNodeAddress != null)
                Utils.log("Node address for '" + nodeName + "' updated");
             else
                Utils.log("New node '" + nodeName + "' connected");

             _nodeNameAddressMap.put(nodeName, nodeAddress);
          }
    }
```

<p>Here's the same snippet minus the fluff, although this version can easily crash if fed bad data, but otherwise it will compile and run fine:</p>

<pre class="lang-java prettyprint-override"><code>   NodeEvent event = NodeEvent.valueOf(msg.getAction());
   switch (event) {
     case NODE_CONNECTING:
        _nodeNameAddressMap.put(nodeName, nodeAddress);
</code>```

The clean version is easier to read, obviously, but is brittle. The verbose version is safer, it just looks cluttered.

I'm just curious to know if it's more effective for a social projects to go for the cleaner look at the expense of fragility, allowing those who fork the project to fill in the blanks. A quick survey of github projects and it's clear most go for the clean look.

答:
Here's the thing with error checks like the prints you've inserted; they're not really all that necessary if you're using good source control (and if you're using GitHub, you're using Git, so you are). Learn to use it well and you won't have to ask yourself such questions. It also says that you might not be using automated tests in the best possible way.

If I read code like that I might make some assumptions like "This person is kind of an amateur" or "This person doesn't know how to use source control very well". I might also think "This code has been vetted pretty well" or "This person has a good thought process". How I think depends on the situation, but leaving in the prints means I might think the former way more than the latter.

The code you post says something about you as a coder. Just keep that in mind.


问:
What are the pros and cons for the employer of code questions during an interview?
The Joel Test question #11 is: "Do new candidates write code during their interview?". What are arguments for and against to ask new candidates to write code during the interview and to make a decision upon it?</p>

答:
One con I can think of is that it is hard to "code out loud" in front of other people. I find it hard even to type with someone looking over my shoulder, and I'm not alone. I notice when someone calls me over to their workstation to help with something, they suddenly start making typos, selecting the wrong code-completion, even making downright mistakes — none of which they would have made had I not been sitting right there. Hell, I've seen people start using the menu for cut & paste operations, just because they were under observation. This is not normal behavior, and the coders I'm talking about are excellent programmers and quite smart besides.

I recently had an interview in which the interviewer asked me how I would code a particular operation and he said, "Just show me the math." Well, I had to think about the problem first before getting to the math of it, so that had me hemming and hawing. What I put down on the white board at first was embarrassing, and I felt I was losing at that point. I eventually got the A-ha moment and found the answer (actually when it finally occurred to me what he was really asking), but the "mess" I made before I got there made me feel very uncomfortable. Nevertheless, I got the job, but if the interviewer had been less patient I might not have.

I think if you give interviewees a coding task, give them some time alone to work it out on a computer, perhaps even in an IDE they're familiar with. Let them write the code for you and then talk about it. Ask them why they did things a certain way, and whether another way might not be better. You will find out more from that kind of process than by asking them to (figuratively speaking) pee into a cup right in front of you.


问:
Upgrading an app to support iOS5, 6 and 7
We are looking at an app that needs an upgrade. Currently it runs on iOS4, 5 & 6. The upgrade will move to iOS5, 6 & 7. It will also involve some UI changes and new features. I've been reading stuff on iOS7 and looking at things like auto-layout.

What we are trying to figure out is the best way to handle the differences between the various iOS versions. Auto-layout seems like a good idea, but it's not available on iOS 5. There are also API changes to consider between all 3 versions and other new features of iOS7.

So the questions:

How would you handle auto layout given iOS5 does not have it?

Are there any significant differences between the SDKs that you think would cause issues?

Would we be better off with separate code bases?

答: A couple different possibilities for a requirement to support both iOS 6 and 7.  One is to create two different sets of xib's, selected at runtime depending on the OS version of the device.  The other is to also detect the OS version at runtime, and run code to modify UI elements to their desired position and appearance options, specific to the current OS of the device.</p>


问:
Can all business logic be decomposed as a (declarative) state diagram on simple crud operations and conditionals?
This seems an extreme question probably but I'm wondering anyhow:

Can all business logic be decomposed as a (declarative) state diagram on simple crud operations and conditionals?

Already a lot of lower-level domain logic can, and ofen is declaratively defined with ORM-mappings for instance, handling things like:

domain-model schema

validation

uniqueness constraints

ACL/ Role-based authorization, etc

Of course higher-level domain logic exists that often involves coordinating between multiple Domain Objects.

However, it seems ultimately:

This high level business logic really is just a workflow that can be modeled as a state-machine (or probably more extensive as a extended petrinet)

in which all branching is based on conditional logic on some state (i.e: domain object attributes)

the outcome would be a statechange, i.e: a change to domain object attributes (simple crud operations).

If this is the case, could all domain logic be declaratively defined, given a DSL that would support the above workflow, conditional, and CRUD constructs?

If you dismiss this braindump please be insightful while doing so :)

答:
Yes it can, but only in a practically useless sense.

The computation engines we usually use today are ultimately equivalent to Turing machines, which do exactly what you describe (in fact, they do less, because they have only linear-access memory to work with rather then random-access memory, but it can be proved that this makes no difference). But the state machines you would have to operate to encode even a simple application program are so disgustingly, terrifyingly huge that there is no question of actually using this model of computation in practice. It exists only as a theoretically possible mathematical entity of finite size, but on the large side of "finite".

The point of software engineering as a discipline is to find methods to program machines for more complex behaviour with smaller, more comprehensible  programs. Reading and writing individual variables is easier than switching from one state to a neighbouring state that is almost the same except for one subposition in its composite alphabet. Writing loops is easier than leaving markers on an infinite tape and shuttling back and forth until a sentinel value occurs.

That is not to say that state machines don't have their place. When a problem domain can be naturally understood as transitions within a mentally manageable
state space, they can be the most appropriate solution to encode some operation. However, these situations are rare enough that you can basically forget about them until you actually encounter one.


问:
How should I create a combined interface for two logically independent modules?
I'm having trouble coming up with a good way to structure the interfaces for two modules that are logically independent but whose implementations may be combined for the purposes of performance or efficiency.

My specific situation is the replacement of the separate queuing and logging modules in a message routing application with a combined database-backed implementation (let's call it DbQueueLog).  It's easy enough for DbQueueLog to implement both the IQueue and ILogger interfaces so clients of the old queuing and logging modules can use it seamlessly.  The challenge is that the most efficient and performant implementation of DbQueueLog involves combining the EnqueueMessage(Message m) and LogMessage(Message m, List<LogParams> p) methods into an EnqueueAndLogMessage(Message m, List<LogParams> p) method that minimizes the number of cross-process database calls and the amount of data written to disk.  I could create a new IQueueLog interface with these new methods, but I'm uncomfortable with what that would mean if a future iteration of the application moved back to separate queuing and logging modules.

Are there any design approaches to this situation that would allow me to build the efficient, performant DbQueueLog implementation now without permanently coupling together the application's queuing and logging modules?

Edit: The application is built on Windows using C# in case any there are any platform-specific techniques that might be available.

答:
I see two cases here that could be applicable to the situation that call for different approaches.

EnqueueMessage is a special case of LogMessage

Its not entirely clear from the message, but it seems if you're willing to combine EnqueueMessage and LogMessage into a single function that EnqueueMessage is simply a special case (null "p") of LogMessage. If that is the case, rather than combining interfaces I would keep them separate and use composition to your advantage. In this case ILogger would be a member of the class implementing IQueue. The EnqueueMessage method would simply use the instance of ILogger and call its LogMessage method. If in the future the implementation of an IQueue class had to change you would simply no longer instantiate an ILogger.

EnqueueMessage contains different functionality then LogMessage

In this case, I would strongly recommend they be separate classes and not have a combined interface. If they do indeed have different functionality then by combining them together you're breaking encapsulation and creating difficult to maintain code. That said, you do have to balance maintainability against performance. Just be careful you're not overestimating the efficiency gain of combining the implementation. Build it both ways and measure the difference so you can make an informed decision.