答:
The approach I want to take this now is to use packages (Nuget or openwrap) for my shared/utility code and then pull them in to projects as needed using a private server.

The libraries themselves would then be developed independently of the projects they serve which should get you out of lots of VCS issues. As its your libarary you can break the pieces into as many nuget packages as appropriate / desirable (and this includes the ability to have meta packages that pull in several discrete components).

As an aside I'm not sure I'd be overly concerned about code bloat in the general instance - I understand why (historically its has been an issue from time to time) but right now we're at a point where data storage capacity and data transfer speeds are high relative to the size of deployed code. (And to be clear, "not overly concerned" doesn't mean I don't care, just that its probably not a priority.)

Title: Best approach for utility class library using Visual Studio

Body:
I have a collection of classes that I commonly (but not always) use when developing WPF applications.  The trouble I have is that if I want to use only a subset of the classes, I have three options:

Distribute the entire DLL.  While this approach makes code maintenance easier, it does require distributing a large DLL for minimal code functionality.

Copy the classes I need to the current application.  This approach solves the problem of not distributing unused code, but completely eliminates code maintenance.

Maintain each class/feature in a separate project.  This solves both problems from above, but then I have dramatically increased the number of files that need to be distributed, and it bloats my VS solution with tiny projects.

Ideally, I'd like a combination of 1 & 3:  A single project that contains all of my utility classes but builds to a DLL containing only the classes that are used in the current application.

Are there any other common approaches that I haven't considered?  Is there any way to do what I want?

Thank you.


问:
Should an image be able to resize itself in OOP?
I'm writing an app that will have an Image entity, and I'm already having trouble deciding whose responsibility each task should be.

First I have the Image class. It has a path, width, and other attributes.

Then I created an ImageRepository class, for retrieving images with a single and tested method, eg: findAllImagesWithoutThumbnail().

But now I also need to be able to createThumbnail(). Who should deal with that? I was thinking about having an ImageManager class, which would be an app-specific class (there would also be a third party image manipulation reusable component of choice, I'm not reinventing the wheel).

Or maybe it would be 0K to let the Image resize itself? Or let the ImageRepository and ImageManager be the same class?

What do you think?

答:
Basically as Doc Brown already said:

Create a getAsThumbnail() method for the image class, but this method should actually just delegate the work to some ImageUtils class. So it would look something like this:

```<code> class Image{
   // ...
   public Thumbnail getAsThumbnail{
     return ImageUtils.convertToThumbnail(this);
   }
   // ...
 }
</code>```

And

```<code> class ImageUtils{
   // ...
   public static Thumbnail convertToThumbnail(Image i){
     // ...
   }
   // ...
 }
</code>```

This will allow easier-to-look-at code. Compare the following:

```<code>Image i = ...
someComponent.setThumbnail(i.getAsThumbnail());
</code>```

Or

```<code>Image i = ...
Thumbnail t = ImageUtils.convertToThumbnail(i);
someComponent.setThumbnail(t);
</code>```

If the latter one seems good for you, you can also stick to just creating this helper method somewhere.

ContentLicense: CC BY-SA 3.0

Body:
Basically as Doc Brown already said:

Create a getAsThumbnail() method for the image class, but this method should actually just delegate the work to some ImageUtils class. So it would look something like this:

 class Image{
   // ...
   public Thumbnail getAsThumbnail{
     return ImageUtils.convertToThumbnail(this);
   }
   // ...
 }

And

 class ImageUtils{
   // ...
   public static Thumbnail convertToThumbnail(Image i){
     // ...
   }
   // ...
 }

This will allow easier-to-look-at code. Compare the following:

Image i = ...
someComponent.setThumbnail(i.getAsThumbnail());

Or

Image i = ...
Thumbnail t = ImageUtils.convertToThumbnail(i);
someComponent.setThumbnail(t);

If the latter one seems good for you, you can also stick to just creating this helper method somewhere.


问:
What justifies the use of an IDE versus a standard editor?
I find myself using my text editor of choice (vim, nano, gedit, pick your poison) much more often than any IDE as of late.

After noticing my ide shortcuts getting dusty I started to think about this and wonder: what justifies use of an IDE for you opposed to a text editor?

For that matter what rationale would you have for not using an IDE and merely relying on an editor?

答:
Some arguments in favour of "editors":

There are cases where an IDE has not yet been developed or will never be.

With an editor you can make changes "faster" and more surgically.

It needs far less resources (so easier to use many open at the same time)

Because it is the only way to do solve some issues like those described here.

(personal) Sometimes when I have to type everything, I am working more using my concious and am more engaged on what I am typing. Many times I found for example a spelling error in a method (formaqString), which would have gone unnoticed using an IDE.

It makes it easier to work only with using the keyboard (speed/flow)

Mentality of using macros or other time savers.

I use an IDE every day to work, it is difficult to write Java/C# otherwise.

(2) compared with (3): Basically only option to edit files remotely (over ssh / remote desktop) and do minimal changes to a distant server's configuration or files.


问:
Torvalds' quote about good programmer
Accidentally I've stumbled upon the following quote by Linus Torvalds:

"Bad programmers worry about the code. Good programmers worry about
  data structures and their relationships."

I've thought about it for the last few days and I'm still confused (which is probably not a good sign), hence I wanted to discuss the following:

What interpretation of this possible/makes sense?

What can be applied/learned from it?

答:
Code is easy, it's the logic behind the code that is complex.

If you are worrying about code that means you don't yet get that basics and are likely lost on the complex (ie data structures and their relationships).

Title: Torvalds' quote about good programmer


答:
Algorithms + Data Structures = Programs

Code is just the way to express the algorithms and the data structures.

Title: Torvalds' quote about good programmer

Body:
Accidentally I've stumbled upon the following quote by Linus Torvalds:

"Bad programmers worry about the code. Good programmers worry about
  data structures and their relationships."

I've thought about it for the last few days and I'm still confused (which is probably not a good sign), hence I wanted to discuss the following:

What interpretation of this possible/makes sense?

What can be applied/learned from it?


答:
I think he's saying that the overall high-level design (data-structures and their relationships) is much more important than the implementation details (code).  I think he values programmers who can design a system over those who can only focus on details of a system.

Both are important, but I would agree that it's generally much better to get the big picture and have issues with the details than the other way around.  This is closely related to what I was trying to express about breaking up big functions into little ones.

Title: Torvalds' quote about good programmer


问:
Is Object Oriented Programming a solution to complexity?
Do you think Object Oriented Programming is a solution to complexity. Why? This topic may be a bit controversial but my intentions to know the answer of Why from the experts here !</p>

答:
There is no solution to complexity.

In "The Mythical Man-Month", Fred Brooks discusses the difference between accidental and essential complexity in programming.  Accidental complexity is caused by our tools and methods, such as having to write and test additional code in a language because we can't express our ideas directly, and things like that.  New methods and techniques can reduce accidental complexity.  I can write programs faster and better than I could twenty-five years ago, because I have better languages and tools.

Essential complexity comes from the fact that what we try to do with programming is inherently complicated, and that there is an irreducible complexity.  "Essential", in this context, means "relating to the essence of the thing" rather than "very necessary".

Therefore, he claimed that there would be no silver bullet, that writing software would continue to be difficult.

I strongly recommend that you read his book:  specifically, I recommend the Silver Anniversary edition, with an additional essay "No Silver Bullet".  In that, he reviews the proposed solutions to complexity and considers their impact.  (What he finds the most effective is shrink-wrap software - write something complex once, and sell thousands or millions of copies.)

Now, object-oriented programming helps, when done right, by creating abstractions and hiding away complexity.  An object of a class has a certain defined behavior that we can reason from, without caring about the complexity of the implementation.  Properly written classes have low coupling with each other, and divide-and-conquer is an excellent way to deal with complexity if you can get away with it.  They also have high cohesion, in that they're a set of functions and data that relate very closely to each other.

ContentLicense: CC BY-SA 2.5


问:
Compiler design in Lisp
With some googling, I could easily find some documents in compiler design in C, Java, and C# and even in Haskell, but not in Lisp except implementing Scheme/Lisp in Lisp.

Is Lisp not so popular in implementing other (not functional) programming languages?
Do you know of some good documentation about implementing a compiler in LISP?

答: Lisp compilers are pretty conventional, except that the syntax phase is a lot simpler.  It's the data structures in lisp that are unusual compared to other languages.  Lisp targets a virtual machine with a specific set of properties (different depending on the variant).  Google "lisp virtual machine"</p>

OwnerDisplayName: prosseek

Title: Compiler design in Lisp


答:
To expand on Morons' answer a bit, the idea is that understanding the particulars of the code (syntax, and to a lesser extent, structure/layout) is easy enough that we build tools that can do it.  Compilers can understand all that needs to be known about code in order to turn it into a functioning program/library.  But a compiler can't actually solve the problems that programmers do.

You could take the argument one step further and say "but we do have programs that generate code", but the code it generates is based on some sort of input that is almost always hand-constructed.

So, whatever route you take to get to code:  be it via some sort of configuration or other input that then produces code via a tool or if you're writing it from scratch, it's not the code that matters.  It's the critical thinking of all the pieces that are required to get to that code which matter.  In Linus' world that's largely data structures and relationships, though in other domains it may be other pieces.  But in this context, Linus is just saying "I don't care if you can write code, I care that you can understand the things that will solve the problems I'm dealing with".

Title: Torvalds' quote about good programmer


问:
Name for this antipattern? Fields as local variables
In some code I'm reviewing, I'm seeing stuff that's the moral equivalent of the following:

```<code>public class Foo
{
    private Bar bar;

    public MethodA()
    {
        bar = new Bar();
        bar.A();
        bar = null;
    }

    public MethodB()
    {
        bar = new Bar();
        bar.B();
        bar = null;
    }
}
</code>```

The field bar here is logically a local variable, as its value is never intended to persist across method calls. However, since many of the methods in Foo need an object of type Bar, the original code author has just made a field of type Bar.

This is obviously bad, right?

Is there a name for this antipattern?

答: It's a specific case of "improper scoping", with a side of "variable reuse".</p>


答:
It might help to consider what Torvalds said right before that:

git actually has a simple design, with stable and reasonably well-documented data structures. In fact, I'm a huge proponent of designing your code around the data, rather than the other way around, and I think it's one of the reasons git has been fairly successful […] I will, in fact, claim that the difference between a bad programmer and a good one is whether he considers his code or his data structures more important.

What he is saying is that good data structures make the code very easy to design and maintain, whereas the best code can't make up for poor data structures.

If you're wondering about the git example, a lot of version control systems change their data format relatively regularly in order to support new features.  When you upgrade to get the new feature, you often have to run some sort of tool to convert the database as well.

For example, when DVCS first became popular, a lot of people couldn't figure out what about the distributed model made merges so much cleaner than centralized version control.  The answer is absolutely nothing, except distributed data structures had to be much better in order to have a hope of working at all.  I believe centralized merge algorithms have since caught up, but it took quite a long time because their old data structures limited the kinds of algorithms they could use, and the new data structures broke a lot of existing code.

In contrast, despite an explosion of features in git, its underlying data structures have barely changed at all.  Worry about the data structures first, and your code will naturally be cleaner.

Title: Torvalds' quote about good programmer


答:
The only one I'd really recommend is the debugger. An IDE is really an editor with a load of other gubbins added on, but if you can compile by typing make (or up arrow + enter) in a command prompt, then you don't need an IDE. If you can commit to SCM by right clicking in explorer and choosing the right menu item, you don't need an IDE.

Now I know some people need stuff like refactoring support (write your code right the first time :) ) or some integrated GUI designer (but even then, using Visual Studio I use Expression to do my GUI work, not the crappy XAML support in VS), and many people need intellisense and autocomplete (especially for verbose languages like Java and C# that have godallmightlylong names).

But for me, the GUI debugger is the only really good reason to use the IDE. I still use a 'command-line' debugger (well, windbg) but for day-to-day, its the builtin one to VS.

Title: What justifies the use of an IDE versus a standard editor?

Body:
I find myself using my text editor of choice (vim, nano, gedit, pick your poison) much more often than any IDE as of late.

After noticing my ide shortcuts getting dusty I started to think about this and wonder: what justifies use of an IDE for you opposed to a text editor?

For that matter what rationale would you have for not using an IDE and merely relying on an editor?


答:
There are benefits to an IDE. Not all languages have a comprehensive IDE to really tip the scales or it could be prohibitively hard to create one for a said language. Reasons why would would want an IDE? Well lets start with these:

The language has a rich standard API that in IDE popups could help speed development.

There is a lot of boiler-plate code. (Forced try/catch, getters/setters, etc)

Autocomplete can accurately meet your coding needs

Your language unit testing suite is integrated into said IDE.

IDE is aware and supports numerous language common libraries regarding best practices.

Plugins available to make work mo'betta

It isn't so heavy it slows your system

Highly integrated debugger? That helps.

Problem is not all languages really gain a large productivity gain from a comprehensive IDE. I use IDEs for some work I do (Java, C#) but not for others (Python, Ruby, Coldfusion). It all really is a balancing act. Some languages just don't require such a comprehensive suite.

Are there IDEs for each? Sure. Do you always need one? Not really.


答:
For IDE:

--advanced features are wired-up out of the box.

--some features are so specific for your framework that editors have no equivalent.

For editor:

--Keeping your hands on the keyboard.

--your dev environment is the same across all systems

--better scripting for your editor

--some features of an IDE are available with external tools or scripts. (intellisense, goto definition, find references)


答:
I know that OOP is about encapsulating data and behavior together, but I don't think it's a good idea for an Image to have the resize logic embedded in this case, because an Image doesn't need to know how to resize itself to be an Image.

A thumbnail is actually a different Image.  Perhaps you might have a datastructure that holds the relationship between a Photograph and it's Thumbnail (both of which are Images).

I try to divide my programs into things (like Images, Photographs, Thumbnails, etc.) and Services (like PhotographRepository, ThumbnailGenerator, etc.).  Get your data structures right, and then define the services that let you create, manipulate, transform, persist and recover those data structures.  I don't put any more behavior in my data structures than making sure they're created properly and used appropriately.

Therefore, no, an Image shouldn't contain the logic about how to make a Thumbnail.  There should be a ThumbnailGenerator service that has a method like:

```<code>Image GenerateThumbnailFrom(Image someImage);
</code>```

My bigger data structure might look like this:

```<code>class Photograph : Image
{
    public Photograph(Image thumbnail)
    {
        if(thumbnail == null) throw new ArgumentNullException("thumbnail");
        this.Thumbnail = thumbnail;
    }

    public Image Thumbnail { get; private set; }
}
</code>```

Of course that might mean you're doing effort you don't want to do while constructing the object, so I would consider something like this OK too:

```<code>class Photograph : Image
{
    private Image thumbnail = null;
    private readonly Func<Image,Image> generateThumbnail;

    public Photograph(Func<Image,Image> generateThumbnail)
    {
        this.generateThumbnail = generateThumbnail;
    }

    public Image Thumbnail
    {
        get
        {
            if(this.thumbnail == null)
            {
                this.thumbnail = this.generateThumbnail(this);
            }
            return this.thumbnail;
        }
    }
}
</code>```

... in the case where you want a data structure with lazy evaluation.  (Sorry I didn't include my null checks and I didn't make it thread-safe, which is something you'd want if you were trying to mimic an immutable data structure).

As you can see, either of these classes is being built by some kind of PhotographRepository, which probably has a reference to a ThumbnailGenerator that it got through dependency injection.

Title: Should an image be able to resize itself in OOP?

Body:
I'm writing an app that will have an Image entity, and I'm already having trouble deciding whose responsibility each task should be.

First I have the Image class. It has a path, width, and other attributes.

Then I created an ImageRepository class, for retrieving images with a single and tested method, eg: findAllImagesWithoutThumbnail().

But now I also need to be able to createThumbnail(). Who should deal with that? I was thinking about having an ImageManager class, which would be an app-specific class (there would also be a third party image manipulation reusable component of choice, I'm not reinventing the wheel).

Or maybe it would be 0K to let the Image resize itself? Or let the ImageRepository and ImageManager be the same class?

What do you think?

Body:
I know that OOP is about encapsulating data and behavior together, but I don't think it's a good idea for an Image to have the resize logic embedded in this case, because an Image doesn't need to know how to resize itself to be an Image.

A thumbnail is actually a different Image.  Perhaps you might have a datastructure that holds the relationship between a Photograph and it's Thumbnail (both of which are Images).

I try to divide my programs into things (like Images, Photographs, Thumbnails, etc.) and Services (like PhotographRepository, ThumbnailGenerator, etc.).  Get your data structures right, and then define the services that let you create, manipulate, transform, persist and recover those data structures.  I don't put any more behavior in my data structures than making sure they're created properly and used appropriately.

Therefore, no, an Image shouldn't contain the logic about how to make a Thumbnail.  There should be a ThumbnailGenerator service that has a method like:

Image GenerateThumbnailFrom(Image someImage);

My bigger data structure might look like this:

class Photograph : Image
{
    public Photograph(Image thumbnail)
    {
        if(thumbnail == null) throw new ArgumentNullException("thumbnail");
        this.Thumbnail = thumbnail;
    }

    public Image Thumbnail { get; private set; }
}

Of course that might mean you're doing effort you don't want to do while constructing the object, so I would consider something like this OK too:

class Photograph : Image
{
    private Image thumbnail = null;
    private readonly Func<Image,Image> generateThumbnail;

    public Photograph(Func<Image,Image> generateThumbnail)
    {
        this.generateThumbnail = generateThumbnail;
    }

    public Image Thumbnail
    {
        get
        {
            if(this.thumbnail == null)
            {
                this.thumbnail = this.generateThumbnail(this);
            }
            return this.thumbnail;
        }
    }
}

... in the case where you want a data structure with lazy evaluation.  (Sorry I didn't include my null checks and I didn't make it thread-safe, which is something you'd want if you were trying to mimic an immutable data structure).

As you can see, either of these classes is being built by some kind of PhotographRepository, which probably has a reference to a ThumbnailGenerator that it got through dependency injection.


问:
Is there such thing like a "refactoring/maintainability group" role in software companies?
So, I work in a company that does embedded software development, other groups focus in the core development of different products' software and my department (which is in another geographical location) which is located at the factory has to deal with software development as well, but across all products, so that we can also fix things quicker when the lines go down due to software problems with the product.

In other words, we are generalists while other groups specialize on each product.

Thing is, it is kind of hard to get involved in core development when you are distributed geographically (well, I know it really isn't that hard, but there might be unintended cultural/political barriers when it comes to the discipline of collaborating remotely).

So I figured that, since we are currently just putting fires out and somewhat being idle/sub-utilized (even though we are a new department, or maybe that is the reason), I thought that a good role for us could be detecting areas of opportunity of refactoring and rearchitecting code and all other implementations that might have to do with stewarding maintainability and modularity. Other groups aren't focused on this because they don't have the time and they have aggressive deadlines, which damage the quality of the code (eternal story of software projects)

The thing is that I want my group/department to be recognized by management and other groups with this role officially, and I'm having trouble to come up with a good definition/identity of our group for this matter.

So my question is: is this role something that already exists?, or am I the first one to make something like this up?

Edit: What I mean is a group driving refactoring initiatives, not doing all the refactoring work themselves. Much like an open source community to an open source product, now that I think of it.

答:
I've never heard of such a thing at any company that I've worked or interviewed for.  Companies normally only want to pay for new features or changes that have measurable improvements for end users (like performance improvements).  Refactoring code doesn't do this in a directly measurable way.

What I've witnessed at companies that do understand and care about code quality is that developers are encouraged to refactor code as they work.  If you're going to make a change to a file anyway, you might as well clean it up while you're in there.  Add unit tests, refactor, run a static analysis tool, etc.

This has two purposes.  First, the code is actively improved over time without delegating that task exclusively to any developers.  Second, time is only spent improving code that needed to be changed anyway.  If you have modules of code that are never going to be touched again, there's not a lot of sense in spending time on maintaining them.  They're not going to need it.  Better to spend less time by only refactoring those modules that are most likely to change in the future.


答: If a programmer knows someone else will be refactoring their code - he/she will NEVER bother to refactor their own work. Setting up a separate team to refactor is like justifying poor quality code existing in the first place. It's like acknowledging that there will be problems and then modifying your company's organizational structure to cater to it. I admire your passion for quality code, but maybe in this case it IS better to say "not my job". Refactoring should be one by the programmer who writes the code, not by a 3rd party who didn't write it. </p>

Title: Is there such thing like a "refactoring/maintainability group" role in software companies?

Body:
So, I work in a company that does embedded software development, other groups focus in the core development of different products' software and my department (which is in another geographical location) which is located at the factory has to deal with software development as well, but across all products, so that we can also fix things quicker when the lines go down due to software problems with the product.

In other words, we are generalists while other groups specialize on each product.

Thing is, it is kind of hard to get involved in core development when you are distributed geographically (well, I know it really isn't that hard, but there might be unintended cultural/political barriers when it comes to the discipline of collaborating remotely).

So I figured that, since we are currently just putting fires out and somewhat being idle/sub-utilized (even though we are a new department, or maybe that is the reason), I thought that a good role for us could be detecting areas of opportunity of refactoring and rearchitecting code and all other implementations that might have to do with stewarding maintainability and modularity. Other groups aren't focused on this because they don't have the time and they have aggressive deadlines, which damage the quality of the code (eternal story of software projects)

The thing is that I want my group/department to be recognized by management and other groups with this role officially, and I'm having trouble to come up with a good definition/identity of our group for this matter.

So my question is: is this role something that already exists?, or am I the first one to make something like this up?

Edit: What I mean is a group driving refactoring initiatives, not doing all the refactoring work themselves. Much like an open source community to an open source product, now that I think of it.


答:
Usually when people do refactoring, everybody does it using opportunistic refactoring.  So I don't think you will find a common name for such an uncommon practice.

But in your unusual situation, even though having everybody refactor would probably be ideal, it sounds like it would make sense to try it.

However, the same political problems that are currently preventing people from refactoring their own code will most likely bring you down as well (which is probably part of why there is no name for what you are thinking of).  Will other teams be O.K. with you "improving" their code?  What happens the first time you introduce a bug in the course of doing something management doesn't perceive as that valuable in the first place?  What happens when another team doesn't like your new design?

You can't guarantee that you will never cost another team some time.  And almost any argument that you will have a net positive effect could also be applied to letting them refactor themselves.

It's possible that what you are proposing will be acceptable yet letting everyone else refactor will not be - but the only way I can picture this happening is if everyone basically agrees that refactoring is a good thing that saves time in the long run but takes time in the short run, and that your team is the only one with sufficient free time in the short run.  And if other teams trust you to do the refactorings and are willing to deal with any problems it causes them.


问:
How to adopt scrum agile methodology for a small .Net team
I am working on a small product based company developing .Net applications. There is a small team with 5-6 developers. I am a person responsible for planning everything. But my primary role is Software developer.

Now our current project is very unstable because of poor organization. Today my boss called me and told to submit a report about required resources, appropriate methodology, required man power and their salary scales to make the current project success.

I know I don’t have enough organization skills and I need to go deep in my programming skills. So I need to focus only in the development. So I can’t manage the project anymore.

Now I am searching some other ways to make ongoing development success. My questions are

What is the suitable agile methodology to my team?

Is Scrum is suitable for above mentioned scenario?

If we adopt Scrum, what we have to do next? (I think hiring new one
to manage the project is more suitable. So we have to get Scrum
master and some other developers.)

Are there any resources (books, Blogs and etc) to get some tips and
advices to solve this problem?

If Scrum is not a suitable methodology for our scenario, what else
can be more suitable methodology to adopt?

Can anyone give a good solution for my problem?

答:
Yes, scrum may very well be appropriate, but you need to learn more about it.  Ken Schwaber's book will tell you a lot of stuff--like how the Scrum Master is not at all a project manager, and that the team needs to be self-organizing.

The main things you'll need if you're going down the agile route, is a team who can self-motivate and pick up whatever ball gets dropped in front of them, customers who are willing to work closely with the team throughout the development process, and a product owner who has the wherewithal to decide what needs to be within your current and longterm scope and its priority.

So, first you need to learn more about scrum and decide whether it is appropriate.
If you so decide, you'll have to talk to all the stakeholders and see if they are willing to give it a go--hopefully one of them taking the reins as Product Owner.  Then you'll either need to hire or become a Scrum Master.


问:
Does an unexperienced programmer need an IDE?
Reading this other question makes me wonder if I (as an absolute beginner PHP programmer) should stick with WAMP and Notepad++ or to switch to some IDE like Eclipse.

It's understandable that skilled developers will benefit from a big shiny IDE. But why should an absolute beginner use an IDE? Do the benefits outweigh the extra challenge of learning the IDE on top of learning to develop?

Update for clarification:

My goal is to get some basic programming experience. By choosing PHP and WAMP (and FogBugz and Kiln) I hope to avoid having to navigate the tricky / messy OS specifics and compiling etc. and just focus on basic functionality like an online user registration form.

I've got lots of theoretical understanding from university a decade ago but no practical experience. I want to remedy that with a hobby project that would be similar to a real-world sellable web app.

There are so many questions to ask. So many pitfalls I probably have to blunder into. This question is just one piece (my first!) of that puzzle.

答:
I can only share my own experience, as well as some insight into how it effects a developer.

First off, I'll state that I enjoy working in both kinds of environments. Whether I'm using Vim and a makefile with GCC or QtCreator/Visual Studio with their respective environments and compilers purely depends on the project itself and the scale of the application.

For learning, I will occasionally use Vim simply because I hate not knowing how things work and simply going off and writing something through ignorance. When I first learned to code I did it through C# and Visual Studio. This taught me the basics. After a while, though, I decided to take it upon myself to learn how to use Makefiles and a decent Text Editor.

Rei Miyasaka said in a comment that anyone can learn how to use a Makefile within a couple of hours with nothing more than a page's worth of information. I whole heartedly disagree with this, especially for someone new. It can take a few days (at least, in my case it did). Also worth noting is that most documentation on Makefiles spans hundreds of pages, and while you can get a good introduction through a single page, to really know how to use them takes far more time and reading.

In my opinion, if you're ambitious enough and you've just started learning, roll a Linux distro (doesn't matter which one as long as it has a good package manager and is relatively stable - I recommend Linux Mint or even Debian itself), and learn C. Start off with a text editor (syntax highlight, auto-indentation, and line number support are musts - everything else is purely preference), simply learning how to invoke the compiler via CLI. Once you've gotten to the point where you're past learning how to code using only one source file per project is when you then start learning how to write a Makefile. Also worth picking up is Valgrind (if you are writing in C/C++, I'm not sure if it supports other programming languages). After a few months of coding in this environment, as you take on bigger projects, learn an IDE (preferably something FL/OSS) and you should be good to go.

The reason why I suggest this is because using an IDE severely limits a programmer when they are just learning. Autocompletion and project/build management is very nice, however if you don't have any idea on how it works underneath the hood, you're going to be severely limited in terms of debugging and/or figuring out why your application isn't running properly, especially if it is just because of an improper build or compiler setting specified by you or the IDE itself.

Cheers.


问:
Is there any reason why I should use parentheses when calling new in PHP?
When there are no arguments, we have these two options:

```<code>$obj = new MyClass;
</code>```

vs.

```<code>$obj = new MyClass();
</code>```

I always pick the former, just because.

Any thoughts?

答: Include them. It isn't much extra work and it won't confuse people that don't know that leaving them off the parenthesis is an option.</p>


答:
I'd say when you get right down to it, this is really a lack of cohesion, and I might give it the name "False Cohesion".  I'd coin (or if I'm getting it from somewhere and forgetting about it, "borrow") this term because the class appears to be cohesive in that its methods appear to operate on a member field.  However, in reality they do not, meaning the apparent cohesion is actually false.

As for whether it's bad or not, I'd say it clearly is, and I think Stephen C does an excellent job of explaining why.  However, whether it deserves to be called "anti-pattern" or not, I think it and any other coding paradigm could do with a label, since that generally makes communication easier.

Title: Name for this antipattern? Fields as local variables

Body:
In some code I'm reviewing, I'm seeing stuff that's the moral equivalent of the following:

```<code>public class Foo
{
    private Bar bar;

    public MethodA()
    {
        bar = new Bar();
        bar.A();
        bar = null;
    }

    public MethodB()
    {
        bar = new Bar();
        bar.B();
        bar = null;
    }
}
</code>```

The field bar here is logically a local variable, as its value is never intended to persist across method calls. However, since many of the methods in Foo need an object of type Bar, the original code author has just made a field of type Bar.

This is obviously bad, right?

Is there a name for this antipattern?


问:
Why is OOP difficult?
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?

答:
Motivation.  It's harder to learn something when you don't see why, and also when you can't look at what you did and figure whether you did it right or not.

What's needed is small projects that use OO to do useful things.  I'd suggest looking through a book on design patterns and come up with one that is obviously useful and works well with OO.  (I used Strategy the one time I tried it.  Something like Flyweight or Singleton would be bad choices, since they're ways of using objects in general, not using objects to accomplish something.)

Title: Why is OOP difficult?


答: I'd call it the "Wandering Xenophobe". It wants to be left alone but winds up not knowing quite where or what it is. Thus it's a bad thing as others have stated.</p>


答:
It's quite common. I've worked at a software company where this was the norm. You had teams dedicated to implementing new functionality. Then there was a maintenance team who fixed bugs causing problems for clients. The maintenance team fell under the consultancy/support branch of the organisation.

In that case there were benefits to the developers, namely they worked more closely with clients, even spending time out on site. Product teams doing new development didn't interact with the clients at all (a hateful situation imo).

It seems more common in software companies and outsource providers that for in house provision. I'm in finance and I can only think of one bank which has used this structure in the past. That said, it's common that tactical teams might pick up those sort of issues as part of their remit. It's not quite the same, but similar.

If your team is being under-utilised you need to be a little careful. Under-utilised can be translated into "unnecessary cost" quite easily, so your team of X can become a team of X-1 quite quickly.

A preferable approach might be to spend a little more time on the fixes and incorporate some unwritten refactoring time into the bug fix time.

It does depend on how your company works though. The interesting thing is you don't really know, so if you have a team lead, it would be worth discussing it with them. If they don't know, have them talk to the next person up the chain (be involved in that, don't hand it off). If they don't know if that would fit in with what management expects, you might fall further into the cost category rather than the asset category.


答:
Common Lisp Macros are compilers. If you write a macro that transforms some code into Common Lisp that can then be compiled by Common Lisp, then isn't that a compiler? Check out some Common Lisp programming books on Macros, and I think you'll find some very useful information there. I'd recommend On Lisp and Let Over Lambda.

A recent practical example of using Common Lisp macros as a code transformer/compiler is CLPython, but there are all sorts of DSLs/other examples that use this technique.

Another good example is Doug Hoyte's implementation of a Forth compiler in Common Lisp; that one is at the end of Let Over Lambda.

Title: Compiler design in Lisp

Body:
With some googling, I could easily find some documents in compiler design in C, Java, and C# and even in Haskell, but not in Lisp except implementing Scheme/Lisp in Lisp.

Is Lisp not so popular in implementing other (not functional) programming languages?
Do you know of some good documentation about implementing a compiler in LISP?


答:
This is a specific case of a general pattern known as global doorknobbing.  When building a house, it's tempting to buy only one doorknob and leave it lying around.  When someone wants to use a door or cupboard, they just grab that one global doorknob.  If doorknobs are expensive, it can be a good design.

Unfortunately, when your friend comes over and the doorknob is simultaneously used in two different places, reality shatters.  If the doorknob is so expensive that you can only afford one, then it's worth it to build a system that safely allows people to wait their turn for the doorknob.

In this case the doorknob is just a reference, so it's cheap.  If the doorknob was an actual object (and they were reusing the object instead of just the reference), then it might be expensive enough to be a prudent global doorknob.  However, when it is cheap, it is known as a cheapskate global doorknob.

Your example is of the cheapskate variety.


答: Include them; with PHP, you want to be as specific and unambiguous as you can.</p>

Title: Is there any reason why I should use parentheses when calling new in PHP?

Body:
When there are no arguments, we have these two options:

```<code>$obj = new MyClass;
</code>```

vs.

```<code>$obj = new MyClass();
</code>```

I always pick the former, just because.

Any thoughts?


答:
It's not an anti-pattern. Anti-patterns have some property that makes it seem like a good idea, which leads people to do it on purpose; they're planned as patterns and then it goes terribly wrong.

It's also what makes for debates as to whether something is a pattern, an anti-pattern, or a commonly mis-applied pattern that does still have uses in some places.

This is just wrong.

To add a bit more.

This code is superstitious, or at best a cargo-cult practice.

A superstition is something done without a clear justification. It may be related to something real, but the connection is not logical.

A cargo-cult practice is one where you try to copy something that you've learnt from a more knowledgeable source, but you are actually copying the surface artefacts rather than the process (so-named for a cult in Papua New Guinea who would make aircraft control radios out of bamboo hoping to make the WWII Japanese and American planes come back).

In both of these cases there isn't any real case to be made.

An anti-pattern is an attempt at a reasonable improvement, whether in the small (that extra branching to deal with that extra case that has to be dealt with, that leads to spaghetti code) or in the large where you very deliberately implement a pattern that either is discredited or debated (many would describe the singletons as such, with some excluding a write-only - e.g. logging objects or read-only e.g. configuration settings objects - and some would condemn even those) or else where you're solving the wrong problem (when .NET was first brought out, MS recommended a pattern for dealing with disposing when you had both unmanaged fields and disposable managed fields - it does indeed deal with that situation very well, but the real problem is that you've got both types of field in the same class).

As such, an anti-pattern is something that a smart person who knows the language, problem domain and available libraries well will deliberately do, that still has (or is argued to have) a downside that overwhelms the upside.

Since none of us start out knowing a given language, problem domain and available libraries well, and since everyone can miss something as they go from one reasonable solution to another (e.g. start storing something in a field for a good use, and then try to refactor it away but not complete the job, and you'll end up with code like in the question), and since we all miss things from time to time in learning, we have all created some superstitious or cargo-cult code at some point. The good thing, is they're actually clearer to identify and correct than anti-patterns. True anti-patterns are either arguably not anti-patterns, or at have some attractive quality, or at least have some way of luring one into them even when identified as bad (too many and too few layers are both uncontroversially bad, but avoiding one leads to the other).


答:
Lord no, don't do this. think of being in the other position - you write code, you commit it, you do some other work, then you're asked to do some bugfixes on your code, so you notice it's been updated, check it out and see that it bears no resemblance to what you originally wrote.

You lose a lot of traceability in the SCM too - all those moved and renamed methods mean the code you end up with has no direct trace to the original, it often appears too changed to use the diffs.

so all you're doing is pissing people off that you sweep in and click a few refactor tools in your IDE, then tell the other coders that you've improved it for them. Kind of like Slashdot where you occasionally get people replying sarcastic responses to your post with "there, fixed that for you". It might be fine if its humourous on /., it wouldn't be if you did it to my code - I'd tell you it was yours to own from then on and you can perform the maintenance on it.

Now, if you are doing real work on the code, that's different, but refactoring for its own sake, even under the guide of "maintenance" is just going to annoy everyone else, and that goes double for the "want my group/department to be recognized by management and other groups with this role officially" - can you say "political manoeuvring"? Can you imagine what the other departments will say when their code crashes on customer site? "It was fine when we last touched it, it must have been the refactor department that broke it, they touched it last."

What you could try is to persuade management that various parts of the software needs more attention, bring the poor parts up and see if they will devote time to improving it. While this happens, you can suggest you take some of the core groups other workload on to add features to the core product. I doubt you'll get far trying to re-implement core functionality for them, but you will increase your departments ability to add features that can be pushed back onto the core group, then you'll get more dev responsibility.


答:
Well, I can't entirely agree, because you have to worry about all of it. And for that matter, one of the things I love about programming is the switches through different levels of abstraction and size that jump quickly from thinking about nanoseconds to thinking about months, and back again.

However, the higher things are more important.

If I've a flaw in a couple of lines of problems that causes incorrect behaviour, it probably isn't too hard to fix. If it's causing it to under-perform, it probably doesn't even matter.

If I've a flaw in the choice of data structure in a sub-system, that causes incorrect behaviour, it's a much bigger problem and harder to fix. If it's causing it to under-perform, it could be quite serious or if bearable, still appreciably less good than a rival approach.

If I've a flaw in the relationship between the most important data structures in an application, that causes incorrect behaviour, I've a massive re-design in front of me. If it's causing it to under-perform, it might be so bad that it would almost be better if it it was behaving wrong.

And it'll be what makes finding those lower-level problems difficult (fixing low-level bugs is normally easy, it's finding them that can be hard).

The low-level stuff is important, and its remaining importance is often seriously understated, but it does pale compared to the big stuff.

Title: Torvalds' quote about good programmer


答:
This quote is very familiar to one of the rules in "The Art of Unix Programming" which is Torvalds' forte being the creator of Linux.  The book is located online here

From the book is the following quote that expounds on what Torvalds is saying.

Rule of Representation: Fold knowledge into data so program logic can be stupid and robust.

Even the simplest procedural logic is hard for humans to verify, but quite complex data structures are fairly easy to model and reason about. To see this, compare the expressiveness and explanatory power of a diagram of (say) a fifty-node pointer tree with a flowchart of a fifty-line program. Or, compare an array initializer expressing a conversion table with an equivalent switch statement. The difference in transparency and clarity is dramatic. See Rob Pike's Rule 5.

Data is more tractable than program logic. It follows that where you see a choice between complexity in data structures and complexity in code, choose the former. More: in evolving a design, you should actively seek ways to shift complexity from code to data.

The Unix community did not originate this insight, but a lot of Unix code displays its influence. The C language's facility at manipulating pointers, in particular, has encouraged the use of dynamically-modified reference structures at all levels of coding from the kernel upward. Simple pointer chases in such structures frequently do duties that implementations in other languages would instead have to embody in more elaborate procedures.

Title: Torvalds' quote about good programmer


答: Someone who knows code sees the "trees." But someone who understands data structures sees the "forest." Therefore a good programmer will focus more on data structures than on code.</p>

Title: Torvalds' quote about good programmer


答:
Having a group that solely focuses on refactoring and maintainability and implementing it at the expense of other development groups is dangerous to your organization.  There needs to be a commitment from upper management, testers, and all development groups to improve the quality of the code via refactoring to improve maintainability and minimize bugs.  It should be everyone's responsibility to improve the code.  When refactoring needs to be done, then it should be put into the release schedule along with the new features.  Managers need to be educated and understand that taking time to improve the code will pay off in the long run, because technical debt is what will bring a product to a screeching halt if not paid down as part of the ongoing development process. If all you're doing is constantly fighting fires from constant bug fixing, the house is going to burn down, because obviously the house is a fire hazard and needs better construction and renovation.

You group sounds more like it should be a architecture/software staff group dedicated to developing the next generation architecture that will be more maintainable.  Your group should probably focus on how to demonstrate that refactoring pays off to the "pointy-hair" types, encourage developers with new methods and processes, and educate key stakeholders in management to adopt better code quality and get them to "buy-in" to the process. Come up with a plan to migrate products to a better architecture if anything by laying down a simple foundation first. Take the painful lessons everyone has been learning from supporting your products and come up with a plan to mitigate that pain in the future.


问:
What is the opposite of initialize (or init)?
The term will be used as a method name. The method is called when a part of the user interface is hidden (or removed), and it is used to reset values to default and dispose objects that will not be used any more.

Possible names are: release, remove, dispose, clear etc.

Which do you think is the most appropriate?

答:
I'd say it depends on if the action is optional or required (without leaking resources), and if the language supports constructors/destructors. For optional cases I use:

clear

reset

hide (in UI context)

In other cases where the opposite action is required (in languages without constructors/destructors, or when the destructor doesn't release the resource), I use:

init - fini

initialize - deinitialize

create - destroy

In your case I think I would prefer hide. It can still release memory/resources if it wants to - the important thing is that it is optional, i.e. that the destructor would take care of it if you didn't.


问:
Where is sympy library used?
I'd admire the functions of sympy library, what it does is really awesome. The integration functions are really few guys intellectual work. But where exactly we use them practically on computers? If not sympy, do we really need such libraries? If we need them, what languages would satisfy our needs?</p>

答:
In some scientific fields (from experience: mostly mathematics and physics; most engineers prefer to use numerical approximations), often is interesting to calculate exact forms for integrals, derivatives, solutions of differential equations etc...

Thus, SymPy becomes useful for those applications. Also, I imagine it being useful for educational applications (where an exact answer, at least for simple problems, is interesting)

Title: Where is sympy library used?


答:
It depends on what you really mean by refactoring and maintainability - both in theory and in practice.

We used to have a group dedicated to code cleanup and bug fixes. It didn't work out so well, because, not surprisingly, good developers don't want to spend all their time doing code cleanup and bug fixes.

Some organizations choose to have a dedicated "software engineering" team which will tend to spend a good deal of time on code review and mentor the less senior developers on good practices. However, this isn't a true engineering group unless it is heavily involved in the project plans, architecture, test plans, release process, etc. It's critical to have this holistic approach, and preferably some amount of training in software or other engineering, otherwise, it tends to devolve into the "cleanup" above.

Bottom line, developers don't make good janitors in the long haul. And even if you have a true engineering group, that approach tends to work better with cross-functional teams, otherwise other teams may start to ignore or even resent the effort, viewing it as an ivory tower.

Don't have a room full of developers doing nothing but refactoring and rearchitecting. It won't end well.


问:
Hiring at start-ups vs established companies
I have always wondered about this and perhaps experienced folks here can comment on this. I always read that big established software companies such as Google, Microsoft, etc are always wary of hiring software engineers/(or other related professionals) who don't exactly meet the job requirements, and would rather turn down a close "Yes/Maybe" decision.

There's also the general perception that start-ups are generally more willing to hire such "less-than-perfect" employees. But to me this sounds counter-intuitive: start-ups are generally much smaller and resource constrained so they would actually need a "10/10" hire while established companies with bigger teams and more resources would be willing to take a (small) risk on a hire.

Anyone have any comments on this from first-hand experience?

Thanks,

答:
When running my startup Tribily.com I took a risk on some people, which didn't always work out very well. The trick is that I start with every person on a freelance basis. If it works out, we can go look at a contract, although right now all 5 of my engineers are contracted freelancers. I just find it works a lot better for my situation.
That said, we are completely self-funded. I could see this be a lot less of an issue if there's actual funds to hire people :)</p>


问:
I don't understand why algorithms are so special
I'm a student of computer science trying to soak up as much information on the topic as I can during my free time. I keep returning to algorithms time and again in various formats (online course, book, web tutorial), but the concept fails to sustain my attention. I just don't understand: why are algorithms so special?

I can tell you why fractals are awesome, why the golden ratio is awesome, why origami is awesome and scientific applications of all the above. Heck I even love Newton's laws and conical sections. But when it comes to algorithms, I'm just not astounded. They are not insightful in new ways about human cognition at all. I was expecting algorithms to be shattering preconceptions and mind-altering, but time and time again they fail miserably. Perhaps I am doing something wrong in my approach.

Can someone tell me why algorithms are so important to programming?

答:
They are not awesome. It's just an ordinary tool we use in development like any other tools.

Its sole purpose is to provide an answer to a specific problem, avoiding reinventing the wheel again and again, i.e. wasting your time.

Examples:

If you need to sort a list, you would use an existent algorithm, instead of wasting your time inventing your own.

Exception: you know exactly what are you doing and you know that in a particular situation, yours will be faster or somehow better compared to any other.

If you need to hash a password, you would use an existent algorithm, instead of inventing your own, and not only wasting your time, but also introducing a security threat.

Exception: you are a security researcher and have a lab of experts ready to test your new algorithm.


答:
Algorithms are part of your basic toolkit for solving problems. If you have to reinvent a particular type of sort routine every time you need things in a particular order, you are a) going to be slow to develop a solution, and b) almost certainly get it wrong (or at least not right).

When is it best to use a B+-tree? When is locality of reference important and when can you ignore it? Do you always need to fully normalize your relational database design, or are there times when denormalizing it will be better? What patterns work well with interprocess (or interthread) locking, and which ones grind to a halt? Etc., etc.

If you don't understand how to think about algorithms (created by other people or by yourself), then you will never advance past being a simple coder.

Title: I don't understand why algorithms are so special

Body:
I'm a student of computer science trying to soak up as much information on the topic as I can during my free time. I keep returning to algorithms time and again in various formats (online course, book, web tutorial), but the concept fails to sustain my attention. I just don't understand: why are algorithms so special?

I can tell you why fractals are awesome, why the golden ratio is awesome, why origami is awesome and scientific applications of all the above. Heck I even love Newton's laws and conical sections. But when it comes to algorithms, I'm just not astounded. They are not insightful in new ways about human cognition at all. I was expecting algorithms to be shattering preconceptions and mind-altering, but time and time again they fail miserably. Perhaps I am doing something wrong in my approach.

Can someone tell me why algorithms are so important to programming?


答:
Algorithms are a very central part of any kind of computation or computer program. In fact, computer programs are only a bunch of algorithms slapped together with some fancy structured data. That's it. Algorithms + Data Structures = Programs.

A computer program consists of logical rules which it follows. Such rules are structured as algorithms. Rules alone are useless, as they do not operate on anything - they lack substance for which they are meaningful. Just like it is meaningless to try to spoon food from an empty plate - without food the process yields nothing. It's useless. But when you add that substance, in this context food or data it all becomes meaningful. There's something to operate on.

Algorithms then define how to operate. What exactly to do to solve a problem. Different kinds of algorithms solve different kinds of problems, it is important to understand how the algorithm solves the problem, because without understanding of what one's doing it's impossible to see things from higher perspective. Similarly, one can't build a bridge by just placing brick after another. There has to be deeper understanding of what exactly one is doing, what problem they are solving and why they do it the way they do. In context of computing and computer programming, understanding and studying of algorithms give this understanding.


答: What algorithms demonstrate about human cognition is that it is possible for us to create nearly infinitely complex applications, with only the requirement to solve relatively minor, immediate problems. This because generations of previous problems have been solved and encapsulated in algorithms, which can simply be used opaquely without knowledge of how those algorithms were developed or how they function.</p>


答:
I think there are few examples because of lack of motivation.

Normally when you implement a compiler or an interpreter the point is raising the level of abstraction. It makes a lot of sense to implement an assembler writing in machine code, then a C compiler using the assembler, then a Python interpreter using the C compiler...

Staying on the same level or going in the opposite direction is not nonsense but a lot less natural... and is done mainly for portability. Some cases are implementing an assembler (for a different processor or for a generic processor) using an higher level language, bootstrapping a compiler, implementing a virtual machine.

With Lisp the whole idea of language level doesn't fit that well (here I mean a full Lisp that includes general full macros, reader macros and that is not allergic to side effects, not a self limited version that only allows template based macros or forces you to a functional programming model).

Lisp is neither an high level language, nor a low level one... more than a language Lisp is a meta-language in which you shape the language that would be ideal to solve the problem you are facing. Creating language abstraction levels is just normal programming in Lisp and doesn't require a new language, compiler or interpreter.

In Lisp you don't need to implement a whole different language if you need a specific abstraction (e.g. exceptions, objects), you just implement that abstraction for use within Lisp. There have been systems programmed down from hardware control up to artificial intelligence all in Lisp.

For example in Common Lisp there is support for object oriented programming (and more sophisticated than in C++) but if it wasn't there it could be just coded... and indeed it was a regular library before Common Lisp. In C instead the only way was to create a full compiler from C++ to C to be able to get there.

Title: Compiler design in Lisp


问:
Dependency injection with n-tier Entity Framework solution
I am currently designing an n-tier solution which is using Entity Framework 5 (.net 4) as its data access strategy, but am concerned about how to incorporate dependency injection to make it testable / flexible.

My current solution layout is as follows (my solution is called Alcatraz):

Alcatraz.WebUI: An asp.net webform project, the front end user interface, references projects Alcatraz.Business and Alcatraz.Data.Models.

Alcatraz.Business: A class library project, contains the business logic, references projects Alcatraz.Data.Access, Alcatraz.Data.Models

Alcatraz.Data.Access: A class library project, houses AlcatrazModel.edmx and AlcatrazEntities DbContext, references projects Alcatraz.Data.Models.

Alcatraz.Data.Models: A class library project, contains POCOs for the Alcatraz model, no references.

My vision for how this solution would work is the web-ui would instantiate a repository within the business library, this repository would have a dependency (through the constructor) of a connection string (not an AlcatrazEntities instance).  The web-ui would know the database connection strings, but not that it was an entity framework connection string.

In the Business project:

```<code>public class InmateRepository : IInmateRepository
{
    private string _connectionString;

    public InmateRepository(string connectionString)
    {
        if (connectionString == null)
        {
            throw new ArgumentNullException("connectionString");
        }

        EntityConnectionStringBuilder connectionBuilder = new EntityConnectionStringBuilder();

        connectionBuilder.Metadata = "res://*/AlcatrazModel.csdl|res://*/AlcatrazModel.ssdl|res://*/AlcatrazModel.msl";
        connectionBuilder.Provider = "System.Data.SqlClient";
        connectionBuilder.ProviderConnectionString = connectionString;

        _connectionString = connectionBuilder.ToString();
    }

    public IQueryable<Inmate> GetAllInmates()
    {
        AlcatrazEntities ents = new AlcatrazEntities(_connectionString);

        return ents.Inmates;
    }
}
</code>```

In the Web UI:

```<code>IInmateRepository inmateRepo = new InmateRepository(@"data source=MATTHEW-PC\SQLEXPRESS;initial catalog=Alcatraz;integrated security=True;");

List<Inmate> deathRowInmates = inmateRepo.GetAllInmates().Where(i => i.OnDeathRow).ToList();
</code>```

I have a few related questions about this design.

Does this design even make sense in terms of Entity Frameworks capabilities?  I heard that Entity framework uses the Unit-of-work pattern already, am I just adding another layer of abstract unnecessarily?

I don't want my web-ui to directly communicate with Entity Framework (or even reference it for that matter), I want all database access to go through the business layer as in the future I will have multiple projects using the same business layer (web service, windows application, etc.) and I want to have it easy to maintain / update by having the business logic in one central area.  Is this an appropriate way to achieve this?

Should the Business layer even contain repositories, or should that be contained within the Access layer?  If where they are is alright, is passing a connection string a good dependency to assume?

Thanks for taking the time to read!

答:
A few quick comments.  I personally probably wouldn't pass a connection string.  If anything I would try and create interfaces maybe for the repositories and just pass the interfaces around?  Have the repositories implement or expose a IOW interface.

This way it doesn't event need to be a database that implements your repositories.  they could be an in memory cache, or anything.  Maybe then you could use some sort of dependancy injection framework to instantiate these even?

So in answer to some of your questions:

Yes, I think it's ok

I would still have the UI reference the EF project and the buisness layer reference interfaces that the EF repository layer implements.  That way other projects could still use the same assemblies but they have the flexibility to swap out if desired?

hmmm, Probably the repositories in the access layer but implementing an interface definition exposed in the business layer??

These are just some thoughts to mull over.


答:
Others have already addressed algorithms in the cookbook sense, so I'll try to address the theory.

It's easy to get the idea that a simple and quick algorithm is adequate - and then your code gets used for real-world problems with larger data sets and it's not just slow, it's unusable.

A lot of the theory is about how time and space requirements grow as the problem size increases, and it's important because naive choices are often very fast on small data sets, but with unacceptable growth.

A lot of programmers never need to analyze an algorithm for themselves, and many get away with misunderstandings about the theory, but anyone who thinks a bubblesort is an adequate way to sort a potentially huge dataset should be shot.

Another thing is that while a lot of basic algorithms are precisely that, some of the ideas you encounter for more sophisticated algorithms really are surprising and definitely awesome.

But... well, if shattering preconceptions is your yardstick, you first need relevant preconceptions to shatter. Unless it's an understanding of what exponential time (or worse) really means as your problem sizes increase, algorithm theory doesn't really aim to shock.


问:
Showing user and userinterface interaction on a sequence diagram
I need to draw a sequence diagram and I am not sure exactly if it is correct to show interaction between user and user interface in this diagram. For example I want to make a panel visible or invisible based on choosing a check box by user. Is it correct to have it on a sequence diagram? and how can I draw it?

thanks

答: UML allows to you to place an actor in a sequence diagram. The actor ("user") has a lifeline like any object instance. I'd say that "checking the check box" is the message, that the user sends to your check box instance. Alternatively you can take the IBM approach and let the initial event be an incoming message to your first instance.</p>


答:
What do you mean "not awesome"?

How did your first sorting function look like? Did it take N log(N) time to sort the array? Or was it a variation of insertion/selection/bubble sort?

Would Internet search engines be possible without algorithms? Would people use Google as often as they do if it took as little as 2 minutes to search through 20 billion of pages they index? Try to create an application which will allow your to text-search a folder with a mere 1GB of text files and see how that goes without algorithms.

I find looking for ways to decrease the running time of a piece of code totally awesome. You are provided knowledge others studied for decades and able to grasp it in a matter of days, or hours. It's like standing on the shoulders of giants.


问:
How to create distinct set from other sets?
While solving the problems on Techgig.com, I got struck with one of the problems. The problem is like this:

A company organizes two trips for their employees in a year. They want to know whether all the employees can be sent on the trip or not. The condition is that no employee can go on both the trips. Also to determine which employees can go together the constraint is that the employees who have worked together in past won't be in the same group. Examples of the problem:

Suppose the work history is given as follows: {(1,2),(2,3),(3,4)}; then it is possible to accommodate all the four employees in two trips (one trip consisting of employees 1& 3 and the other having employees 2 & 4). Neither of the two employees in the same trip have worked together in past.

Suppose the work history is given as {(1,2),(1,3),(2,3)} then there is no possible way to have two trips satisfying the company rule and accommodating all the employees.

Can anyone tell me how to proceed on this problem?

答:
You could to write a standard complete search to solve the problem in a primitive but reliable way. Simply assign any employee (arbitrarily) to trip 1, then assign the next employee to either 1 or 2, etc., back-tracking whenever you can't place the next employee on either trip, and terminating if all employees are assigned.

The more interesting question is whether the search can be made more efficient. In this case, since past co-workers cannot travel together, you can immediately assign all co-workers of anyone you place on trip 1 to trip 2 - and then you can assign all of their co-workers to trip 1, for the same reason, and so on until constraint 2 doesn't give you any new information. If you encounter any constraint violation during this process, the problem is unsolvable. This will not find a solution faster than the naive solution, but it can prove the absence of a solution much faster, since you don't have to backtrack your way through the entire solution space. An additional optimization could be to place the employees with the most co-workers first, since this excludes more parts of the solution space than placing a solitary worker.


答:
Here is a hint. I see that you can solve this in 2 steps. as follows:

Part 1 - Identify Eligible Pairs

First, we could identify, according to requirements rules, pairs of employees who could travel together on one trip using the matrix below based on your stated case:  {(1,2),(2,3),(3,4)}

Cells with x (as well as the diagonal cells) represent instances where 2 employees can travel together because they worked together.

Also, it is implied that travelTogether(i,j)=travelTogether(j,i) (Blue cells are deduced from input) and that

travelTogether(i,i)="x" (meaning No, or false).

non-marked cells indicate 'yes' or true, that is the pair travelTogether(i,j) can travel together on the same trip. For example, employee 1 can travel with 3 and/or 4. However, Employee 3 can only travel with 1.

Part 2. Identify Candidates per Trip

-You have 2 trips.

-You have pairs that must travel together (or not travel at all) such as Employee 3.

-You don't have no maximum capacity per trip.

For each employee determine number of available travel mates.

Sorting the employees on that number of available travel mates we get:

So Each of the employees 2 and 3 can choose 1 trip mate. Starting by the 2 (arbitrary selection), you place 2 with its only possible mate 4. This leaves 3 and 1 to travel together. You could then have 1 trip to include (2,4) and another for (3,1).

Title: How to create distinct set from other sets?

Body:
While solving the problems on Techgig.com, I got struck with one of the problems. The problem is like this:

A company organizes two trips for their employees in a year. They want to know whether all the employees can be sent on the trip or not. The condition is that no employee can go on both the trips. Also to determine which employees can go together the constraint is that the employees who have worked together in past won't be in the same group. Examples of the problem:

Suppose the work history is given as follows: {(1,2),(2,3),(3,4)}; then it is possible to accommodate all the four employees in two trips (one trip consisting of employees 1& 3 and the other having employees 2 & 4). Neither of the two employees in the same trip have worked together in past.

Suppose the work history is given as {(1,2),(1,3),(2,3)} then there is no possible way to have two trips satisfying the company rule and accommodating all the employees.

Can anyone tell me how to proceed on this problem?


问:
Why do HDFS clusters have only a single NameNode?
I'm trying to understand better how Hadoop works, and I'm reading

The NameNode is a Single Point of Failure for the HDFS Cluster. HDFS is not currently a High Availability system. When the NameNode goes down, the file system goes offline. There is an optional SecondaryNameNode that can be hosted on a separate machine. It only creates checkpoints of the namespace by merging the edits file into the fsimage file and does not provide any real redundancy. Hadoop 0.21+ has a BackupNameNode that is part of a plan to have an HA name service, but it needs active contributions from the people who want it (i.e. you) to make it Highly Available.

from http://wiki.apache.org/hadoop/NameNode

So why is the NameNode a single point of failure? What is bad or difficult about having a complete duplicate of the NameNode running as well?

答:
Why does the design of HDFS have a single name node? Simplicity. According to http://hadoop.apache.org/common/docs/r0.20.2/hdfs_design.html#NameNode+and+DataNodes:

The existence of a single NameNode in a cluster greatly simplifies the
  architecture of the system. The NameNode is the arbitrator and
  repository for all HDFS metadata.

You can have a secondary name node that can take over when the primary fails (see http://hadoop.apache.org/common/docs/current/hadoop-yarn/hadoop-yarn-site/HDFSHighAvailability.html) and there are design proposals for distributed name nodes but, as far as I know, none are implemented reliably at this time.


答:
You say your "current project is very unstable because of poor organization." In response, your boss has asked the "person responsible for planning everything" whose primary job is a "Software developer" but "cannot manage the project any more" to do upfront planning. I am not criticizing your ability either as a software developer or a project manager but I suspect there may be bigger problems here that a development methodology cannot solve. Let me speculate on some of your issues and how Scrum may or may not help.

Scrum is great for handling imprecise or changing requirements. The team implements the requirements and produces a release that the product owner (customer) sees and suggests improvements in future sprints. It is especially good when the product owner does not know exactly what is wanted by "will know it when they see it."

However, Scrum will not force the creation of such requirements. If you do not have access a customer representative to be a product owner, some of the advantages of Scrum will be lost.

Scrum is a great way to demonstrate progress. If people are losing faith that you can deliver something, providing a regular cadence of visible improvements can help greatly.

However, Scrum does not work as well when you have immovable deadlines with required features. Indeed, no development methodology does. Scrum will help you get a subset of your features implemented with good quality but it is not a silver bullet.

Scrum can also be difficult to explain to non-technical people used to dictating deadlines and seeing detailed upfront planning. Many people hear "plan as you go" as "cowboy coding" and baulk at the apparent loss of control. If you want to implement Scrum, it may be easier to pick a less critical project and demonstrate it working. Otherwise, if you implement it here and the project fails, it will be much harder to use it for future projects.

Title: How to adopt scrum agile methodology for a small .Net team

Body:
I am working on a small product based company developing .Net applications. There is a small team with 5-6 developers. I am a person responsible for planning everything. But my primary role is Software developer.

Now our current project is very unstable because of poor organization. Today my boss called me and told to submit a report about required resources, appropriate methodology, required man power and their salary scales to make the current project success.

I know I don’t have enough organization skills and I need to go deep in my programming skills. So I need to focus only in the development. So I can’t manage the project anymore.

Now I am searching some other ways to make ongoing development success. My questions are

What is the suitable agile methodology to my team?

Is Scrum is suitable for above mentioned scenario?

If we adopt Scrum, what we have to do next? (I think hiring new one
to manage the project is more suitable. So we have to get Scrum
master and some other developers.)

Are there any resources (books, Blogs and etc) to get some tips and
advices to solve this problem?

If Scrum is not a suitable methodology for our scenario, what else
can be more suitable methodology to adopt?

Can anyone give a good solution for my problem?


问:
What are the best education options for software engineers after an undergraduate degree?
Having recently completed a BSC (computer science), I am working as software engineer.  With one year of experience, what educational options are available to me?  I want to move further in management.  </p>

<p>Please provide suggestions.  I am considering a MSC but I got negative reply from lots of people. </p>

答:
Why do you want to become a manager? If you just want to be a manager and move into any management position as fast as possible, it is hard to go past a Master of Business Administration (MBA). Learn about finance, budgeting and lots of things that this stack exchange site won't be able to help you with.

If you want to become a manager because you like dictating the design and direction of software projects, you have two options. The first is to become a technical lead or software architect. In this case, start focusing on design and patterns, learn about networking, multiple programming languages and libraries and the wonderful varied thing that is software development these days.

Formal training may help here but many Master of Science courses in IT are rebadged Bachelor degrees for those who are either moving into the industry or want to update their skills. Doing a more research oriented Masters will help if you want to push yourself or move into research but it sounds like that is not what you want. Simply picking up the nearest interesting looking software development book is probably the best place to start.

If you want to move into the more organization aspects, consider a Certified Scrum Master (CSM) and/or Project Management Professional (PMP). These will help you to learn how to organize and plan software development releases.

That said, irrespective of why you want to become a manager, the most important thing you need is to "do". You only have one year of experience. While that does not disqualify you from management, do not discount the value of experience. It is one thing to complete a programming assignment for a university course. It is another to single-handedly take responsibility for a project that your boss is depending on you to fix. Some things just cannot be taught.


答:
Here's my take on this:

Beginners are the only people that need IDE. This is because of debugging -- beginners still can have problems understanding how program's execution works, and stepping through the code can help with that.

Mediogre programmers can speed up their programming process because IDE's provide features that let you easier navigate in large source repositories and find where each symbol is located in the source code. They don't need ide any longer, but it sometimes makes life easier.

Advanced programmers do not need IDE. They've done it long enough that IDE's user interface is just too slow for them - pressing a key and waiting for response just takes too long time - instant response is required in order to not waste time. Navigating the source code is not the main priority, since they can remember where every piece of code is located in - they did read the whole code before modifying anything.

Title: Does an unexperienced programmer need an IDE?

Body:
Reading this other question makes me wonder if I (as an absolute beginner PHP programmer) should stick with WAMP and Notepad++ or to switch to some IDE like Eclipse.

It's understandable that skilled developers will benefit from a big shiny IDE. But why should an absolute beginner use an IDE? Do the benefits outweigh the extra challenge of learning the IDE on top of learning to develop?

Update for clarification:

My goal is to get some basic programming experience. By choosing PHP and WAMP (and FogBugz and Kiln) I hope to avoid having to navigate the tricky / messy OS specifics and compiling etc. and just focus on basic functionality like an online user registration form.

I've got lots of theoretical understanding from university a decade ago but no practical experience. I want to remedy that with a hobby project that would be similar to a real-world sellable web app.

There are so many questions to ask. So many pitfalls I probably have to blunder into. This question is just one piece (my first!) of that puzzle.


问:
Bug severity classification issues
In a book I have, there is a following classification of defect:

Critical : A defect receives a “critical” severity level if one or more critical
system functionalities are impaired by a defect with is impaired and there
is no workaround.

High: A defect receives a “high” severity level if some fundamental system
functionalities are impaired but a workaround exists.

Medium: A defect receives a “medium” severity level if no critical functionality
is impaired and a workaround exists for the defect.

Low: A defect receives a “low” severity level if the problem involves a
cosmetic feature of the system.

To be honest, I do not get it.. For example point 2. What if fundamental but not critical feature is impaired and there is NOT a workaround. The same for point 3: what if no critical functionality is affected but there is no workaround?
E.g. optional field in the registration form does not work. No workaround but barely an issue.

答:
You have a book making suggestions how to categorize issues, and the suggestions leave out some intermediate cases - because your book just tries you to give you a rough guideline how things could be classified, no less, no more. Just like any book, such rules should not stop you from thinking by yourself.

Think about this in context of your specific real-world case (for example, when implementing an issue tracker in an organization, for specific software system) - how do you want the issues to be categorized? Where do you draw the line between "critical" and "fundamental" features in your context (is there even a difference)? Are those 4 categories those you need, do you need more, do you need less? Perhaps your issue tracker allows to enter attributes for both "importance of the feature affected" and "does workaround exist"?

Title: Bug severity classification issues


答: One more point - if you're looking for algorithms that bear any semblance to human cognition, then perhaps you've simply haven't been exposed to them during your studies. I'm talking mostly about topics from the field of artificial intelligence (expert systems, neural networks, metaheuristics), which are usually taught in advanced classes, or even not at all.</p>


问:
How do inheritance and composition differ?
I'm wondering about the differences between inheritance and composition examined with concrete code relevant arguments.

In particular my example was:

Inheritance:

class Do:
    def do(self):
        self.doA()
        self.doB()

    def doA(self):
        pass

    def doB(self):
        pass

class MyDo(Do):
    def doA(self):
        print("A")

    def doB(self):
        print("B")

x=MyDo()
```

<p>vs <strong>Composition</strong>:</p>

<pre class="lang-python prettyprint-override"><code>class Do:
    def __init__(self, a, b):
        self.a=a
        self.b=b

    def do(self):
        self.a.do()
        self.b.do()

x=Do(DoA(), DoB())
</code>```

(Note for composition I'm missing code so it's not actually shorter)

Can you name particular advantages of one or the other?

I'm think of:

composition is useful if you plan to reuse DoA() in another context

inheritance seems easier; no additional references/variables/initialization

method doA can access internal variable (be it a good or bad thing :) )

inheritance groups logic A and B together; even though you could equally introduce a grouped delegate object

inheritance provides a preset class for the users; with composition you'd have to encapsule the initialization in a factory so that the user does have to assemble the logic and the skeleton

...

Basically I'd like to examine the implications of inheritance vs composition. I heard often composition is preferred, but I'd like to understand that by example.

Of course I can always start with one and refactor later to the other.

答:
An important thing to mention is that inheritance should not be for the sole purpose of code re-use, use delegation/composition for this.

Composition would be when we have a class say BroadbandConnection with a method called connection(). Then your manager says we want to add encryption, so you create a class BroadbandConnectionWithEncryption. Your natural instinct may be to use inheritance and then make the new class BroadbandConnectionWithEncryption derive from BroadbandConnection.

Drawback's to this is that the creator of the initial class had not designed it for inheritance so you would need to change its definition to make the method connection() virtual so you can override its behavior in the derived class. This is not always ideal. A better idea is to use delegation here for the purpose of code reuse.

class BroadBandConnection
{
   public:
   void Connection (string password)
   {
      //connection code.
   }
};

class BroadBandConnectionWithEndcryption
{
   public:
   void Connection (string password)
   {
       mbroadbandconnection.Connection(password);
       //now do some stuff to zero the memory or
       //do some encryption stuff
   }

   private:
   BroadBandConnection mbroadbandconnection;
};
```


问:
Object Oriented Programming Language performance ranking
After reading this post about ideal programming language learning sequence, I am wondering what would have been the answers if the question was performance -instead of learning- oriented ?

Since there are many programming languages I chose to ask the question for OOL to be the least subjective. But any thought or comparison about no-OOL are appreciated :D

If we omit the programming effort, time and costs. What is your ranking of the most powerful object oriented languages ?

答:
I would say Java for rapid application development, and C++ for raw power.

Java has numorous libraries thta make development much simpler - example being the Swing API which make GUI development almost ridiculously easy, especially with an IDE like Netbeans. Also file I/O is much easier (IMO) in Java than C/C++. Java also has the advantage of being easily ported to other platform since it runs in a virtual machine.

C++ has long been used in the graphics community. In my understanding, it is used because it works closely with the hardware (being loosely typed and compiled, not interpreted in any way) but still uses object-oriented principles for structure and organization. The compilable aspect is important for GPU programming. Also, I don't think you can drop ASM instruction in a Java program. The combination of speed and flexibility makes C++ ideal for graphics processing and other real-time applications.

So, in short, whichever language fits best for your application. These are just the two object-oriented languages that I am most familiar with; there may be others as well that are better than these in certain applications.


答:
Inheritance: Clients deal with instances of MyDo (or other subclasses). They choose the behavior they want by selecting a given subclass and using it. Best choice when you want to deliver a predetermined and immutable set of behaviors to the client.

Composition: Clients deal directly with instances of Do. They can choose he behavior they want by configuring the object, or by using an appropriate factory method. They may even change an object's behavior by reconfiguring it on the fly. Best choice when you want to give the client freedom to customize an object.

Imagine that you're an automobile manufacturer. You've got three models: Scoot, Zip, and Fly. All three are based on a common chassis and drive train (which you call Base internally) but have different body styles, interiors, etc. You don't sell Base as a product; it's just the foundation for the models that you do sell and not even manufactured as a separate assembly, it's just the common set of characteristics that the three models share. Scoot, Zip, and Fly are complete packages -- they're like subclasses of Base. All three models are available with various dealer installable options: sunroof, stereo, rocket boosters, etc.

When deciding between inheritance and composition, consider what you want to provide to users. Do you want a given feature to be baked into the product like the wheel base, or do you want it to be a dealer installable option, like a navigation system? Sometimes the choice is obvious; other times it's a matter of design choices.

Title: How do inheritance and composition differ?

Body:
I'm wondering about the differences between inheritance and composition examined with concrete code relevant arguments.

In particular my example was:

Inheritance:

class Do:
    def do(self):
        self.doA()
        self.doB()

    def doA(self):
        pass

    def doB(self):
        pass

class MyDo(Do):
    def doA(self):
        print("A")

    def doB(self):
        print("B")

x=MyDo()
```

<p>vs <strong>Composition</strong>:</p>

<pre class="lang-python prettyprint-override"><code>class Do:
    def __init__(self, a, b):
        self.a=a
        self.b=b

    def do(self):
        self.a.do()
        self.b.do()

x=Do(DoA(), DoB())
</code>```

(Note for composition I'm missing code so it's not actually shorter)

Can you name particular advantages of one or the other?

I'm think of:

composition is useful if you plan to reuse DoA() in another context

inheritance seems easier; no additional references/variables/initialization

method doA can access internal variable (be it a good or bad thing :) )

inheritance groups logic A and B together; even though you could equally introduce a grouped delegate object

inheritance provides a preset class for the users; with composition you'd have to encapsule the initialization in a factory so that the user does have to assemble the logic and the skeleton

...

Basically I'd like to examine the implications of inheritance vs composition. I heard often composition is preferred, but I'd like to understand that by example.

Of course I can always start with one and refactor later to the other.


问:
Years experience over unfinished degree?
I'm currently in my placement year and working for a great software development company. It was always my intention of getting to this stage through university, getting enough academic experience as well as the year’s placement and then try to get a full time programming job without the need to finish my degree. I decided this from an early stage as I have never really liked the whole university environment. I was so unhappy at university and I’m so happy now I’m on my placement year, I really don’t know if I can go back.

My question is, do you think companies will take me on if I apply for other jobs after my placement year and not penalize me for not finishing my degree?

I guess at the end of the day I don't want to look back on my life and think "god, why didn't I just spend one more year being unhappy to have a job I love" but I know that even if I get a degree I could still end up without a programming job and this worries me more than anything.

答: I dropped out of college because, I was offered a full time position and the pay was great at the time. However, after three years I was laid off. Since then (6 months), I have not been able to find a job, and now more than ever I need the money. Don't do it, no matter how smart or experienced you are most companies require a degree and there is no back door or short cut to a dream job. Otherwise, more people would drop out their Jr & Sr year. </p>


答:
They are not insightful in new ways about human cognition at all.

Algorithms can be considered as constructive proofs of the existence of a solution to the considered problem.  And similarly, a constructive proof of existence can be turned in an algorithm for computing the result.

And proofs, even alternative proofs when one already exists, provide insight about the problem at hand.