答:
Mono is not a 1:1 port of Microsoft's .net. There are technologies that Mono simply won't implement or has no plans to do so (e.g., Workflow Foundation or WPF) while on the other hand they have some technologies of their own that Microsoft .NET doesn't do, e.g., SIMD Extensions.

Short Answer: Mono and Microsoft .NET are based on the same underlying foundation - CIL and BCL - but are separate projects.


问:
Is context inheritance, as shown by Head First Design Patterns' Duck example, irrelevant to strategy pattern?
In Head First Design Patterns it teaches the strategy pattern by using a Duck example where different subclasses of Duck can be assigned a particular behavior at runtime.  From my understanding the purpose of the strategy pattern is to change a single object's behavior at runtime, yet they are using inheritance of Duck to change the behavior of various types of Duck.

Relevance?

Is context inheritance of Duck irrelevant to the strategy pattern or is varying Duck types and also varying their behaviors a good reason to employ the strategy pattern? Do situations where you need to vary both constitute a good reason to use strategy pattern?  Why would they include this as the strategy pattern example?

A Simpler Example

Could I further simplify this example by just having a Duck class (no derived classes)?  Then when implementing one duck object it can be assigned different behaviors based on certain circumstances that aren't dependent on its own object type. For example: FlyBehavior changes based on the weather or QuackBehavior changes based on the time of day or how hungry a duck is. I realize this would be solving a different problem than from the one in the book, but what I am looking for is a relevant strategy pattern example to fall back on.

Would my example above constitute the strategy pattern as well?

Edit:

I was successful in finding 2 simpler strategy pattern examples that adhere more strictly to being just strategy patterns without context inheritance: Hunter.java and solver.py.

答:
Yes, I think you are on the right track. The class using the strategy pattern does not have to be a subclass. The strategy pattern is an alternative to inheritance for code re-use. This comes back to the even broader comparison of inheritance vs composition.

From Design Patterns: Elements of Reusable OOP you would use strategy pattern to

Avoid an explosion of subclasses (due to combinations of behaviors)

If you need to swap out behavior at run-time

If you used inheritance to implement Quack and Fly behaviors you would result with all these subclasses to represent all the combinations of behaviors.

FlyableQuackableDuck

FlyableSqeakableDuck

FlyableMuteDuck

NoFlyQuackableDuck

NoFlySqueakableDuck

NoFlyMuteDuck

Having so many subclasses makes it harder to maintain which is why strategy pattern is favored in this case. You just need two properties which encapsulate Flyability and Quackability and you can mix and match these without creating new classes.

You also already mentioned the run-time benefit of if the weather changed the duck's Fly property could be replaced with a NoFly object due to the conditions.

This is consistent with the advice to favor composition over inheritance when possible.

ContentLicense: CC BY-SA 3.0


问:
What would be the fastest way of storing or calculating legal move sets for chess pieces?
For example if a move is attempted I could just loop through a list of legal moves and compare the x,y but I have to write logic to calculate those at least every time the piece is moved.

Or, I can store in an array [,] and then check if x and y are not 0 then it is a legal move and then I save the data like this
[0][1][0][0] etc etc for each row where 1 is a legal move, but I still have to populate it.

I wonder what the fastest way to store and read a legal move on a piece object for calculation.

I could use matrix math as well I suppose but I don't know.

Basically I want to persist the rules for a given piece so I can assign a piece object a little template of all it's possible moves considering it is starting from it's current location, which should be just one table of data. But is it faster to loop or write LINQ queries or store arrays and matrices?

```<code>public class Move
{
    public int x;
    public int y;
}

public class ChessPiece : Move
{
    private List<Move> possibleMoves { get; set; }

    public bool LegalMove(int x, int y){
      foreach(var p in possibleMoves)
      {
         if(p.x == x && p.y == y)
         {  return true;  }
      }
    }
}
</code>```

Anyone know?

答: If you're spending your time worrying about the fastest way, you'll never have time to develop a strong program.   Computer cycles are cheap.  Your cycles are a very limited resource.  Optimizing at this level is the very last thing you should do. Literally.</p>


问:
Are there any benefits to removing unused using statements in a VS project?
Are there any benefits to removing unused using statements in a VS project (such as can be done using Resharper), or will VS automatically take care of that when building/deploying?</p>

答:
Yes - I can think of two primary benefits:

Beyond its primary functional purpose (i.e. to reduce code verbosity), the 'Using' statement list at the top of a code file can tell future readers (especially those without Resharper) which namespaces are (or at least were) relevant to that code file. If you actively prune this list, it can act as a better signaling mechanism.

Removing unused namespaces will reduce the number of autocompletion candidates in your text editor as you type. If you rely on the autocompletion lists at all, this will help keep you "on the straight and narrow" and may even increase your typing speed, as you should be able to find your intended autocompletion candidate just a little bit faster.


问:
Share mulitple classes as one dll or a lib with mulitple projects
Currently I have some shared class files (.cpp and .h) which I include them in around 20 Projects. Currently I have to include them in all of the projects.

So if I get some business requirements and I change some of the shared (.cpp or .h) files I have to include them in all the 20 Projects which is kind of tedious.

Is there a way where I can create a shared dll or library and include it all of my projects? So if I have to change it, I just have to change it once and then just Add Reference to include that dll or library which contains all the shared (.cpp, .h) files.

I am using VS2012 for VC++.

答: This would be an appropriate use of a shared library. The difference will be that you will need to include a header file and link to the library versus including the headers and cpp files. However, the advantage is that you can build the library once and link to it once rather than having to build the the same code with every project. If you only add classes to the library that don't change much, which are used commonly throughout your code, it will also help to increase the modularity and stability of your programs.</p>


问:
Which are the significant algorithms for humankind in past decades?
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...

答:
All algorithms which used for solving Visibility Problem in 3D Computer Animation seems crucial to me.

Painter's algorithm

The painter's algorithm, also known as a priority fill, is one of the simplest solutions to the visibility problem in 3D computer graphics. When projecting a 3D scene onto a 2D plane, it is necessary at some point to decide which polygons  are visible, and which are hidden.

Z-buffering

In computer graphics, z-buffering is the management of image depth coordinates in three-dimensional (3-D) graphics, usually done in hardware, sometimes in software. It is one solution to the visibility problem, which is the problem of deciding which elements of a rendered scene are visible, and which are hidden. The painter's algorithm is another common solution which, though less efficient, can also handle non-opaque scene elements. Z-buffering is also known as depth buffering.

Hidden surface determination

In 3D computer graphics, hidden surface determination (also known as hidden surface removal (HSR), occlusion culling (OC) or visible surface determination (VSD) is the process used to determine which surfaces and parts of surfaces are not visible from a certain viewpoint. A hidden surface determination algorithm is a solution to the visibility problem, which was one of the first major problems in the field of 3D computer graphics. The process of hidden surface determination is sometimes called hiding, and such an algorithm is sometimes called a hider. The analogue for line rendering is hidden line removal. Hidden surface determination is necessary to render an image correctly, so that one cannot look through walls in virtual reality, for example.

ContentLicense: CC BY-SA 2.5


问:
Improve Bad testing
We have a large team of developers and testers. The ratio is one tester for every one developer.

We have full bug tracking and reporting systems in place.

We have test plans in place.

Every change to the product, the testing team is involved in the design of the feature and are included in the development process as much as possible.

We build in small iterative blocks, using scrum methodology and every scrum they are included in, including the grooming sessions etc.

But every release of the product, they miss even the most simple and obvious defects.

How can we improve this?

答:
But every release of the product, they miss even the most simple and
  obvious defects.

The root of any good process (no matter how it look's in detail - be it scrum or traditional) is always:

maximum constructive quality assurance: good productive tools, coding standards, solid requirements etc. -> preventing defects

good analytical quality assurance: such as manual/automated blackbox testing, code reviews --> finding defects

"maximum constructive" means: before you improve finding defects, improve that you create less defects.

Are you sure you have a good analytical QA mix? Such as unit tests, manual tests, but also code reviews etc?

Do your testers use different techniques such as Exploratory Testing and not only Plan-based testing? Is your tooling sufficent for testing? (I hope you don't use Excel-lists...)

Takes your testing different view angles?

Do your testers have good test data?

In the end: budget? Would it be possible to test everything as desired? If not, set priorities.

That are only some points. Probably no team or company is good at everything and your team is probably also not bad at everything.

Try to brainstorm over the issue and priorize things that might help. But always ensure that you have a balance between constructive and analytical measures.

And some not so nice truth: some people are not suited for complex projects - they are sloppy and will nevery change. Get rid of them.

Title: Improve Bad testing


答:
We experienced this a lot.

The main problem, which I have experienced a lot is that the feature gets tested, it seems OK, you push it to production and then you experience problems.

My approach to this (I am a one-man QA operations with 4 developers!) is a good mix of automated regression tests combined with unit testing the current feature.

I don't have the time or capacity to write (selenium in my case) scripts for all the various features being delivered, so what I do is tested them manually.  That's usually fairly straight-forward.  I focus on multiple browsers, version and devices at this point to see how things look.  I try to put in unusual values, click all links, that kinda stuff.

On a parallel track I develop automated tests using Selenium.  These serve as good Integration tests and are really helpful at getting at those 'unintended consequences' that happen when one thing is changed and it affect others.  These tests also represent true user workflow.  I have each suite start from scratch and build up the entire system.  Then the data gets deleteed (also through the ui).  I have had to learn about selenium variables, xpath and css and javascript call-out to achieve some of the more difficult things but it has had great reward.  The suites focus on the core functionality and workflow of the product, not the latest features.

Also 'when' QA gets involved is important.  I have seen two approaches to this:

When the feature has been coded and delivered and is deemed 'ready for QA'

During the design session

It is easiest to do 1) but this leads to QA being too late in the process and - critically - not being involved in the design or layout.  This in turn leads to low motivation and low job satisfaction which are the two biggest killers to getting high-quality work.  Under approach 2) when QA is involved up-front during design, they are then more likely to be motivated to do good QA when the time comes.

Also - make sure (and humor can help here) that QA knows that it's really good when they find bug(s).  It is their job and it saves the company from putting it in front of the client.
"Many QA testers quickly feel they become Product Owners themselves.  Find a ay to work with this, not against it."

Title: Improve Bad testing

Body:
We have a large team of developers and testers. The ratio is one tester for every one developer.

We have full bug tracking and reporting systems in place.

We have test plans in place.

Every change to the product, the testing team is involved in the design of the feature and are included in the development process as much as possible.

We build in small iterative blocks, using scrum methodology and every scrum they are included in, including the grooming sessions etc.

But every release of the product, they miss even the most simple and obvious defects.

How can we improve this?


问:
Does Agile (scrum) require one server environment?
Is it necessary/recommend/best practice/any other positive to use only one server environment to perform all development, unit testing and QA?

If so, is it then wise/part of Agile to then have only one staging environment before Live?

Considering that this could mean internationally distributed teams of developers and testers in different time zones is this wise?

This is something being implemented by our QA manager. The opinion put forward is that doing all the dev and testing on a single server is "Agile." The staging environment would be a second environment, and then live.

答:
It is well established in a waterfall environment that the early detection of bugs reduces cost of fixing them. As analogy, you could think of all waterfall stages happening concurrently.

Therefore, a way of supporting that and reducing waste, you could argue that using one development server could cut costs. As soon as the developer has finished, the Testers can begin doing their work. It eliminates the waste of having to deploy the software to a new environment and the waste of waiting time.

Of course, testing deployment in itself is valuable. Having features in a state of development may cause false positives - unfinished features may 'work' and then later regress or testers tell you that it doesn't work when it isn't finished. You have to make this judgement call for our own team. We don't have enough context for a definitive answer.

And in the end, your QA manager doesn't actually have to do the coding himself. In this context he has a 'chicken' role. If your team of developers feel that they can work better or more productively by ignoring him, then they should.


答:
You're asking the wrong questions. For one, the whole team is responsible for software quality, so it's not just that the testers are missing the defects. The developers are, too.

The more important question is, why are your teams adding the "simple and obvious" defects to begin with? Don't focus  your attention on catching more bugs, focus your attention on writing fewer bugs.

Title: Improve Bad testing


问:
Questions to ask to ensure someone understands programming? (and iOS)
So, I've been tutoring my friend for 2 years. Most people learn programming on their own in 3-6 months, (sans algorithms). It's confusing 'cause he'll run anywhere I tell him to, understands how to read C and C++ honestly better than the average college student, and he'll modify and repeat anything I do... but for the love of god he doesn't move on to new things and he still has test anxiety.

I've recently realized he's copied and toyed with existing, but not once gained an understanding of why. I was under the impression he was learning fast because he could write it, but when you say "Make a function that takes an NSString" and he says "How?" and I say "The same way you make ANY function that takes any parameter, NSString is just a type like int" and all I hear is "No, it's an NSString, it's a special thing." and we get into an arguing match 'cause I'm like "It's just a class like any other class, you've used them for months now" and blah...

I've subconsciously avoided comprehension questions because of this. Anyway, if you have him copy a program and say "Just initialize it" "Where?" "I don't care, didLoad or initWithCoder or Awake from nib, anywhere it gets initialized" and "No, it has to be exactly where you had it!" "No it doesn't!"

I'm sick of this, but he won't give up. So I'm done avoiding these yelling matches and becoming a sadist from now on. I would like some help in finding questions to ask him that force him to understand what he's doing.

I'd like some help and any resources I can find. CQuestions looked like a good site, but now I need some iPhone stuff.

For example:
*What do properties do? How are they changed? How do you change the name of the getter?

*Why are Booleans inefficent? What advantage does int have over a boolean and how does the bit-shift operator help?

*What does Copy do to a string?

*What's the difference between a view controller and a uiview?

*Write a program from memory that displays blah on screen, and flashes each view one by one.

From beginner up to intermediate, hobbyist with some algebra at most. I'm just looking for resources to work with. I left in backstory so you know to "twist" the questions so he doesn't know he's supposed to init a variable here or there, but has to figure it out, and learn why it goes "here" or that "anywhere is fine as long as it's". Sample programs, anything.

I'm relatively open about this because, being a programmer, I seriously doubt he's the only one who has this issue. I'd like to know how others have overcome similar. What made things "click"? for you?

Did you have a hard time finding answers on Google, and how did you learn a better way to find what you were looking for? (He's so exact, he'll search for how to write a checkers program with color X and Y inside a uiview, as his search string, instead of breaking it up into components, I need help with that too, and believe it is related).

This type of problem has to remind one of us of someone they know.

So, Exercises to force them to think? Ways we overcame this thing in the past?

I greatly appreciate any help.

答:
You have an XY Problem.  See here and here

"Y" in your case is a resource request question to test comprehension of programming.  For that, I'd suggest looking over interview.

The "X" in your case is that you have ceased being an effective tutor for your friend.  Or looking at it the other way, he has ceased being a good student for you.  Either way, the root of the problem is that he's not ready for the lessons you wish to present in the manner you wish to present them.

So it's time to stop the tutelage.  At least for now.  Let him go explore, build, and enjoy the craft.  If things change and he's ready for more or you have new means to convey the information, then you'll realize it and the lessons can start again.

Don't ruin a friendship over a matter like this.  Save that sort of destruction for something like "emacs vs vi" or a foray into the curly brace war.  Ok, those aren't worth ruining a friendship over either.

Solve your X problem by realizing it's time to stop and move on to another chapter.


问:
What are some ramifications of open source software turning into closed source software?
If a company takes a permissively licensed open source application and then develops a closed source application from that by reworking extensive parts of the application, adding new features and applying bug fixes...

Ignoring any license requirements...

How does the transition happen and what can be done to prevent it beyond choosing a difference license?

What are the (ethical or social) responsibilities for the company? (For example: Giving back to the open source project would be the ethical thing to do)

If the open source version and closed source version are both available, how does the competition affect either product?

Are there any examples of companies or products that have done this (either successfully or unsuccessfully) in the past? What was the community attitude toward those projects?

答:
It's important to note that this scenario can happen in both legal and illegal forms.

This can occur legally if the company owns or has access to the copyright associated with the code.  For example, smaller, independent development teams may wish to sell or license their copyright to a larger firm.  Likewise, if the bulk of the code's copyright can be acquired, the "unattainable" portion may simply be thrown out and rewritten.

On the other side of the coin, the code may simply be taken illegally.  New Corp, Inc. may not care what the legal ramifications are.  The project may be too old or abandoned or New Corp thinks they'll win in a lawsuit.  Or New Corp may be registered in an area where this sort of "acquisition" simply isn't defined as illegal.  Not all OSS licenses are enforceable, especially not the ones that were cobbled together by non-experts in the law.  Not all project owners may have the ability to enforce their copyright claims, and larger organizations such as the FSF may not have standing in that jurisdiction for that claim.  TL;DR - this area can get hazy and ugly really fast.

Transition & prevention

How does the transition happen and what can be done to prevent it beyond choosing a difference license?

The transition occurs when New Corp, Inc. acquires the code base and places that copy under their control.  New Corp's developers then begin working on their version of the code base making whatever changes the corporate overlords have decreed necessary.  The actual mechanics of this fork will vary based upon the repository.  And while it's a philosophically big deal, it's really pretty underwhelming in practice.  get all from OpenRepos and then checkin to the PrivateRepos.

What can be done to prevent it short of never distributing the source?  Nothing.  Sorry.

Let's use GPL (GNU public license) as an example.  GPL requires the source to be available to anyone receiving a legitimate copy of the project.  There are no provisions that allow the holder of the source to refuse delivery of the source to a legitimate holder of a copy of the GPL'd application.  It goes against the grain of Free software, and that's why the GPL copyleft is in place.

Potentially, you have after-the-fact legal courses of action to pursue.  But those are all after the source has escaped and been forked, not before.  And in some jurisdictions you won't have any legal recourse.  And all of this assumes you're even aware that the fork occurred.  You may never find out.

Ethics

What are the (ethical or social) responsibilities for the company? (For example: Giving back to the open source project would be the ethical thing to do)

Ethics are local to the culture.  So temper this section with that grain of salt.  A full discussion of cultural consideration of ethics is beyond the scope of this answer and off-topic for Programmers.

I have noticed that the programming community tends to react negatively to a hostile fork.  Heck, in some cases the same community still reacts negatively to a friendly and legal fork.  It's a pretty complex community.

From an FOSS perspective, there is an expectation that New Corp is going to "repay" the community for the contribution it forked.  The terms, conditions, and duration of that repayment are as varied as the number of OSS projects in existence.  Some in the community (think Richard Stallman) will never be content with an open project going closed.  Others will look for the benefit provided to the community at large and will judge based upon that.  And others simply won't care because they never knew of or cared about the origin project.

Source availability

If the open source version and closed source version are both available, how does the competition affect either product?

It really depends upon how comparable the two code bases are with respect to functionality, performance, and stability.

If the code bases remain similar and New Corp is friendly to the OSS community, they may contribute their updates back into the base project.  In this case, everyone benefits.  It's not a "competition" in this case, but more of a mutually beneficial collaboration.

If the code bases wildly diverge and New Corp is not friendly to the OSS community, then there still isn't a competition.  The more feature rich product survives and the less rich product tends to die off.  Note that this can go either way - the closed version could die off if the open source version continues to innovate or better meet the needs of the community.

The reality will be somewhere between those two ends of the spectrum.

Example

Red Hat has two main distributions - Enterprise Linux and Fedora.  EL is their "closed" licensed version and Fedora is their community edition.  Due to the GPL, much, if not all, of the EL edition is released in source form.  Another project not affiliated with Red Hat called CentOS picks up the changes to EL and distributes that project after some minor rebranding.

There were some grumblings when Red Hat forked into two separate editions, but by and large, it's been a pretty workable agreement.  The Fedora community wanted features rolled into the distribution faster than what Red Hat's enterprise customers were comfortable with.  Enhancements to the code bases flow in both directions.


答:
Assuming that everything is legal and above board, and that we are talking about a product that has a kosher open source license before the process starts:

How does the transition happen ...

Basically, the company makes a new release of the software with the non-open source license.

and what can be done to prevent it beyond choosing a difference license?

In general nothing.  The only case where it can be prevented (or delayed) is if there are multiple copyright owners, and some of them object to the re-licensing.  But if the company is serious, they could decide to solve that problem by rewriting the relevant parts of the code-base, etcetera.

Attempting to apply "moral pressure" before the fact probably are unlikely to work.  The company is likely to do this kind of thing without any prior notification.

Having said that, there are examples where attempts to "wind back" open source has backfired on the company doing it.  Consider the cases of OpenOffice, Hudson and MySQL, where the actions of Oracle have lead to a fork, a mass exodus of the developer community and (for OO and MySQL) distros increasingly dumping the original product in favour of the fork (LibreOffice and MariaDB).

What are the (ethical or social) responsibilities for the company?

To be frank (and somewhat cynical), it is not relevant what you and I think the ethical and social responsibilities of a company should be.

From a legal perspective perspective, the company directors' and executives' sole responsibilities are 1) to maximize value for the share-holders / owners, and 2) ensure that the law is obeyed.  You could argue that as individuals, these people have social and ethical responsibilities, but ... unfortunately ... many of them would disagree.

But either way, ethical and social responsibilities are only relevant in a practical sense if the company and its officers take them on board and take them seriously.

If the open source version and closed source version are both available, how does the competition affect either product?

I don't think there is an answer to this.  It depends on the circumstances.

Are there any examples of companies or products that have done this (either successfully or unsuccessfully) in the past? What was the community attitude toward those projects?

Yes there are examples.  Just Google for the phrase "goes closed source" and apply a bogosity filter.  Reading through the (non bogus) hits will give you a feel for community attitude, and if you research further into the products / companies you can make up your mind whether they were successful or not.  (I'm not going to do this for you because "successful" is a value judgement.)

Title: What are some ramifications of open source software turning into closed source software?

Body:
If a company takes a permissively licensed open source application and then develops a closed source application from that by reworking extensive parts of the application, adding new features and applying bug fixes...

Ignoring any license requirements...

How does the transition happen and what can be done to prevent it beyond choosing a difference license?

What are the (ethical or social) responsibilities for the company? (For example: Giving back to the open source project would be the ethical thing to do)

If the open source version and closed source version are both available, how does the competition affect either product?

Are there any examples of companies or products that have done this (either successfully or unsuccessfully) in the past? What was the community attitude toward those projects?


问:
Are C or C++ The Only Viable Languages for a GC

Background

I have just finished writing a compiler for a functional language compiling to the JVM as a learning project. However, since I'm just doing this to learn, I thought it might be interesting to write a native backend and a RTS for it.

As I've been planning out what this new backend will look like, the one point I'm stumbling on is the garbage collector. I've implemented the compiler in Haskell. But I have no desire to write the GC in Haskell since, while it may be possible, it'd suck.

Question

I've looked at several FOSS garbage collectors prior to posting and most of them were implemented in good old ANSI C. Is this still the most accepted choice for writing a GC nowadays?

I've seen that this site tends to frown upon questions with multiple answers so I hope this will make it more specific: If some startup was writing a professional grade gc today, are the only viable choice for them C or C++?

It's my first question here so please comment and let me know if this question is ill-suited for for programmers.

答:
If some startup was writing a professional grade gc today, are the only viable choice for them C or C++?

No.

C is simply the lingua franca of systems programming, and often the first tool developers reach for when developing a new language, VM, or OS. That many GCs are written in C is simply a result of that fact.


问:
Dependency Injection Confusion
I think I have a decent grasp of what Dependency Inversion principle (DIP) is, my confusion is more around dependency injection.

My understanding is the whole point of DI is to decouple parts of an application, to allow changes in one part without effecting another, assuming the interface does not change.

For examples sake, we have this

```<code>public class MyClass(IMyInterface interface)
{
   public MyClass
   {
      interface.DoSomething();
   }
}

public interface IMyInterface
{
    void DoSomething();
}
</code>```

How is this

```<code>var iocContainer = new UnityContainer();
iocContainer.Resolve<MyClass>();
</code>```

better practice than doing this

```<code>//if multiple implementations are possible, could use a factory here.

IMyInterface interface = new InterfaceImplementation();
var myClass  = new MyClass(interface);
</code>```

It may be I am missing a very important point, but I am failing to see what is gained. I am aware that using an IOC container I can easily handle an objects life cycle, which is a +1 but I don't think that is core to what IOC is about.

Edit

Here is an expanded example:

```<code>void Main()
{
    IRepository repository = new AddRepository();
    var maths = new PointlessMaths(repository,5);
    Console.WriteLine(maths.Result);
}

public interface IRepository
{
    int DoSomething(int id);
}

public class AddRepository : IRepository
{
    public int DoSomething(int id)
    {
        return id + 1;
    }
}

public class SubtractRepository : IRepository
{
    public int DoSomething(int id)
    {
        return id - 1;
    }
}

public class PointlessMaths
{
    public int Result {get;set;}
    public PointlessMaths(IRepository repository, int id)
    {
        Result = repository.DoSomething(id);
    }
}
</code>```

答:
In this example, I would not call using a DI container "better practice". However, code bases tend to grow and become more complicated. Imagine we have a dependency graph like this:

```<code>    A
   / \
  /   \
 B     C
  \   /
   \ /
    D
</code>```

The code to construct this graph without a DI container would look something like this:

```<code>ID d = new D();
IB b = new B(d);
IC c = new C(d);
A a = new A(b, c);
</code>```

Note that the same instance of D is used for for B and C. But what if we decide that they each need their own instance? Now we have to duplicate the code to create a new instance of D, and the result looks like this:

```<code>ID d1 = new D();
IB b = new B(d1);
ID d2 = new D();
IC c = new C(d2);
A a = new A(b, c);
</code>```

Nontrivial applications can easily have far more complicated dependency graphs than this, and the code's complexity will scale accordingly. Contrast the above with the equivalent code using a DI container:

```<code>var iocContainer = new UnityContainer();
iocContainer.Resolve<A>();
</code>```

Note that the complexity does not scale with the number of dependencies. Even when you consider the container's configuration, that only scales with the number of unique dependencies (e.g. you'll only need one entry for D even if it ends up creating a hundred instances). In addition, some dependencies (like concrete classes) can be automatically resolved without any configuration at all.

DI containers also provide the flexibility to specify, in configuration, whether or not you want D to be a singleton (for example), in addition to plenty of other resolution, construction, and lifecycle options. These may also be more readable using your container's configuration syntax than implementing them yourself.

The more complex your dependency graph becomes, the more benefit you'll get from a DI container.

Also, popular DI containers often integrate well with particular platforms (e.g. ASP.NET MVC, WCF, etc.).

Title: Dependency Injection Confusion

Body:
In this example, I would not call using a DI container "better practice". However, code bases tend to grow and become more complicated. Imagine we have a dependency graph like this:

    A
   / \
  /   \
 B     C
  \   /
   \ /
    D

The code to construct this graph without a DI container would look something like this:

ID d = new D();
IB b = new B(d);
IC c = new C(d);
A a = new A(b, c);

Note that the same instance of D is used for for B and C. But what if we decide that they each need their own instance? Now we have to duplicate the code to create a new instance of D, and the result looks like this:

ID d1 = new D();
IB b = new B(d1);
ID d2 = new D();
IC c = new C(d2);
A a = new A(b, c);

Nontrivial applications can easily have far more complicated dependency graphs than this, and the code's complexity will scale accordingly. Contrast the above with the equivalent code using a DI container:

var iocContainer = new UnityContainer();
iocContainer.Resolve<A>();

Note that the complexity does not scale with the number of dependencies. Even when you consider the container's configuration, that only scales with the number of unique dependencies (e.g. you'll only need one entry for D even if it ends up creating a hundred instances). In addition, some dependencies (like concrete classes) can be automatically resolved without any configuration at all.

DI containers also provide the flexibility to specify, in configuration, whether or not you want D to be a singleton (for example), in addition to plenty of other resolution, construction, and lifecycle options. These may also be more readable using your container's configuration syntax than implementing them yourself.

The more complex your dependency graph becomes, the more benefit you'll get from a DI container.

Also, popular DI containers often integrate well with particular platforms (e.g. ASP.NET MVC, WCF, etc.).


问:
Code Reuse and Abstraction in FP vs OOP
I've been told that code reuse and abstraction in OOP is far more difficult to do than it is in FP, and that all the claims that have been made about Object Orientedness (for lack of a better term) being great at reusing code have been flat out lies

So I was wondering if anyone here could tell me why that is, and perhaps show me some code to back up these claims, I'm not saying I don't believe you Functional programmers, it's just that I've been "indoctrinated" to think Object Orientedly, and thus can't (yet) think Functionally enough to see it myself

To quote Jimmy Hoffa (from an answer to one of my previous questions):

The cake is a lie, code reuse in OO is far more difficult than in FP. For all that OO has claimed code reuse over the years, I have seen it follow through a minimum of times. (feel free to just say I must be doing it wrong, I'm comfortable with how well I write OO code having had to design and maintain OO systems for years, I know the quality of my own results)

That quote is the basis of my question, I want to see if there's anything to the claim or not

答:
Many arguments against object oriented reuse is that for the majority of objects, you can't use just them. You need to use them, and all of the things they depend on, which tends to be some framework to support their needs, a slew of interfaces you need to supply/implement, and possibly a pile of configuration to tie it all together.

Frankly, functional programming of any complexity suffers from the same sort of dependency chaining but the impact is lessened since almost all of the dependencies tend to boil down to list manipulation pretty quickly.

Title: Code Reuse and Abstraction in FP vs OOP


问:
Better solution then simple factory method when concrete implementations have different attributes
```<code>abstract class Animal {
  function eat() {..}
  function sleep() {..}
  function isSmart()
}

class Dog extends Animal {
  public $blnCanBark;
  function isSmart() {
    return $this->blnCanBark;
  }
}

class Cat extends Animal {
  public $blnCanJumpHigh;
  function isSmart() {
    return $this->blnCanJumpHigh;
  }
}

.. and so on up to 10-20 animals.
</code>```

Now I created a factory using simple factory method and try to create instances like this:

```<code>class AnimalFactory {
  public static function create($strName) {
       switch($strName) {
          case 'Dog':
            return new Dog();
          case 'Cat':
            return new Cat();
          default:
            break;
       }
  }
}
</code>```

The problem is I can't set the specific attributes like blnCanBark, blnCanJumpHigh in an efficient way.

I can send all of them as extra params to create but this will not scale to more then a few classes. Also I can't break the inheritance because a lot of the basic functionality is the same.

Is there a better pattern to solve this?

答:
Factory combined with Strategy comes to mind. Each animal could support the notion of a set of behaviours that can be added / passed as an array of behaviour interface references or array of instances of descendants of an abstract behaviour class.

Don't think this is the way to go though, as it means you put the decision of which behaviours to pass in outside of the factory and that seems to defeat the purpose of having a factory in the first place.

Builder seems specifically suited to your problem. I have always viewed Builder as an extension (not in the inheritance but the "taking it one step further" sense). Instead of focusing on instantiation, it specifically caters to constructing instances of classes that need more than just a call to a constructor.

Update:

Below is an example of the Builder pattern. It uses Delphi syntax as that is the language I'm most familiar with, but I have refrained from using Delphi specific constructs (meta classes for example). Error checking and freeing your instances has also been kept out of the example.

Please note that instead of passing the director an instance of a builder, you could also pass a string and let the director work out which builder to instantiate and use. In that case I would opt for a registry of builders in the director and a register method on the director so you can declare and builders without changing the director.

```<code>type
  TBehaviour = class(TObject)
  end;
  TSpeakBehaviour = class(TBehaviour);
  TJumpBehaviour = class(TBehaviour);

  TAnimal = class(TObject)
  public
    procedure AddBehaviour(const aBehaviour: TBehaviour);
  end;

  TCat = class(TAnimal);
  TDog = class(TAnimal);

  TAnimalBuilder = class(TObject)
  public
    procedure BuildBody; virtual; abstract;
    procedure AddBehaviours; virtual; abstract;
    function GetAnimal: TAnimal; virtual; abstract;
  end;

  TCatBuilder = class(TBuilder)
  private
    FCat: TCat;
  public
    procedure BuildBody; override;
    procedure AddBehaviours; override;
    function GetAnimal: TAnimal; override;
  end;

  TDogBuilder = class(TBuilder)
  private
    FDog: TDog;
  public
    procedure BuildBody; override;
    procedure AddBehaviours; override;
    function GetAnimal: TAnimal; override;
  end;

  TAnimalDirector = class(TObject)
  private
    FBuilder: TAnimalBuilder;
  public
    constructor Create(const aBuilder: TAnimalBuilder);
    function BuildAnimal: TAnimal;
  end;

procedure BuildMeAnAnimal;
var
  Builder: TAnimalBuilder;
  Director: TAnimalDirector;
  Animal: TAnimal;
begin
  Builder := TCatBuilder.Create;
  Director := TAnimalDirector.Create(Builder);
  Animal := Director.BuildAndimal;
end;

//--- Animal Director --------------

constructor TAnimalDirector.Create(const aBuilder: TAnimalBuilder);
begin
  FBuilder := aBuilder;
end;

function TAnimalDirector.BuildAnimal: TAnimal;
begin
  FBuilder.BuildBody;
  FBuilder.AddBehaviours;
  Result := FBuilder.GetAnimal;
end;

//--- Cat Builder --------------

procedure TCatBuilder.BuildBody;
begin
  FCat := TCat.Create;
end;

procedure TCatBuilder.AddBehaviours;
begin
  FCat.AddBehaviour(TSpeakBehaviour.Create('miauw'));
  FCat.AddBehaviour(TJumpBehaviour.Create(jaHigh));
end;

function TCatBuilder.GetAnimal: TAnimal;
begin
  Result := FCat;
end;

//--- Dog Builder --------------

procedure TDogBuilder.BuildBody;
begin
  FDog := TDog.Create;
end;

procedure TDogBuilder.AddBehaviours;
begin
  FDog.AddBehaviour(TSpeakBehaviour.Create('woof'));
  FDog.AddBehaviour(TJumpBehaviour.Create(jaMediumHigh));
end;

function TDogBuilder.GetAnimal: TAnimal;
begin
  Result := FDog;
end;
</code>```

Body:
Factory combined with Strategy comes to mind. Each animal could support the notion of a set of behaviours that can be added / passed as an array of behaviour interface references or array of instances of descendants of an abstract behaviour class.

Don't think this is the way to go though, as it means you put the decision of which behaviours to pass in outside of the factory and that seems to defeat the purpose of having a factory in the first place.

Builder seems specifically suited to your problem. I have always viewed Builder as an extension (not in the inheritance but the "taking it one step further" sense). Instead of focusing on instantiation, it specifically caters to constructing instances of classes that need more than just a call to a constructor.

Update:

Below is an example of the Builder pattern. It uses Delphi syntax as that is the language I'm most familiar with, but I have refrained from using Delphi specific constructs (meta classes for example). Error checking and freeing your instances has also been kept out of the example.

Please note that instead of passing the director an instance of a builder, you could also pass a string and let the director work out which builder to instantiate and use. In that case I would opt for a registry of builders in the director and a register method on the director so you can declare and builders without changing the director.

type
  TBehaviour = class(TObject)
  end;
  TSpeakBehaviour = class(TBehaviour);
  TJumpBehaviour = class(TBehaviour);

  TAnimal = class(TObject)
  public
    procedure AddBehaviour(const aBehaviour: TBehaviour);
  end;

  TCat = class(TAnimal);
  TDog = class(TAnimal);

  TAnimalBuilder = class(TObject)
  public
    procedure BuildBody; virtual; abstract;
    procedure AddBehaviours; virtual; abstract;
    function GetAnimal: TAnimal; virtual; abstract;
  end;

  TCatBuilder = class(TBuilder)
  private
    FCat: TCat;
  public
    procedure BuildBody; override;
    procedure AddBehaviours; override;
    function GetAnimal: TAnimal; override;
  end;

  TDogBuilder = class(TBuilder)
  private
    FDog: TDog;
  public
    procedure BuildBody; override;
    procedure AddBehaviours; override;
    function GetAnimal: TAnimal; override;
  end;

  TAnimalDirector = class(TObject)
  private
    FBuilder: TAnimalBuilder;
  public
    constructor Create(const aBuilder: TAnimalBuilder);
    function BuildAnimal: TAnimal;
  end;

procedure BuildMeAnAnimal;
var
  Builder: TAnimalBuilder;
  Director: TAnimalDirector;
  Animal: TAnimal;
begin
  Builder := TCatBuilder.Create;
  Director := TAnimalDirector.Create(Builder);
  Animal := Director.BuildAndimal;
end;

//--- Animal Director --------------

constructor TAnimalDirector.Create(const aBuilder: TAnimalBuilder);
begin
  FBuilder := aBuilder;
end;

function TAnimalDirector.BuildAnimal: TAnimal;
begin
  FBuilder.BuildBody;
  FBuilder.AddBehaviours;
  Result := FBuilder.GetAnimal;
end;

//--- Cat Builder --------------

procedure TCatBuilder.BuildBody;
begin
  FCat := TCat.Create;
end;

procedure TCatBuilder.AddBehaviours;
begin
  FCat.AddBehaviour(TSpeakBehaviour.Create('miauw'));
  FCat.AddBehaviour(TJumpBehaviour.Create(jaHigh));
end;

function TCatBuilder.GetAnimal: TAnimal;
begin
  Result := FCat;
end;

//--- Dog Builder --------------

procedure TDogBuilder.BuildBody;
begin
  FDog := TDog.Create;
end;

procedure TDogBuilder.AddBehaviours;
begin
  FDog.AddBehaviour(TSpeakBehaviour.Create('woof'));
  FDog.AddBehaviour(TJumpBehaviour.Create(jaMediumHigh));
end;

function TDogBuilder.GetAnimal: TAnimal;
begin
  Result := FDog;
end;


答:
...all the claims that have been made about Object Orientedness (for
  lack of a better term) being great at reusing code have been flat out
  lies

Perhaps the best reason why people think OOP produces code that is hard to re-use is they aren't even using OO methodologies! Just because you use an OO language does mean you are applying proper OO techniques.

I think Telastyn makes a good point about dependencies so I would like to propose a solution to that argument.

Code re-use is in fact a difficult thing to achieve in OOP. It requires careful attention to the overall architecture and layering of the application. If you lack experience then you may put little or no time into thinking about these things and you just start coding away or you may do this because it's just the easiest way. Then you end up with tightly coupled classes that are not module and cannot be ripped out and re-used.

Aiming for loosely-coupled, small module classes is one of the best ways to achieve code re-use. Dependency Injection is a great tool for doing this (I am referring to the pattern, not any DI/IOC frameworks).

Here is an example to demonstrate this

Hard-Coded

```<code>class WebScraper
{
    Database Db = new Database();

    public string Scrape(string url)
    {
        string content = WebClient.DownloadString(url);
        Db.Save(content);

        return content;
    }
}
</code>```

Dependency Injection

```<code>class WebScraperPro
{
    IStorage Storage;

    public WebScraperPro(IStorage storage)
    {
        Storage = storage;
    }

    public string Scrape(string url)
    {
        string content = WebClient.DownloadString(url);
        storage.Save(content);

        return content;
    }
}
</code>```

After writing the first class I have hard-coded my database code directly into the class. This makes it hard to re-use because what if I don't have a network connection to reach the database server, what if I don't want to store it in a database? If I wanted to just scrape the website I would have to write a new class even though all the functionality would be the same except for the persistence.

On the other hand when we use Dependency Injection we decouple the database from the business logic. I can pass in a TextStorage object that just writes it to a text file if I don't have network access, or I can pass in a NoStorage object if I don't want to store it anywhere. It allows me to re-use it more easily. Also notice we have now separated out Logic layer from our Data layer. This is the same reason why we do not want to bake UI code into the Logic layer.

This is just a contrived example off the top of my head, you could move the persistence to a higher level, but it should help grasp the concept of removing hard-coded dependencies.

When people use static classes everywhere they do not even realizing that they are binding their code to these dependencies. When you allocate concrete classes inside other classes you are doing the same thing. Programming to an interface and removing hard-coded dependencies is a big step in writing code that is re-usable. I also find that writing to an interface makes me think harder about the responsibility of the class and I end up writing smaller classes that follow the single responsibility principle. This makes everything more modular and more flexible.

I cannot comment on the other end of the spectrum about whether FP is better for re-use or not because I do not have experience with FP, but I can say that it is possible to write highly re-usable code in OOP if done properly.

Title: Code Reuse and Abstraction in FP vs OOP

Body:
I've been told that code reuse and abstraction in OOP is far more difficult to do than it is in FP, and that all the claims that have been made about Object Orientedness (for lack of a better term) being great at reusing code have been flat out lies

So I was wondering if anyone here could tell me why that is, and perhaps show me some code to back up these claims, I'm not saying I don't believe you Functional programmers, it's just that I've been "indoctrinated" to think Object Orientedly, and thus can't (yet) think Functionally enough to see it myself

To quote Jimmy Hoffa (from an answer to one of my previous questions):

The cake is a lie, code reuse in OO is far more difficult than in FP. For all that OO has claimed code reuse over the years, I have seen it follow through a minimum of times. (feel free to just say I must be doing it wrong, I'm comfortable with how well I write OO code having had to design and maintain OO systems for years, I know the quality of my own results)

That quote is the basis of my question, I want to see if there's anything to the claim or not

Body:
...all the claims that have been made about Object Orientedness (for
  lack of a better term) being great at reusing code have been flat out
  lies

Perhaps the best reason why people think OOP produces code that is hard to re-use is they aren't even using OO methodologies! Just because you use an OO language does mean you are applying proper OO techniques.

I think Telastyn makes a good point about dependencies so I would like to propose a solution to that argument.

Code re-use is in fact a difficult thing to achieve in OOP. It requires careful attention to the overall architecture and layering of the application. If you lack experience then you may put little or no time into thinking about these things and you just start coding away or you may do this because it's just the easiest way. Then you end up with tightly coupled classes that are not module and cannot be ripped out and re-used.

Aiming for loosely-coupled, small module classes is one of the best ways to achieve code re-use. Dependency Injection is a great tool for doing this (I am referring to the pattern, not any DI/IOC frameworks).

Here is an example to demonstrate this

Hard-Coded

class WebScraper
{
    Database Db = new Database();

    public string Scrape(string url)
    {
        string content = WebClient.DownloadString(url);
        Db.Save(content);

        return content;
    }
}

Dependency Injection

class WebScraperPro
{
    IStorage Storage;

    public WebScraperPro(IStorage storage)
    {
        Storage = storage;
    }

    public string Scrape(string url)
    {
        string content = WebClient.DownloadString(url);
        storage.Save(content);

        return content;
    }
}

After writing the first class I have hard-coded my database code directly into the class. This makes it hard to re-use because what if I don't have a network connection to reach the database server, what if I don't want to store it in a database? If I wanted to just scrape the website I would have to write a new class even though all the functionality would be the same except for the persistence.

On the other hand when we use Dependency Injection we decouple the database from the business logic. I can pass in a TextStorage object that just writes it to a text file if I don't have network access, or I can pass in a NoStorage object if I don't want to store it anywhere. It allows me to re-use it more easily. Also notice we have now separated out Logic layer from our Data layer. This is the same reason why we do not want to bake UI code into the Logic layer.

This is just a contrived example off the top of my head, you could move the persistence to a higher level, but it should help grasp the concept of removing hard-coded dependencies.

When people use static classes everywhere they do not even realizing that they are binding their code to these dependencies. When you allocate concrete classes inside other classes you are doing the same thing. Programming to an interface and removing hard-coded dependencies is a big step in writing code that is re-usable. I also find that writing to an interface makes me think harder about the responsibility of the class and I end up writing smaller classes that follow the single responsibility principle. This makes everything more modular and more flexible.

I cannot comment on the other end of the spectrum about whether FP is better for re-use or not because I do not have experience with FP, but I can say that it is possible to write highly re-usable code in OOP if done properly.


问:
How to get from 1 byte to 2 bytes
We have 1 byte, which is 8 bits, which is 2^8. Now 2 bytes should be 2 * 1 byte, which is 2 * 2^8 = 2^9, but actually 2 bytes is 2^16. What am I missing here? It seems like 2 bytes isn't 2 * 1 byte, it's more like 1 byte * 1 byte, but this should give you byte^2, which doesn't make sense.

Can please someone explain to me what I am getting wrong here?

答:
There are two aspects: the size and the number of representable states.  Increasing the size by one bit multiply the number of representable states by 2 (you get all the previous state with the additional bit set to 0, and again all the previous states with the additional bit set to 1).  By consequence, doubling the size squares the number of representable states (you have N possible states for the first element which have to be combined with N states for the second, thus in total N²).  If you think in decimal, adding one decimal digit multiply the number of values by 10 (and doubling the number of decimal digits still squares the number of values).

With 8 bits bytes:

1 byte is 8 bits and can represent values between 0 up to 2^8 (not included).

2 bytes is 16 bits and can represent values between 0 up to 2^16 (not included).

If you had a machine with 2 decimal digit bytes:

1 byte would be 2 decimal digits and you could represent values between 0 up to 100 (not included).

2 bytes would be 4 decimal digits and you could represent values between 0 up to 10000 (not included).

Title: How to get from 1 byte to 2 bytes


问:
Creating java package on ubuntu?
I am new to java. Here I am trying to create java package. And try to compile it from another directory . But there is an error like bash: /home/gaurav/Desktop/package2/B.java: Permission denied

Here is My first code and directory is /home/Desktop/package/A.java

```<code>package package1;
public class A
{
interface A1
{ void show();
  void display();
}
}

class B extends A
{
 public void show()
{
System.out.println("This is show method()");
}
public void display()
{
System.out.println("this is Display metthod()");
}
}
</code>```

For compilation I did this command it's works fine.
Working Directory is /home/gaurav

javac /home/gaurav/Desktop/package/A.java

When I try to compile B.java which is in my Other drive

/media/gaurav/iPlay/package/B.java

```<code>package package2;
class B
{
public static void main(String args[])
{
    System.out.println("Reached in Main method of B");
    package1.A Object = new A();
}
}
</code>```

I tired this vommand (grom previous working directory)

```<code>javac -cp /home/gaurav/Desktop/;/media/gaurav/iPlay/package/B.java
</code>```

Error Comes

```<code>javac -cp /home/gaurav/Desktop/;/media/gaurav/iPlay/package/B.java
javac: no source files
Usage: javac <options> <source files>
use -help for a list of possible options
bash: /media/gaurav/iPlay/package/B.java: Permission denied
</code>```

What i am doing wrong? Please it my assignment I am not able to move further without this. I changed permissions.

答:
Here you are making some basic mistake
First is in class B

```<code>package package2;
class B
{
public static void main(String args[])
{
    System.out.println("Reached in Main method of B");
    package1.A Object = new package1.A(); // Here package1.A
}
}
</code>```

Second change package folder name according to there package name
e.g. :

/media/gaurav/iPlay/package2/B.java

/home/gaurav/Desktop/package/A.java

Then compile A.java (Assuming you are in root dir)

javac /home/gaurav/Desktop/package1/A.java

Then B.java

```<code>javac -cp /home/gaurav/Desktop/package/ /media/gaurav/iPlay/package2/B.java
</code>```

To execute this

java -cp /home/gaurav/Desktop/:/media/gaurav/iPlay/ package2.B

i think this should work.

Title: Creating java package on ubuntu?

Body:
Here you are making some basic mistake
First is in class B

package package2;
class B
{
public static void main(String args[])
{
    System.out.println("Reached in Main method of B");
    package1.A Object = new package1.A(); // Here package1.A
}
}

Second change package folder name according to there package name
e.g. :

/media/gaurav/iPlay/package2/B.java

/home/gaurav/Desktop/package/A.java

Then compile A.java (Assuming you are in root dir)

javac /home/gaurav/Desktop/package1/A.java

Then B.java

javac -cp /home/gaurav/Desktop/package/ /media/gaurav/iPlay/package2/B.java

To execute this

java -cp /home/gaurav/Desktop/:/media/gaurav/iPlay/ package2.B

i think this should work.


答: Byte is a term that refers to storage capacity. The contents of a byte-sized storage location is what you do math on. Doubling the value stored in a byte-sized bucket may or may not require two bytes of capacity to store the result. Doubling 2^8 results in 2^9 which requires the combined capacity of two bytes to store. Doubling 2^6 results in 2^7 which requires only one byte to store.

Title: How to get from 1 byte to 2 bytes

Body:
We have 1 byte, which is 8 bits, which is 2^8. Now 2 bytes should be 2 * 1 byte, which is 2 * 2^8 = 2^9, but actually 2 bytes is 2^16. What am I missing here? It seems like 2 bytes isn't 2 * 1 byte, it's more like 1 byte * 1 byte, but this should give you byte^2, which doesn't make sense.

Can please someone explain to me what I am getting wrong here?


答:
You have one byte, which is 8 bits

So far so good

which is 2^8

Your use of "which is" here seems to be the root of your confusion.  A more precise statement is:

8 bits can represent 2^8 distinct values.

Or generally:

N bits can represent 2^N distinct values.

If this is unclear, it may help you to think about decimal digits (0-9).  One decimal digit can represent 10 distinct values (0-9), two decimal digits can represent 10^2=100 distinct values (0-99), N decimal digits can represent 10^N distinct values.

A bit is literally a binary digit.  One bit can represent two distinct values (0-1), two bits can represent four distinct values, and N bits can represent 2^N distinct values.

So eight bits can represent 2^8 distinct values, and sixteen bits can represent 2^16 distinct values.

Title: How to get from 1 byte to 2 bytes


问:
The difference between waterfall model and object oriented model?
Please explain the difference between the waterfall model and the object oriented model.

Since the books and web sites that I've seen didn't provide much information about it, I need someone to explain it to me.

答:
Waterfall model is a software development process consisting of a sequence of phases (requirements, design, construction, testing, deployment, maintenance), followed from first to last one, without going back and without using iterations (unlike in Agile models).

Waterfall model helps modeling project management.

Object-oriented model is a representation of a piece of software as a set of objects interacting between each other, with a goal to reduce the complexity of the system and enable developers to work on a specific object, while treating other objects as black boxes, with the requirement to know only their interfaces, and not their actual implementation.

Object-oriented model helps modeling the architecture and the design of an application.

As you can see, Waterfall model and object-oriented model cannot be compared. I hope the previous paragraphs make it clear what those two models are about. If not, Wikipedia has a good article about Waterfall model (as well as the close V-model), as well as a detailed article about OOP.


答:
If 1 byte were indeed 2^8, then 2 bytes is not 2*(2^8), but 2^(2*8).

Where you went wrong is in assuming that the unit "byte" is exactly equivalent to the formula 2^8. 2^8 is only the number of distinct states that you can represent with 8 bits.

In fact, "byte" as a unit is equivalent to 8 bit (and not 2^8). Therefore, 2 bytes is equivalent to 2*8 bit, and you can represent 2^(2*8) distinct states with these.

(Off-topic: To be somewhat more precise, a byte does not necessarily have to be 8 bits wide; that is only the most wide-spread size for bytes today. If you want a unit that always, unconditionally means exactly 8 bits, that would be the "octet".)

Title: How to get from 1 byte to 2 bytes


答:
These are completely different beasts.

The waterfall model is one of the ways to organize software development process dividing it into sequential stages known as Requirements, Design, Implementation, Verification, Maintenance. For example, your boss told you you have to develop an online shop. According to the waterfall model you first have to analyze the task inside out, gather all the possible information, may be talk to the customers, etc. in order to gain full information about the requirements of the project. Then you sit down and write a detailed technical specification of the project where you try to account for every possible detail and every possible requirement of the customer.

Then follows the planning stage where you design you software. It is this stage where you can choose an objected oriented design, functional programming, aspect-oriented design or some other model for your software and make a bunch of other important decisions about how you will structure it. If you choose an objected-oriented paradigm, you then decompose  everything into basic entities (Customer, Warehouse, Transaction, etc.) modelled by objects, then you design their interfaces and data structures using UML.

And only after all this lengthy preparation to begin to actually write code (the implementation stage). At this stage you try to follow the specification prepared at the design stage as closely as possible. Only after the software process is fully written comes the verification stage (where your testers test your software to ensure that it fully conforms to the specs and then the same is done by your customer). After your customer hopefully accepts your software begins the maintenance stage where update the software and correct the bugs.

The most cited problem with this is approach is that the actual writing of code happens very late. You have to actually be done with a tonne of bureaucratic stuff before you can write even a single line of code. On the hand, imagine that your customer decides to make some significant changes while you are writing the soft. With the waterfall model that actually means that you have to stop writing the code and basically start over the whole process from the very beginning, i.e. collect the requirements, then update the specs and only then begin to changing the soft. It is because of its rigidity the waterfall model which once was the predominant model in the software development world now has been overshadowed in most fields by more flexible models.

The object oriented programming is a programming paradigm. It is a way you design your software, as I already mentioned. It is very well suited for modelling real-world situations because here everything is regarded as objects. Continuing the online shop example, you could use Customer, Transaction, Currency, Warehouse, Product, ProductCategory, Shopping Cart and a whole bunch of other objects. In your code they then would be coded as classes. Every object here has properties. For example, Shopping Cart can have number of items in the cart as its property. Also objects have methods which are ways to interact with other objects.  For example, the Shopping Cart can have add (to allow Customer to add stuff to the shopping cart), remove, empty and other methods.

Title: The difference between waterfall model and object oriented model?

Body:
Please explain the difference between the waterfall model and the object oriented model.

Since the books and web sites that I've seen didn't provide much information about it, I need someone to explain it to me.


问:
Representation of data in application versus database
I'm going to make an application that will be given data to put in a database. The data will for the most part be the same, but the way it is formatted will vary a lot (could be in anything from text files to .xls to .doc).

I'm not a very experienced developer, but I can see some potential issues and I want to minimize them.

First off I have decided to use the DAO pattern, so that I can easily support new file formats or file suddenly formatted in different ways.

What I really wonder about though, is how I should manage the data itself within my application. I'm thinking that the database DAO should have models representing each table of the database with the same relations between them, to make the uploading process easy. But should the filesystem DAO's have to use the same models? I can imaging that when the database changes, the change will suddenly propagate throughout the entire system, all DAOs and models alike. And that is obviously a bad thing.

I'm a little bit tired and out of time. Will update with what ever questions you have.

Thanks!

答:
I believe that it may actually be better to abstract the organization of your database away from the organization of the code. If you mimic your database design, this will create problems when you will have to make changes to the data storage, for example if you later need some additional information like metadata, etc. So I would go for separating your objects from the databse plus using JPA or Hibernate to persist them into the database.

Also, why use a huge single object? I think it might be better to use some some basic class where you can concentrate your general-purpose code and then represent each file format by a different subclass of the basic class to allow for better code organization, flexibility and maintainability.


问:
Trying to understand 3 layer programming
I am confused to understand the structure of a 3 layer programm. Where is good place for exceptions, entity and etc.? If I use MVC, in my UI model, how to transfer entity class to model class and etc.?

I have created a project that called Ramznegar. It is web project. In this a user can register and get a account. Then login and can create category, like gmail, yahoo, etc... In each category user can add any item and its password. This programm actually is password keeper.

For developing this program I created four project with following structure:

RamznegarDAL: contains all DAO file

RamznegarBLL: contains logic of the program. like password decrypt and encrypt class

RamznegarUI : contains all JSP and Servlet class.

entity : contains 2 type of classes. entity (like Category, Item and User class) and exceptions (include all exception class that use in program like DataSourceAccessException)

RamznegarDAL use entity as library.

RamznegarBLL use RamznegarDAL and entity as library
RamznegarUI use RamznegarBLL and entity as library.

Now, please say me this structure is correct or if I have a problem with 3 layer concept.

答:
There is a good example about the MVC pattern applied to JSP and Servlet world in the HeadFirst Servlets and JSP book.

Basically, the Controller part is represented by a Servlet. The JSP is the view and the Model functions are performed by some Plain Old Java Object, i.e. a regular Java Class. In the book they show how you can write a simple BeerExpert app as an illustration of the MVC pattern naturally supported by the Web tier of the J2EE.

The HTML code of the starting page.

```<code><html><body>
<h1 align=”center”>Beer Selection Page</h1>
<form method=”POST”
  action=”SelectBeer.do”>
  Select beer characteristics<p>
  Color:
  <select name=”color” size=”1”>
    <option value=”light”> light </option>
    <option value=”amber”> amber </option>
    <option value=”brown”> brown </option>
    <option value=”dark”> dark </option>
  </select>
  <br><br>
  <center>
    <input type=”SUBMIT”>
  </center>
</form></body></html>
</code>```

The JSP code (used to display results)

```<code><%@ page import=”java.util.*” %>
<html>
<body>
<h1 align=”center”>Beer Recommendations JSP</h1>
<p>
<%
  List styles = (List)request.getAttribute(“styles”);
  Iterator it = styles.iterator();
  while(it.hasNext()) {
    out.print(“<br>try: “ + it.next());
  }
%>
</body>
</html>
</code>```

The Servlet code (used to initialize the Model, get the result of its calculations and forward them to the View component)

```<code>package com.example.web;

import com.example.model.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class BeerSelect extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
           throws IOException, ServletException {

String c = request.getParameter(“color”);
       BeerExpert be = new BeerExpert();
       List result = be.getBrands(c);

request.setAttribute(“styles”, result);
       RequestDispatcher view = request.getRequestDispatcher(“result.jsp”);
       view.forward(request, response);
</code>```

The Model (used to perform the actual calculations and contain the business logic; can also contain interaction with the database)

```<code>package com.example.model;
import java.util.*;

public class BeerExpert {
  public List getBrands(String color) {
    List brands = new ArrayList();
    if (color.equals(“amber”)) {
       brands.add(“Jack Amber”);
       brands.add(“Red Moose”);
    }
    else {
       brands.add(“Jail Pale Ale”);
       brands.add(“Gout Stout”);
    }
    return(brands);
  }
}
</code>```

Please refer to the cited book for more detailed description.

UPDATE - July, 01, 2013

Regarding th three-tier architecture. There are a lot of possible ways to approach this question. The 3-tier design pattern means that your software is architectured in three parts: Presentation layer (the user interface part of the app, might be a browser, SWING app, Android / iOS app., etc), Business Logic Tier (your server-side app consisting of servlets, POJOs, EJBs, etc.) and the Data store tier (could be a relational or object database, NoSQL database, etc.).
So, the three-tier architecture describes how your whole software system / application is organized. There are also so called design patterns that are used to organize the particular tiers / layers of your application / software system. For example, the Business Logic and Presentation tier of your app can be organized in an MVC pattern (like in the previous example, where JSPs and HTML were the UI / View part constituting the Presentation layer of your architecture, while Servlets (the Controller part) and POJOs (the Model part) were collectively your Business Logic Layer. The Data Storage Layer could be covered by the Oracle or MySQL or PostgreSQL database servers and while they become part of your thee-tier architecture, they have nothing to do with the MVC pattern you used to organize your business logic. If you used a SWING app as the Presentation Tier, you could also write that app alone in the MVC style.

You know that there are a lot other options besides MVC. For example, you could build your Business Logic + Presentation Tiers in Model-View-Presenter, Model-View-ViewModel and lots of other design patterns.

Lastly, your could also write a one-tier application (like a MS Access) in an MVC way. The way you architecture your whole system (which tiers you have, etc) does nothing to do with how each of the tiers are designed (MVC, MVP, etc.).

Body:
There is a good example about the MVC pattern applied to JSP and Servlet world in the HeadFirst Servlets and JSP book.

Basically, the Controller part is represented by a Servlet. The JSP is the view and the Model functions are performed by some Plain Old Java Object, i.e. a regular Java Class. In the book they show how you can write a simple BeerExpert app as an illustration of the MVC pattern naturally supported by the Web tier of the J2EE.

The HTML code of the starting page.

<html><body>
<h1 align=”center”>Beer Selection Page</h1>
<form method=”POST”
  action=”SelectBeer.do”>
  Select beer characteristics<p>
  Color:
  <select name=”color” size=”1”>
    <option value=”light”> light </option>
    <option value=”amber”> amber </option>
    <option value=”brown”> brown </option>
    <option value=”dark”> dark </option>
  </select>
  <br><br>
  <center>
    <input type=”SUBMIT”>
  </center>
</form></body></html>

The JSP code (used to display results)

<%@ page import=”java.util.*” %>
<html>
<body>
<h1 align=”center”>Beer Recommendations JSP</h1>
<p>
<%
  List styles = (List)request.getAttribute(“styles”);
  Iterator it = styles.iterator();
  while(it.hasNext()) {
    out.print(“<br>try: “ + it.next());
  }
%>
</body>
</html>

The Servlet code (used to initialize the Model, get the result of its calculations and forward them to the View component)

package com.example.web;

import com.example.model.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class BeerSelect extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
           throws IOException, ServletException {

String c = request.getParameter(“color”);
       BeerExpert be = new BeerExpert();
       List result = be.getBrands(c);

request.setAttribute(“styles”, result);
       RequestDispatcher view = request.getRequestDispatcher(“result.jsp”);
       view.forward(request, response);

The Model (used to perform the actual calculations and contain the business logic; can also contain interaction with the database)

package com.example.model;
import java.util.*;

public class BeerExpert {
  public List getBrands(String color) {
    List brands = new ArrayList();
    if (color.equals(“amber”)) {
       brands.add(“Jack Amber”);
       brands.add(“Red Moose”);
    }
    else {
       brands.add(“Jail Pale Ale”);
       brands.add(“Gout Stout”);
    }
    return(brands);
  }
}

Please refer to the cited book for more detailed description.

UPDATE - July, 01, 2013

Regarding th three-tier architecture. There are a lot of possible ways to approach this question. The 3-tier design pattern means that your software is architectured in three parts: Presentation layer (the user interface part of the app, might be a browser, SWING app, Android / iOS app., etc), Business Logic Tier (your server-side app consisting of servlets, POJOs, EJBs, etc.) and the Data store tier (could be a relational or object database, NoSQL database, etc.).
So, the three-tier architecture describes how your whole software system / application is organized. There are also so called design patterns that are used to organize the particular tiers / layers of your application / software system. For example, the Business Logic and Presentation tier of your app can be organized in an MVC pattern (like in the previous example, where JSPs and HTML were the UI / View part constituting the Presentation layer of your architecture, while Servlets (the Controller part) and POJOs (the Model part) were collectively your Business Logic Layer. The Data Storage Layer could be covered by the Oracle or MySQL or PostgreSQL database servers and while they become part of your thee-tier architecture, they have nothing to do with the MVC pattern you used to organize your business logic. If you used a SWING app as the Presentation Tier, you could also write that app alone in the MVC style.

You know that there are a lot other options besides MVC. For example, you could build your Business Logic + Presentation Tiers in Model-View-Presenter, Model-View-ViewModel and lots of other design patterns.

Lastly, your could also write a one-tier application (like a MS Access) in an MVC way. The way you architecture your whole system (which tiers you have, etc) does nothing to do with how each of the tiers are designed (MVC, MVP, etc.).


问:
Python — Time complexity of built-in functions versus manually-built functions in finite fields
Generally, I'm wondering about the advantages versus disadvantages of using the built-in arithmetic functions versus rolling your own in Python.

Specifically, I'm taking in GF(2) finite field polynomials in string format, converting to base 2 values, performing arithmetic, then output back into polynomials as string format.  So a small example of this is in multiplication:

Rolling my own:

```<code>def multiply(a,b):
    bitsa = reversed("{0:b}".format(a))
    g = [(b<<i)*int(bit) for i,bit in enumerate(bitsa)]
    return reduce(lambda x,y: x+y,g)
</code>```

Versus the built-in:

```<code>def multiply(a,b):  # a,b are GF(2) polynomials in binary form ....
    return a*b  #returns product of 2 polynomials in gf2
</code>```

Currently, operations like multiplicative inverse (with for example 20 bit exponents) take a long time to run in my program as it's using all of Python's built-in mathematical operations like // floor division and % modulus, etc. as opposed to making my own division, remainder, etc.  I'm wondering how much of a gain in efficiency and performance I can get by building these manually (as shown above).

I realize the gains are dependent on how well the manual versions are built, that's not the question.  I'd like to find out 'basically' how much advantage there is over the built-in's.  So for instance, if multiplication (as in the example above) is well-suited for base 10 (decimal) arithmetic but has to jump through more hoops to change bases to binary and then even more hoops in operating (so it's lower efficiency), that's what I'm wondering.  Like, I'm wondering if it's possible to bring the time down significantly by building them myself in ways that maybe some professionals here have already come across.

答:
There is pretty much no way your own hand-rolled operation will be anything but pathetically slow compared to the built-in operations in python. If you try to implement hand-rolled operations you will make you program much much slower.

If you'd like to know how to make your code run faster, ask that question. Post your complete slow code on http://codreview.stackexchange.com, and get feedback there on what can be improved.

OwnerDisplayName: stackuser


问:
Minimizing Dependencies For GUIs
I've been working on a project, and have been charged with designing the projects GUI front-end. I'm coding in Java and using the Swing toolkit. Usability-wise, the GUI front-end follows all of Nielsen's heuristics. Users can easily get to where they want to go through the click of a button / JComboBox. Essentially, in Swing terms, what happens is their actions drive the creation/deletion of custom panels.

The GUI is coming along fine for the most part. However, I have to admit to being utterly dismayed at the tight web of dependencies my code is being smothered in.

The main problem that I've encountered, that I haven't been able to fix as of yet, is how to keep a reference to the panels/buttons being changed.

I'll give an example:

Say there's a button A

Say there's a panel B displaying picture C

Say there's another picture D (not currently being displayed by panel B)

When user clicks A, panel B should remove picture C and display picture D

My question is, what's the best way of keeping track of panel B? Since I need a global point of access to panel B, my solution has so far been to just shoehorn it into a static variable, and access it through a series of static getters and setters. And this static variable is usually stored in the reference's original class. I.e. UserPanel has a static variable that stores a reference to itself.

Is there an easy, tried-and-true way of dealing with these kinds of situations? Like my GUI works fine, but it is not modular and/or robust at all. To add to this, the dreaded 'cyclical dependencies' issue that's shunned by so many programmers is out here in full effect. I'm fairly new to development and just want to make sure that my code will be fairly extensible and won't cause much of a headache to the next person that decides to get a try at it.

I know there's loads of books out there that probably have a nice elegant solution to this, but unfortunately I just don't have the time to leisure read right now. I need something that's quick and dirty.

Thanks in advance

答:
Have you heard of the MVC web layer architecture?  Well, that's flat out wrong.  MVC is a modular GUI design.  It was invented with Smaltalk and helped establish OOP as 'the' way to write GUI applications.

In short, you write model objects that hold whatever information is needed, start with the "document", but also anywhere you have to show a list, or input some complex data, or so.  There should be some core API shared by all (or most) models, but it's ok to add some methods only where the make sense.

Then the view objects are those that handle GUI widgets, controllers, etc. to show the content of the model(s).  Some views are generic and can show almost any model, others are more specific and can be paired only to some subset of model classes.

Lastly the controllers.  Some frameworks omit these, or make them very thin.  But in most cases it's better not to allow the views modify directly model data, it's better to specialize actions in model objects.  This separation typically allows better reuse, a single view can be used in different ways with different controllers.

Note that it's not a layered architecture, each of the different modules in your application will typically have at least one of these trios, but hopefully only a small extra code for each, inheriting most of the behavior from more generic classes.

Title: Minimizing Dependencies For GUIs


问:
What syntax element do you hate most in a programming language you use frequently?
No matter how much you love a programming language, there are always a few details in it that aren’t quite as nice as they could be.

In this question, I would like to specifically focus on syntax elements. In a programming language that you use frequently (perhaps your favourite programming language, or perhaps the one you are forced to use at work), which syntax element do you find most unreadable, unclear, inconvenient or unpleasant?

答:
Java

Period.  Full stop.  End of story.

Where to start?  Oh, I know where to start: Java’s insanely complicated and ugly and stupid  and inherently broken generics.  Need I say more? :(  Ok fine, then: type erasure.

Then there’s non-deterministic resource management.  Kewl feetcher!

What’s next up?  Oh yeah: Java’s stupid regexes are my most irritating, seething beef. I cannot count how many times I’ve been hosed by not having enough backslashes.  This is even worse than not having access to any Unicode properties from this millennium — which is complete bull.  Ten fricking years out of date!!! Completely useless.  Trash it.

Then there’s the bug that the character class shortcuts don’t work on non-ASCII. What a royal pain!  And don’t even consider using \p{javaWhiteSpace}; it doesn’t do the right thing with several very common Unicode whitespace code points.

Did you know there’s a \p{javaJavaIdentifierStart} property?  Whatwhatatat wereere  they thinkinking? So glad they got such smart peepers wurkin on dis tough.

Ever tried to use the CANON_EQ flag? Do you know that really does, and what it doesn’t do?  How about so-called “Unicode case”?  A bunch of normal casing things just don’t work at all.

Then they make it hard to write maintainable regexes.  Java still hasn’t figured out how to write multiline strings, so you end up writing insane things like this:

```<code>    "(?= ^ [A-Z] [A-Za-z0-9\\-] + $)      \n"
  + "(?! ^ .*                             \n"
  + "    (?: ^     \\d+      $            \n"
  + "      | ^ [A-Z] - [A-Z] $            \n"
  + "      | Invitrogen                   \n"
  + "      | Clontech                     \n"
  + "      | L-L-X-X                      \n"
  + "      | Sarstedt                     \n"
  + "      | Roche                        \n"
  + "      | Beckman                      \n"
  + "      | Bayer                        \n"
  + "    )      # end alternatives        \n"
  + ")          # end negated lookahead   \n"
</code>```

What are all those newlines?  Oh, just Java stupidity. They used Perl comments, not Java comments (idiots!) which go till end of line.  So if you don’t put those \n’s there, you chop off the rest of your pattern.  Duh and double duh!

Don’t use regexes in Java: you’ll just end up wanting to smash things, it’s all so painful and broken. I can’t believe people put up with this.  Some don’t.

Then we can start talking about Java’s idiot nonsense with encodings. First, there’s the fact that the default platform encoding is always some lame 8-bit encoding even though Java’s charchars are Unicode.  Then there’s how they don’t raise an exception on an encoding error.  You’re guaranteed to get crap.  Or how about this:

```<code>OutputStreamWriter(OutputStream out)
          Creates an OutputStreamWriter that uses the default character encoding.
OutputStreamWriter(OutputStream out, Charset cs)
          Creates an OutputStreamWriter that uses the given charset.
OutputStreamWriter(OutputStream out, CharsetEncoder enc)
          Creates an OutputStreamWriter that uses the given charset encoder.
OutputStreamWriter(OutputStream out, String charsetName)
          Creates an OutputStreamWriter that uses the named charset.
</code>```

What’s the difference?  Did you know that only one of those will raise an exception if you have an encoding error?  The rest just muzzle them.

Then there’s the idiocy of Java chars not being sufficient to hold a character!  What the hell are they thinking?  That’s why I call them charchars.  You have to write code like this if you expect it work right:

```<code>private static void say_physical(String s) {
    System.out.print("U+");
    for (int i = 0; i < s.length(); i++) {
        System.out.printf("%X", s.codePointAt(i));
        if (s.codePointAt(i) > Character.MAX_VALUE) { i++; }  // UG!
        if (i+1 < s.length()) { System.out.printf("."); }
    }
}
</code>```

And who ever thinks to do that? Next to nobody.

How many characters are there in "\uD83D\uDCA9"?  One or two? Depends on how you count them.  The regex engine of course deals with logical characters, so a pattern ^.$ will succeed and a pattern ^..$ will fail.  This insanity is demonstrated here:

```<code>String { U+61, "\u0061", "a" }  =~ /^.$/ => matched.
String { U+61, "\u0061", "a" }  =~ /^..$/ => failed.
String { U+61.61, "\u0061\u0061", "aa" }  =~ /^.$/ => failed.
String { U+61.61, "\u0061\u0061", "aa" }  =~ /^..$/ => matched.
String { U+DF, "\u00DF", "ß" }  =~ /^.$/ => matched.
String { U+DF, "\u00DF", "ß" }  =~ /^..$/ => failed.
String { U+DF.DF, "\u00DF\u00DF", "ßß" }  =~ /^.$/ => failed.
String { U+DF.DF, "\u00DF\u00DF", "ßß" }  =~ /^..$/ => matched.
String { U+3C3, "\u03C3", "σ" }  =~ /^.$/ => matched.
String { U+3C3, "\u03C3", "σ" }  =~ /^..$/ => failed.
String { U+3C3.3C3, "\u03C3\u03C3", "σσ" }  =~ /^.$/ => failed.
String { U+3C3.3C3, "\u03C3\u03C3", "σσ" }  =~ /^..$/ => matched.
String { U+1F4A9, "\uD83D\uDCA9", "" }  =~ /^.$/ => matched.
String { U+1F4A9, "\uD83D\uDCA9", "" }  =~ /^..$/ => failed.
String { U+1F4A9.1F4A9, "\uD83D\uDCA9\uD83D\uDCA9", "" }  =~ /^.$/ => failed.
String { U+1F4A9.1F4A9, "\uD83D\uDCA9\uD83D\uDCA9", "" }  =~ /^..$/ => matched.
</code>```

That idiocy is all because you can’t write the perfectly reasonable \u1F4A9, nor of course do you get any warning that you can’t do that. It just does the wrong thing.

Stoooopid.

While we’re at it, the whole \uXXXX notation is congenitally brain dead. The Java preprocessor (yes, you heard me) gets at it before Java does, so you are forbidden from writing perfectly reasonable things like "\u0022", because by the time Java sees that, its preprocessor has turned it into """, so you lose.  Oh wait, not if it’s in a regex! So you can use "\\u0022" just fine.

Riiiiiiiight!

Did you know there’s no way in Java to do an isatty(0) call?  You aren’t even allowed to think such thoughts.  It wouldn’t be good for you.

And then there’s the whole classpath abomination.

Or the fact that there’s no way to specify the encoding of your Java source file in that same source file so you don’t lose it?  Once again I demand to know: WHAT THE HELL WERE THEY THINKING‽‽‽

Stop the madness!  I can’t believe people put up with this garbage.  It’s a complete joke. I’d rather be a Walmart greeter than suffer the slings and arrows of outrageous Java insanity.  It’s all broken, and they not only can’t fix it, they won’t fix it.

This by the same foxy-grapey people who prided themselves on a language that made it illegal to have a printf() function. Gee, that sure worked out real well, didn’t it though!?

Sheer numbskulls. Bitch-slapping is too kind for them. If I wanted to program in assembler, I would. This is not a salvageable language. The emperor has no clothes.

We hates it.  We hates it forever. Let it die die die!

Body:
Java

Period.  Full stop.  End of story.

Where to start?  Oh, I know where to start: Java’s insanely complicated and ugly and stupid  and inherently broken generics.  Need I say more? :(  Ok fine, then: type erasure.

Then there’s non-deterministic resource management.  Kewl feetcher!

What’s next up?  Oh yeah: Java’s stupid regexes are my most irritating, seething beef. I cannot count how many times I’ve been hosed by not having enough backslashes.  This is even worse than not having access to any Unicode properties from this millennium — which is complete bull.  Ten fricking years out of date!!! Completely useless.  Trash it.

Then there’s the bug that the character class shortcuts don’t work on non-ASCII. What a royal pain!  And don’t even consider using \p{javaWhiteSpace}; it doesn’t do the right thing with several very common Unicode whitespace code points.

Did you know there’s a \p{javaJavaIdentifierStart} property?  Whatwhatatat wereere  they thinkinking? So glad they got such smart peepers wurkin on dis tough.

Ever tried to use the CANON_EQ flag? Do you know that really does, and what it doesn’t do?  How about so-called “Unicode case”?  A bunch of normal casing things just don’t work at all.

Then they make it hard to write maintainable regexes.  Java still hasn’t figured out how to write multiline strings, so you end up writing insane things like this:

    "(?= ^ [A-Z] [A-Za-z0-9\\-] + $)      \n"
  + "(?! ^ .*                             \n"
  + "    (?: ^     \\d+      $            \n"
  + "      | ^ [A-Z] - [A-Z] $            \n"
  + "      | Invitrogen                   \n"
  + "      | Clontech                     \n"
  + "      | L-L-X-X                      \n"
  + "      | Sarstedt                     \n"
  + "      | Roche                        \n"
  + "      | Beckman                      \n"
  + "      | Bayer                        \n"
  + "    )      # end alternatives        \n"
  + ")          # end negated lookahead   \n"

What are all those newlines?  Oh, just Java stupidity. They used Perl comments, not Java comments (idiots!) which go till end of line.  So if you don’t put those \n’s there, you chop off the rest of your pattern.  Duh and double duh!

Don’t use regexes in Java: you’ll just end up wanting to smash things, it’s all so painful and broken. I can’t believe people put up with this.  Some don’t.

Then we can start talking about Java’s idiot nonsense with encodings. First, there’s the fact that the default platform encoding is always some lame 8-bit encoding even though Java’s charchars are Unicode.  Then there’s how they don’t raise an exception on an encoding error.  You’re guaranteed to get crap.  Or how about this:

OutputStreamWriter(OutputStream out)
          Creates an OutputStreamWriter that uses the default character encoding.
OutputStreamWriter(OutputStream out, Charset cs)
          Creates an OutputStreamWriter that uses the given charset.
OutputStreamWriter(OutputStream out, CharsetEncoder enc)
          Creates an OutputStreamWriter that uses the given charset encoder.
OutputStreamWriter(OutputStream out, String charsetName)
          Creates an OutputStreamWriter that uses the named charset.

What’s the difference?  Did you know that only one of those will raise an exception if you have an encoding error?  The rest just muzzle them.

Then there’s the idiocy of Java chars not being sufficient to hold a character!  What the hell are they thinking?  That’s why I call them charchars.  You have to write code like this if you expect it work right:

private static void say_physical(String s) {
    System.out.print("U+");
    for (int i = 0; i < s.length(); i++) {
        System.out.printf("%X", s.codePointAt(i));
        if (s.codePointAt(i) > Character.MAX_VALUE) { i++; }  // UG!
        if (i+1 < s.length()) { System.out.printf("."); }
    }
}

And who ever thinks to do that? Next to nobody.

How many characters are there in "\uD83D\uDCA9"?  One or two? Depends on how you count them.  The regex engine of course deals with logical characters, so a pattern ^.$ will succeed and a pattern ^..$ will fail.  This insanity is demonstrated here:

String { U+61, "\u0061", "a" }  =~ /^.$/ => matched.
String { U+61, "\u0061", "a" }  =~ /^..$/ => failed.
String { U+61.61, "\u0061\u0061", "aa" }  =~ /^.$/ => failed.
String { U+61.61, "\u0061\u0061", "aa" }  =~ /^..$/ => matched.
String { U+DF, "\u00DF", "ß" }  =~ /^.$/ => matched.
String { U+DF, "\u00DF", "ß" }  =~ /^..$/ => failed.
String { U+DF.DF, "\u00DF\u00DF", "ßß" }  =~ /^.$/ => failed.
String { U+DF.DF, "\u00DF\u00DF", "ßß" }  =~ /^..$/ => matched.
String { U+3C3, "\u03C3", "σ" }  =~ /^.$/ => matched.
String { U+3C3, "\u03C3", "σ" }  =~ /^..$/ => failed.
String { U+3C3.3C3, "\u03C3\u03C3", "σσ" }  =~ /^.$/ => failed.
String { U+3C3.3C3, "\u03C3\u03C3", "σσ" }  =~ /^..$/ => matched.
String { U+1F4A9, "\uD83D\uDCA9", "" }  =~ /^.$/ => matched.
String { U+1F4A9, "\uD83D\uDCA9", "" }  =~ /^..$/ => failed.
String { U+1F4A9.1F4A9, "\uD83D\uDCA9\uD83D\uDCA9", "" }  =~ /^.$/ => failed.
String { U+1F4A9.1F4A9, "\uD83D\uDCA9\uD83D\uDCA9", "" }  =~ /^..$/ => matched.

That idiocy is all because you can’t write the perfectly reasonable \u1F4A9, nor of course do you get any warning that you can’t do that. It just does the wrong thing.

Stoooopid.

While we’re at it, the whole \uXXXX notation is congenitally brain dead. The Java preprocessor (yes, you heard me) gets at it before Java does, so you are forbidden from writing perfectly reasonable things like "\u0022", because by the time Java sees that, its preprocessor has turned it into """, so you lose.  Oh wait, not if it’s in a regex! So you can use "\\u0022" just fine.

Riiiiiiiight!

Did you know there’s no way in Java to do an isatty(0) call?  You aren’t even allowed to think such thoughts.  It wouldn’t be good for you.

And then there’s the whole classpath abomination.

Or the fact that there’s no way to specify the encoding of your Java source file in that same source file so you don’t lose it?  Once again I demand to know: WHAT THE HELL WERE THEY THINKING‽‽‽

Stop the madness!  I can’t believe people put up with this garbage.  It’s a complete joke. I’d rather be a Walmart greeter than suffer the slings and arrows of outrageous Java insanity.  It’s all broken, and they not only can’t fix it, they won’t fix it.

This by the same foxy-grapey people who prided themselves on a language that made it illegal to have a printf() function. Gee, that sure worked out real well, didn’t it though!?

Sheer numbskulls. Bitch-slapping is too kind for them. If I wanted to program in assembler, I would. This is not a salvageable language. The emperor has no clothes.

We hates it.  We hates it forever. Let it die die die!