答:
The main thing that stands out for me in your entire post is that you see C# and SQL as two completely different languages that can't (easily) work together. This is understandable when you've been using a language which integrates the two and you see examples all over the Internet where people are hard coding SQL in their application code.

The easiest thing you could do that would help you overcome this barrier is to look into using an ORM such as Fluent NHibernate. This will allow you to treat your database as just another layer of code. You create classes to represent your database entities and a mapping class that tells the code how to map each column (eg: "the PersonID column is an int and is an incrementing value). This means that you are then always dealing with nice objects in your code.

The next step would be to look at introducing the repository pattern which you get for free with NHibernate (the ISession property is what you want to look in to). This prevents you having to write SQL in your code as the framework can take lambda expressions and make use of LINQ to (under the hood) generate the SQL that you would otherwise have to hand write.

The biggest thing I can suggest is to make use of the brilliant frameworks that people have written to make our lives easier.

Good luck!

Edit: Apologies for any typos, I typed this on my iPhone while waiting for a flight at the airport!

Title: Fitting it together, database, reporting, applications in C#

Body:
Introduction

Preamble

I was hesitant to post this, since it's an application whose intricate details are defined elsewhere, and answers may not be helpful to others. Within the past few weeks (I was actually going to write a blog post about this after I finished) I've discovered that the barrier I'm encountering is one that's actually quite common for newer developers.

This question is not so much about a specific thing as it is about piecing those things together.

I've searched the internet far and wide, and found many tutorials on how to create applications that are kind of similar to what I'm looking for. I've also looked at hiring another, more experienced, developer to help me along, but all I've gotten are unqualified candidates that don't have the experience necessary and won't take care of the client or project like I will. I'd rather have the project never transpire than to release a solution that is half-baked.

I've asked professors at my school, but they've not turned up answers to my question. I'm an experienced developer, and I've written many applications that are -- very abstractly -- close to what I'm doing, but my experiences from those applications aren't giving me enough leverage to solve this particular problem.

I just hope that posting this article isn't a mistake for me to write.

Project Description

I have a project I'm working on for a client that is a rewrite of an application, originally written in Foxpro 2.6 by someone before me, that performs some analysis (which, sadly, I'm not allowed to disclose as per of my employment contract) on financial data.

One day, after a long talk between the client and I -- where he intimately described his frustrations with all the bugs I've been hacking out of this code for 6 months now -- he told me to just rewrite it and gave me a month to write a good 1/8 of this 65k LOC Foxpro monstrosity.  this 65k line of code foxpro monstrosity. It'll take me a good 3 - 6 months to rewrite this software (I know things the original programmer did not, like inheritance) going as I am right now, but I'm quickly discovering that I'm going to need to use databases.

Prior to this contract I didn't even know about foxpro, and so I've had to learn foxpro on the fly, write procedures and make modifications to the database. I've actually come to like it, and this project would be rewritten in Foxpro if it were still a supported language, because over the past few months, I've come to like the features of Foxpro that make it so easy to develop data-driven applications.

I once perfomed an experiment, comparing C# to Foxpro. What took me 45 minutes in C# took me two in Foxpro, and I knew C# prior to Foxpro.

I was hoping to leverage the power of C#, but it intimidates me that in foxpro, you can have one line of code and be using a database.

Prior to this, I have never written any serious database development from scratch. All the applications that I've written are in a different league. They are either completely data-naive or data-naive enough that I can get away with not using a database through serialization or by designing algorithms that work with the data in a manner that is stateless, so there is no need to worry about databases.

I've come to realize, very quickly, that serialization and my efficacy with data structures has been my crutch all these years that's prevented me from adventuring into databases, and has consequently hindered my success in real-world programming.

Sure, I've written some database stuff in Perl and Python, and I've done forms and worked with relational databases and tables, I'm a wizard in Access and Excel (seriously) and can do just about anything, but it just feels unnatural writing SQL code in another language...

I don't mind writing SQL, and I don't It's that bridge between the database and the program code that drives me absolutely bonkers. I hope I'm not the only one to think this, but it bothers me that I have to create statements like the following

```<code>string sSql =  "SELECT * from tablename"
</code>```

When there's really no reason for that kind of unchecked language binding between two languages and two API's. Don't get my wrong, SQL is great, but I don't like the idea that, when executing commands on a SQL database, that one must intermix database and application software, and there's no database independence, which means that different versions of different databases can break code. This isn't very nice.

The nicest thing about Foxpro is the cohesiveness between programming language and database. It's so easy, and Foxpro makes it easy, because the tool just fits the task. I can see why so many developers have created a career with this language, because it lowered the barrier of entry to data-driven applications that so many businesses need. It was wonderful.

For my purposes today, with the demands and need for community support, extensibility, and language features, Foxpro isn't a solution that I feel would be the right tool for the job.

I'm also worried about working too heavy with the database, because I've seen data-driven .NET applications have issues with database caches, running out of memory, and objects in the database not being collected. (Memory leaks)

And OH the queries.

Which one, how, and why?

There are a plethora of different ways that a database can be setup, I think I counted 5 or 6 different kinds of database applications alone that I can chose from. That is a great mountain for me to climb when I don't even know where to begin when it comes to writing data-driven applications.

The problem isn't that I don't know SQL or that I don't know C#. I know both and have worked with both extensively. It's making them work together that's the problem, and it's something I've never done in C# before.

Reports

The client likes paper. The data needs to be printed out in a format that is extensible, layered, and easy to use. I have never done reporting before, and so this is a bit of a problem. From the data source comes crystal reports, and so there's a dependency on the database, from what I understand.

Code reuse

A large part of the design decision that I've gone through so far is to break the task of writing a piece of this software into routines and modular DLL's and so forth such that much of the code can be reused.

For example, when I setup this database, I want to be able to reuse the same database code over and over again.

I also want to make sure that when the day comes that another developer is here, that he/she will be able to pick up just where I left off.

The quicker I develop these applications, the better off I am.

Tasks & Goals

In my project, I need to write routines that apply algorithms and look for predefined patterns in financial data. Additionally, I need to simulate trading based on predefined algorithms and data. Then I need to prepare reports on that data.

Additionally, I need to have a way to change the code base for this application quickly and effectively, without hacking together some band-aid solution for a problem that really needs a trauma ward.

Special Considerations

The solution must be fast, run quickly on existing hardware, and not be too much of a pain to maintain and write. I understand that anything I write I'm married to -- I'm responsible for the things that I write because my reputation and livelihood is dependent on it.

Do I really need a database?

What about performance? Performance was such a big issue that I hand wrote a data structure that is capable of performing 2 billion operations, using a total of 4 gigs of memory in under 1/4 of a second using the standard core two duo processor. I could not find a similar, pre-written data structure in C# to perform this task.

What setup do I use in terms of database?

What about reporting? I'd prefer to have PDF's generated, but I'd like to be able to visually sketch those reports and then just have a ReportFactory of some sort, that when I pass some variables in, it just does that data.

About Me

I'm a lone developer for a small business in this area. This is the first time I've done this and I've never had the breadth and depth of my knowledge tested.

I'm incredibly frustrated with this project because I feel incredibly overwhelmed with the task at hand.

I'm looking for that entry level point where I can draw a line and say "this is what I need to do"

 Conclusion

I may have not been clear enough on my post. I'm still new to this whole thing, and I've been doing my best to contribute back to the community that I've leached so much knowledge from. I'd be glad to edit my post and add more information if possible.

I'm looking for a big-picture solution or design process that helps me get off the ground in this world of data-driven applications, because I have a feeling that it's going to be concentric to my entire career as a programmer for some time.

Specifically, if you didn't get it from the rest of the post (I may not have been clear enough) I really need some guidance as to where to go in terms of the design decisions for this project. Some things that'll be useful will be a pro/con list for the different kinds of database projects available in VS2010. I've tried, but generating that list has been as hard as solving the problem itself...

If you could walk a developer writing a data-driven application for the first time in C#, how would you do that? Where would you point them to?


问:
Who are 'users' in testing?
Having e.g. a system for booking flights, during UAT it is not being tested by real users (customers who will buy tickets) rather than people from the client side who will just simulate this. Are there any more specific terms to distinquish between real users (like end user) and users doing the UAT?</p>

答: Where I work, we are building an internal application and use the terms 'the business' (which are the real end users) and 'testers' (those who do the UATs).</p>

ContentLicense: CC BY-SA 3.0

Title: Who are 'users' in testing?


答:
The customers who are going to buy ticket are not the real users of the application.

Real users are those who are going to deploy the application and will be operating the system.

Customers will just be requesting for the ticket, mentioning their details (not filling any of the details at their own).
The employees of the company will be operating the application, filling the details mentioned by the customer and filling other requirements.

So, the employees will be the real users. They participate in testing, as they need to customize the application as per their requirements.

Title: Who are 'users' in testing?

Body: Having e.g. a system for booking flights, during UAT it is not being tested by real users (customers who will buy tickets) rather than people from the client side who will just simulate this. Are there any more specific terms to distinquish between real users (like end user) and users doing the UAT?</p>


问:
General programming techniques to speed up coding time
I am preparing for a programming contest where we have to code in C++ and it is all about producing working code in a short time. An example would be to use a macro to get the minimum of two ints or using memsets to initialize arrays (but I was told that you shouldn't use either here).

This leads to the question, what kind of coding techniques exist to use at a real job?

答:
Software development is one of those classic 80-20 activities -- ie where the first 80% of the work takes 20% of the time, and the last 20% of the work takes 80% of the time.

The key to speeding up your work in general is, therefore, to work on improving your performance for that that last 20% of the effort. This is typically the debugging stages and the work to tie everything together and make it usable.

You can improve this by taking more care in the early stages. Planning and design work at the outset of a project may seem like a waste of time when you're tempted to dive into the hardcore programming, but they can save a vast amount of time later on.

People will talk about specific methodologies like TDD or BDD. These are great, but if you're not doing them now they will take you a bit of time to adjust to, so they're probably not something that you want to be starting out with for a programming contest. But stopping to plan what you're doing before you dive in and do it will reap rewards no matter what. And they're the first steps toward TDD and BDD anyway. This is where you want to start.


问:
Good practices for large scale development/delivery of software
What practices do you apply when working with large teams on multiple versions of a software or multiple competing projects? What are best practices that can be used to still get the right things done first?

Is there information available how big IT companies do development and management of some of their large projects, e.g. things like Oracle Database, WebSphere Application Server, Microsoft Windows, ....?

答:
Creating big software is a hard thing to do properly, and folowing good practices is very important.

A good start is to design the system properly. Partition it as much as possible, and create good interfaces (that's why hardware engineers are some times very good architects).

Common concepts apply there as well (code repository, unit testing the code, contious integration, etc).


问:
Revamp application
I am a software developer having an experience of 3 yrs. I want to play with latest technologies always. But this is not practical. Because say, I developed a web application in .Net 3.5, now its 30% done. After the release of .Net 4.0, my mind is always goes with .Net 4.0. I think like this, lot of features are in new version, so why shouln't I implement those versions in my application.

When I worked with IT companies, most of them code with very old versions, some body use VB.NET, C, even Classic ASP.

So what might be the points should I consider if I revamp an application?

答:
Remember, legacy code is still legacy code for a reason. It works, and it's too complicated and large scale to correctly replace. Sometimes a new shiny version is not the best option. For example, python 3 caused a bit of a stir over compatibility.

In practice, some things to remember :

Replace deprecated methods

New language optimisations may provide better ways to do something, check the chagelogs

Dependecies/Compatabilty, what is your application interacting with?

Title: Revamp application


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

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

or should it be

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

or even

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

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

答:
I would prefer 2nd and 3rd method.

1st Method are usually from veteran programmers who learn the old stuff and get used to it. I find it very hard to read the codes last time. Luckily VS2010, make it more easily to read but what happen if you open up other editors? There will be problems.

2nd Method are more clearly define and its more easy on your eyes. You will not have much difficulties looking for the ending braces compared to the first one.

3rd Method will save more space and its clearly define its only reading one line of statement. I disagree with people about programmer taking over and making mistake. It was a careless mistake if they overlooked on this.

ContentLicense: CC BY-SA 2.5


问:
What's the equivalent name of "procedure" in OOP?
In several of my programming courses in the University, my teachers always told me the following:

A function and a procedure are basically the same thing: the only difference is that a function returns a value, and the procedure doesn't.

That means that this:

```<code>function sum($a, $b) {
    return $a + $b;
}
</code>```

... is a function, and this:

```<code>function sum($a, $b) {
    echo $a + $b;
}
</code>```

... is a procedure.

In the same train of thought, I've seen that a method is the equivalent of a function in the OOP world.

That means that this:

```<code>class Example {
    function sum($a, $b) {
        return $a + $b;
    }
}
</code>```

Is a method — but how do you call this?

```<code>class Example {
    function sum($a, $b) {
        echo $a + $b;
    }
}
</code>```

What's the equivalent name, or how do you call a method that doesn't returns anything?

答:
One of the Object-Oriented Design Principles set forth by Bertrand Meyer in his book Object-Oriented Software Construction is the Command / Query Segregation Principle. In it he suggests that every method should either be a Query, which he defines to be a pure, referentially transparent method that returns (a function of) some internal state and has no side-effects, or a Command which alters some internal state or performs a side-effect, and which has only side-effects and does not return a value.

So, following this terminology, you could call them Query Methods and Command Methods.

Another possibility that I have encountered is calling them Functional Methods or Procedural Methods.

Pure Methods and Impure Methods are also sometimes used.

Note that as @Loki Astari pointed out in his comment on your question that there does not exist a universally accepted name for a subroutine which has both side-effects and returns a value. Some people call that a procedure, some call it an impure function, C, JavaScript and Python just call it a function. The same applies to methods also.


问:
What are the drawbacks of Python?
Python seems all the rage these days, and not undeservingly - for it is truly a language with which one almost enjoys being given a new problem to solve. But, as a wise man once said (calling him a wise man only because I've no idea as to who actually said it; not sure whether he was that wise at all), to really know a language one does not only know its syntax, design, etc., advantages but also its drawbacks. No language is perfect, some are just better than others.

So, what would be in your opinion, objective drawbacks of Python.

Note: I'm not asking for a language comparison here (i.e. C# is better than Python because ... yadda yadda yadda) - more of an objective (to some level) opinion which language features are badly designed, whether, what are maybe some you're missing in it and so on. If must use another language as a comparison, but only to illustrate a point which would be hard to elaborate on otherwise (i.e. for ease of understanding)

答: Python has no tail-call optimization, mostly for philosophical reasons. This means that tail-recursing on large structures can cost O(n) memory (because of the unnecessary stack that is kept) and will require you to rewrite the recursion as a loop to get O(1) memory.</p>

Title: What are the drawbacks of Python?


问:
Managed Languages vs Compiled Language difference?
I get confused when people try to make a distinction between compiled languages and managed languages. From experience, I understand that most consider compiled languages to be C,C++ while managed languages are Java,C# (There are obviously more, but these are just few examples). But what exactly is the core difference between the two types of languages?

My understanding is that any program, regardless of what language you use is essentially "compiled" into a low-level machine code which is then interpreted, so does that kinda make managed languages a subset of compiled languages (That is, all managed languages are compiled languages but not the other way around)?

答:
To quote Wikipedia:

Managed code is a term coined by Microsoft to identify computer program source code that requires and will only execute under the management of a Common Language Runtime virtual machine (resulting in bytecode).

Managed code needs a runtime (like the .NET CLT) to execute.


问:
Is catching general exceptions really a bad thing?
I typically agree with most code analysis warnings, and I try to adhere to them. However, I'm having a harder time with this one:

CA1031: Do not catch general exception types

I understand the rationale for this rule. But, in practice, if I want to take the same action regardless of the exception thrown, why would I handle each one specifically? Furthermore, if I handle specific exceptions, what if the code I'm calling changes to throw a new exception in the future? Now I have to change my code to handle that new exception. Whereas if I simply caught Exception my code doesn't have to change.

For example, if Foo calls Bar, and Foo needs to stop processing regardless of the type of exception thrown by Bar, is there any advantage in being specific about the type of exception I'm catching?

Maybe a better example:

```<code>public void Foo()
{
    // Some logic here.
    LogUtility.Log("some message");
}

public static void Log()
{
    try
    {
        // Actual logging here.
    }
    catch (Exception ex)
    {
        // Eat it. Logging failures shouldn't stop us from processing.
    }
}
</code>```

If you don't catch a general exception here, then you have to catch every type of exception possible. Patrick has a good point that OutOfMemoryException shouldn't be dealt with this way. So what if I want to ignore every exception but OutOfMemoryException?

答:
I understand the rationale for this rule. But, in practice, if I want
  to take the same action regardless of the exception thrown, why would
  I handle each one specifically?

As others have said, it's really difficult (if not impossible) to imagine some action that you'd want to take regardless of the exception thrown. Just one example are situations where the program's state has been corrupted and any further processing can lead to problems (this is the rationale behind Environment.FailFast).

Furthermore, if I handle specific exceptions, what if the code I'm
  calling changes to throw a new exception in the future? Now I have to
  change my code to handle that new exception. Whereas if I simply
  caught Exception my code doesn't have to change.

For hobby code it's just fine to catch Exception, but for professional-grade code introducing a new exception type should be treated with the same respect as a change in the method signature, i.e. be considered a breaking change. If you subscribe to this point of view then it's immediately obvious that going back to change (or verify) the client code is the only correct course of action.

For example, if Foo calls Bar, and Foo needs to stop processing
  regardless of the type of exception thrown by Bar, is there any
  advantage in being specific about the type of exception I'm catching?

Sure, because you will not be catching just exceptions thrown by Bar. There will also be exceptions that Bar's clients or even the runtime might throw during the time that Bar is on the call stack. A well-written Bar should define its own exception type if necessary so that callers can specifically catch the exceptions emitted by itself.

So what if I want to ignore every exception but OutOfMemoryException?

IMHO this is the wrong way to think about exception handling. You should be operating on whitelists (catch exception types A and B), not on blacklists (catch all exceptions apart from X).


答:
The difference is not in "compiled" vs. "managed", these are two orthogonal axes. By "managed" they normally mean a presence of a garbage-collected memory management and/or a presence of a virtual machine infrastructure. Both has absolutely nothing to do with compilation and whatever people deem to be opposite to it.

All this "differences" are quite blurred, artificial and irrelevant, since it is always possible to mix managed and unmanaged memory in a single runtime, and a difference between compilation and interpretation is very vague too.

Title: Managed Languages vs Compiled Language difference?

Body:
I get confused when people try to make a distinction between compiled languages and managed languages. From experience, I understand that most consider compiled languages to be C,C++ while managed languages are Java,C# (There are obviously more, but these are just few examples). But what exactly is the core difference between the two types of languages?

My understanding is that any program, regardless of what language you use is essentially "compiled" into a low-level machine code which is then interpreted, so does that kinda make managed languages a subset of compiled languages (That is, all managed languages are compiled languages but not the other way around)?


答:
A function is a collection of computing statements. So is a procedure. In some very anal retentive languages, though, a function returns a value and a procedure doesn't. In such languages procedures are generally used for their side effects (like I/O) while functions are used for calculations and tend to avoid side effects. (This is the usage I tend to favour. Yes, I am that anal retentive.)

Most languages are not that anal retentive, however, and as a result people will use the terms "function" and "procedure" interchangeably, preferring one to the other based on their background. (Modula-* programmers will tend to use "procedure" while C/C++/Java/whatever will tend to use "function", for example.)

A method is just jargon for a function (or procedure) bound to a class. Indeed not all OOP languages use the term "method". In a typical (but not universal!) implementation, methods have an implied first parameter (called things like this or self or the like) for accessing the containing class. This is not, as I said, universal. Some languages make that first parameter explicit (and thus allow to be named anything you'd like) while in still others there's no magic first parameter at all.

```<code>class MyClass
{
  int memberVariable;

  void setMemberVariableProcedure(int v)
  {
    memberVariable = v;
  }

  int getMemberVariableFunction()
  {
    return memberVariable;
  }
};

void plainOldProcedure(int stuff)
{
  cout << stuff;
}

int plainOldFunction(int stuff)
{
  return 2 * stuff;
}
</code>```

In this code getMemberVariableProcedure and getMemberVariableFunction are both methods.

Title: What's the equivalent name of "procedure" in OOP?

Body:
In several of my programming courses in the University, my teachers always told me the following:

A function and a procedure are basically the same thing: the only difference is that a function returns a value, and the procedure doesn't.

That means that this:

```<code>function sum($a, $b) {
    return $a + $b;
}
</code>```

... is a function, and this:

```<code>function sum($a, $b) {
    echo $a + $b;
}
</code>```

... is a procedure.

In the same train of thought, I've seen that a method is the equivalent of a function in the OOP world.

That means that this:

```<code>class Example {
    function sum($a, $b) {
        return $a + $b;
    }
}
</code>```

Is a method — but how do you call this?

```<code>class Example {
    function sum($a, $b) {
        echo $a + $b;
    }
}
</code>```

What's the equivalent name, or how do you call a method that doesn't returns anything?

Body:
A function is a collection of computing statements. So is a procedure. In some very anal retentive languages, though, a function returns a value and a procedure doesn't. In such languages procedures are generally used for their side effects (like I/O) while functions are used for calculations and tend to avoid side effects. (This is the usage I tend to favour. Yes, I am that anal retentive.)

Most languages are not that anal retentive, however, and as a result people will use the terms "function" and "procedure" interchangeably, preferring one to the other based on their background. (Modula-* programmers will tend to use "procedure" while C/C++/Java/whatever will tend to use "function", for example.)

A method is just jargon for a function (or procedure) bound to a class. Indeed not all OOP languages use the term "method". In a typical (but not universal!) implementation, methods have an implied first parameter (called things like this or self or the like) for accessing the containing class. This is not, as I said, universal. Some languages make that first parameter explicit (and thus allow to be named anything you'd like) while in still others there's no magic first parameter at all.

class MyClass
{
  int memberVariable;

  void setMemberVariableProcedure(int v)
  {
    memberVariable = v;
  }

  int getMemberVariableFunction()
  {
    return memberVariable;
  }
};

void plainOldProcedure(int stuff)
{
  cout << stuff;
}

int plainOldFunction(int stuff)
{
  return 2 * stuff;
}

In this code getMemberVariableProcedure and getMemberVariableFunction are both methods.


问:
Learning OO for a C Programmer
I've been programming professionally in C, and only C, for around 10 years in a variety of roles.

As would be normal to expect, I understand the idioms of the language fairly well and beyond that also some of the design nuances - which APIs to make public, who calls what, who does what, what is supposed to reentrant and so on. I grew up reading 'Writing Solid Code', it's early C edition, not the one based on C++.

However, I've never ever programmed in an OO language. Now, I want to migrate to writing applications for iPhone (maybe android), so want to learn to use Objective-C and use it with a degree of competence fitting a professional programmer.

How do I wrap my head around the OO stuff? What would be your smallest reading list suggestion to me.

Is there a book that carries some sort of relatively real world example OO design Objective-C?

Besides, the reading what source code would you recommend me to go through.

How to learn OO paradigm using Objective-C?

答:
Object oriented programming is different but not that different. The main thing is that you can stick together state and functions. This can either be done on a class of object level (one per type of object) or on the object level. I'd take a look at some implementations of object oriented programming for C. Like this for example:

http://c.learncodethehardway.org/book/learn-c-the-hard-waych20.html#x25-9700020

The difference with an natively object oriented programming language would be calling Object_method(struct Object *object, args..) and object.method(args..), basically just that you can add methods to a struct that you can call on the object itself.

Python is a simple language to learn object oriented programming in, python is also quite explicit on the "self" variable that points to the object itself.
http://net.tutsplus.com/tutorials/python-tutorials/python-from-scratch-object-oriented-programming/

OTOH, I find that my small experience with SmallTalk was the thing that really made it easy to get started with Objective-C. Looking at some examples of SmallTalk is a great way to understand why things are as they are in Objective-C. Python is easier for grasping the fundamentals of OO though as SmallTalk has more magic feel to it. http://en.wikipedia.org/wiki/Smalltalk

EDIT: (once you have wrapped your head around what OO programming is about)

I'd take a look at the Stanford class on iOS development available for free on itunes. Really good stuff and a solid academic style introduction to iOS programming. The first episode goes through the basics of Objective-C. http://itunes.apple.com/us/itunes-u/ipad-iphone-application-development/id473757255

Then head over to:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Introduction/introObjectiveC.html

Title: Learning OO for a C Programmer


问:
Relationship between SOA and OOA
Thomas Erl defines SOA as follows in his site:

Service-oriented computing represents a new generation distributed
computing platform. As such, it encompasses many things, including its
own design paradigm and design principles, design pattern catalogs,
pattern languages, a distinct architectural model, and related
concepts, technologies, and frameworks.

This definitely sounds like a whole new category which is parallel to object orientation. Almost one in which you would expect an entirely new language to exist for. Like procedural C and object oriented C#.

Here is my understanding:
In real life, we don't have entirely new language for SOA. And most application which have SOA architecture have an object oriented design underneath it. SOA is a "strategy" to make the entire application/service distributed and reliable. SOA needs OOPS working underneath it.

Is this correct? Where does SOA (if at all it does) fit in with object oriented programming practices?

Edit: I have learnt through answers that OOA and SOA work with each other and cannot be compared (in a "which is better" way). I have changed the title to "Relationship between SOA and OOA" rather than "comparison".

答:
Well, I think your question falls somewhat into the domain of this question: What's the next level of abstraction?

There I've made a similar inquiry (in the comments) regarding Aspect Oriented Programming, i.e. is it a different level of abstraction (other than OOP) or not. The conclusion there was that it's not, it's simply a different approach to using OOP. I think the same goes for SOA. The data and algorithm abstractions needed for something that could be called SOA are pretty much the same as those used for something that can be cathegorized as OOP.
Continuing on this idea, what you'd need to better develop SOA software is libraries and frameworks that deal with the boiler plate code, rather than a new language, and I believe this is the case today, you have such frameworks as Mule ESB and Spring Framekwork.

Here's an interesting discussion of different way to take on SOA, and how Spring helps you with it:

http://forum.springsource.org/showthread.php?25892-SOA-Vs-Spring

Title: Relationship between SOA and OOA


答:
This distinction between functions and procedures can be traced back to Pascal and maybe even further. I would speculate, that that's an attempt to accomodate command-query separation in the language design, where commands would be carried out by procedures and queries are carried out by functions.

I believe the word function was chosen here to emphasize the fact, that a query should actually be a function in the mathematical meaning of the term, i.e. repeating the same call again and again should yield the same result - a quality often termed as referential transparency. This doesn't apply to subroutines in general and Pascal didn't actually tie this quality to the concept of a function, random being the canonical proof of that.

In regards to whether a subroutine returns a value or not, there's not much difference between a subroutine, that returns a value directly, or one that takes a variable by reference and stores its result in that variable.
In some languages, especially dynamic ones, even subroutines that do not explicitly return a value, do so implicitly. For example JavaScript "procedures" return undefined in such cases.

There's many ways to define procedures and functions. For me, the sensible definition is, that functions are referentially transparent procedures. Such functions are often called pure functions. This can be used in an OOP context. You can also speak of commands and queries, or of mutators and accessors. But then again, a core idea of OOP is not to make assumptions about what's going on within the method owner. So at the abstraction level that "OOP is really about" the distinction doesn't exists. There's only methods.


答: The distinction doesn't matter. Your acceptance testing should encompass all of the functionality that is exposed to the end user. You absolutely should test it as if you were the end user, as well as testing edge cases and unusual scenarios that may only affect a handful of end users. </p>

Title: Who are 'users' in testing?


问:
What makes Erlang suitable for cloud applications?
We are starting a new project and implementing on our corporations's instantiation of an openstack cloud (see http://www.openstack.org/). The project is security tooling for our corporation. We currently run many hundreds of dedicated servers for security tools and are moving them to our corporations instantiation of openstack.

Other projects in my company currently use erlang in several distributed server applications, and other Q/A point out erlang is used in several popular cloud services. I am trying to convince others to consider where it might be applicable on our project.

What are erlang's strengths for cloud programming? Where are areas it is particularly appropriate to use erlang?

答:
Erlang is particularly strong in concurrent/parallelized computing. In fact, it was designed originally for that very purpose. It has nothing inherent to do with cloud, except that oftentimes, calculation-heavy applications parallelized and deployed in "cloud" instances to make it easier to grow/shrink capacity on demand.

The rest is just marketing-speak.


问:
Method flags as arguments or as member variables?
I think the title "Method flags as arguments or as member variables?" may be suboptimal, but as I'm missing any better terminology atm., here goes:

I'm currently trying to get my head around the problem of whether flags for a given class (private) method should be passed as function arguments or via member variable and/or whether there is some pattern or name that covers this aspect and/or whether this hints at some other design problems.

By example (language could be C++, Java, C#, doesn't really matter IMHO):

```<code>class Thingamajig {
  private ResultType DoInternalStuff(FlagType calcSelect) {
    ResultType res;
    for (... some loop condition ...) {
      ...
      if (calcSelect == typeA) {
        ...
      } else if (calcSelect == typeX) {
        ...
      } else if ...
    }
    ...
    return res;
  }

  private void InteralStuffInvoker(FlagType calcSelect) {
    ...
    DoInternalStuff(calcSelect);
    ...
  }

  public void DoThisStuff() {
    ... some code ...
    InternalStuffInvoker(typeA);
    ... some more code ...
  }

  public ResultType DoThatStuff() {
    ... some code ...
    ResultType x = DoInternalStuff(typeX);
    ... some more code ... further process x ...
    return x;
  }
}
</code>```

What we see above is that the method InternalStuffInvoker takes an argument that is not used inside this function at all but is only forwarded to the other private method DoInternalStuff. (Where DoInternalStuffwill be used privately at other places in this class, e.g. in the DoThatStuff (public) method.)

An alternative solution would be to add a member variable that carries this information:

```<code>class Thingamajig {
  private ResultType DoInternalStuff() {
    ResultType res;
    for (... some loop condition ...) {
      ...
      if (m_calcSelect == typeA) {
        ...
      } ...
    }
    ...
    return res;
  }

  private void InteralStuffInvoker() {
    ...
    DoInternalStuff();
    ...
  }

  public void DoThisStuff() {
    ... some code ...
    m_calcSelect = typeA;
    InternalStuffInvoker();
    ... some more code ...
  }

  public ResultType DoThatStuff() {
    ... some code ...
    m_calcSelect = typeX;
    ResultType x = DoInternalStuff();
    ... some more code ... further process x ...
    return x;
  }
}
</code>```

Especially for deep call chains where the selector-flag for the inner method is selected outside, using a member variable can make the intermediate functions cleaner, as they don't need to carry a pass-through parameter.

On the other hand, this member variable isn't really representing any object state (as it's neither set nor available outside), but is really a hidden additional argument for the "inner" private method.

What are the pros and cons of each approach?

答:
On the other hand, this member variable isn't really representing any object state (as it's neither set nor available outside), but is really a hidden additional argument for the "inner" private method.

That reinforces my gut feeling upon reading your question: try to keep this data as local as possible, i.e. don't add it to the object state. This reduces the state space of your class, making your code simpler to understand, test and maintain. Not to mention that avoiding shared state makes your class more threadsafe too - this may or may not be a concern to you right now, but it may make a huge difference in the future.

Of course, if you need to pass around such flags excessively, it may become a nuisance. In this case, you may consider

creating parameter objects to group related parameters together into a single object, and/or

encapsulating this state and the associated logic into a separate family of strategies. The viability of this depends on the language: in Java, you need to define a distinct interface and a (possibly anonymous) implementation class per each strategy, whereas in C++ or C# you may use function pointers, delegates or lambdas, which simplifies the code considerably.


答:
I would definitely vote for the "argument" option - my reasons:

Synchronization - what if the method is called from multiple threads at the same time? By passing the flags as an argument, you won't have to sychronize access to these flags.

Testability - Let's imagine you are writing an unit test for you class. How you will test the internal state of the member? What if your code throws an exception and the member will end in an unexpected state?

Separation of concerns - By adding the flags to your method arguments, it is clear that no other method is supposed to use it. You won't use it by mistake in some other method.

Body:
I think the title "Method flags as arguments or as member variables?" may be suboptimal, but as I'm missing any better terminology atm., here goes:

I'm currently trying to get my head around the problem of whether flags for a given class (private) method should be passed as function arguments or via member variable and/or whether there is some pattern or name that covers this aspect and/or whether this hints at some other design problems.

By example (language could be C++, Java, C#, doesn't really matter IMHO):

```<code>class Thingamajig {
  private ResultType DoInternalStuff(FlagType calcSelect) {
    ResultType res;
    for (... some loop condition ...) {
      ...
      if (calcSelect == typeA) {
        ...
      } else if (calcSelect == typeX) {
        ...
      } else if ...
    }
    ...
    return res;
  }

  private void InteralStuffInvoker(FlagType calcSelect) {
    ...
    DoInternalStuff(calcSelect);
    ...
  }

  public void DoThisStuff() {
    ... some code ...
    InternalStuffInvoker(typeA);
    ... some more code ...
  }

  public ResultType DoThatStuff() {
    ... some code ...
    ResultType x = DoInternalStuff(typeX);
    ... some more code ... further process x ...
    return x;
  }
}
</code>```

What we see above is that the method InternalStuffInvoker takes an argument that is not used inside this function at all but is only forwarded to the other private method DoInternalStuff. (Where DoInternalStuffwill be used privately at other places in this class, e.g. in the DoThatStuff (public) method.)

An alternative solution would be to add a member variable that carries this information:

```<code>class Thingamajig {
  private ResultType DoInternalStuff() {
    ResultType res;
    for (... some loop condition ...) {
      ...
      if (m_calcSelect == typeA) {
        ...
      } ...
    }
    ...
    return res;
  }

  private void InteralStuffInvoker() {
    ...
    DoInternalStuff();
    ...
  }

  public void DoThisStuff() {
    ... some code ...
    m_calcSelect = typeA;
    InternalStuffInvoker();
    ... some more code ...
  }

  public ResultType DoThatStuff() {
    ... some code ...
    m_calcSelect = typeX;
    ResultType x = DoInternalStuff();
    ... some more code ... further process x ...
    return x;
  }
}
</code>```

Especially for deep call chains where the selector-flag for the inner method is selected outside, using a member variable can make the intermediate functions cleaner, as they don't need to carry a pass-through parameter.

On the other hand, this member variable isn't really representing any object state (as it's neither set nor available outside), but is really a hidden additional argument for the "inner" private method.

What are the pros and cons of each approach?


答:
The first alternative seems OK to me. A function is called with a parameter, and it does something that depends on that parameter. Even if you just forward the parameter to another function, you do it expecting that the result will somehow depends on the parameter.

The second alternative feels like using a global variable, just within the class scope instead of application scope. But it's the same problem... you must read carefully the whole class code to determine who and when is reading and writing those values.

Therefore the first alternative wins.

If you would use too many parameters (read: two or more) in the first alternative, which all just get passed together to the next function, you can consider putting them into one object (make it an inner class, if it's not relevant for the rest of the application) and using this object as a parameter.

Title: Method flags as arguments or as member variables?


答:
OOP is a programming paradigm. SOA is a system architecture concept.SOA can be implemented using OO code (or any other type of coding, it does not matter). OOP can be part of a SOA architecture or can be used outside of that architecture. OO and SOA are two different concepts (level wise). We could for example compare SOA based architecture to non-SOA based architecture or compare OOP to Procedural Programming used in languages such as COBOL II. However, comparing  SOA to OO would not be valid.

SOA needs OOPS working underneath it.

I don't agree. OOP is optional.

SOA is a "strategy" to make the entire application/service distributed and reliable

True (purists may argue about exactness of the wording though...).

Edit:

I have added this section in response to first comment below:

Think of a Service as a black box. The way the service is built internally is not your concern (this is generally a good thing). You mainly focus on consuming the service via its API. Whether you do this via classes in an OO program or even via URL request on the browser as in this example: http://ichart.finance.yahoo.com/table.csv?s=IBM&a=1&b=1&c=2010&d=1&e=1&f=2012&g=d&ignore=.csv, if you click this link Yahoo Finance will get you a CSV file of stock information. No class on the client was required. The magic is hidden inside the service.

Frameworks such as Microsoft WCF provide means of communicating with services via different methods and handles lots of the details required to build a rich service environment. You may want to look for more details on WCF.

Title: Relationship between SOA and OOA

Body:
Thomas Erl defines SOA as follows in his site:

Service-oriented computing represents a new generation distributed
computing platform. As such, it encompasses many things, including its
own design paradigm and design principles, design pattern catalogs,
pattern languages, a distinct architectural model, and related
concepts, technologies, and frameworks.

This definitely sounds like a whole new category which is parallel to object orientation. Almost one in which you would expect an entirely new language to exist for. Like procedural C and object oriented C#.

Here is my understanding:
In real life, we don't have entirely new language for SOA. And most application which have SOA architecture have an object oriented design underneath it. SOA is a "strategy" to make the entire application/service distributed and reliable. SOA needs OOPS working underneath it.

Is this correct? Where does SOA (if at all it does) fit in with object oriented programming practices?

Edit: I have learnt through answers that OOA and SOA work with each other and cannot be compared (in a "which is better" way). I have changed the title to "Relationship between SOA and OOA" rather than "comparison".


答:
Strange OOP:

len(s) through __len__(self) and other "special methods"

extra special methods which could be derived from other special methods (__add__ and __iadd__ for + and +=)

self as first method parameter

you can forget to call base class constructor

no access modifiers (private, protected ...)

no constant definitions

no immutability for custom types

GIL

poor performance which leads to a mix of Python and C and troubles with builds (looking for C libs, platform dependencies ...)

bad documentation, especially in third party libs

incompatibility between Python 2.x and 3.x

poor code analysis tools (compared to what is offered for statically typed languages such as Java or C#)

Title: What are the drawbacks of Python?

Body:
Python seems all the rage these days, and not undeservingly - for it is truly a language with which one almost enjoys being given a new problem to solve. But, as a wise man once said (calling him a wise man only because I've no idea as to who actually said it; not sure whether he was that wise at all), to really know a language one does not only know its syntax, design, etc., advantages but also its drawbacks. No language is perfect, some are just better than others.

So, what would be in your opinion, objective drawbacks of Python.

Note: I'm not asking for a language comparison here (i.e. C# is better than Python because ... yadda yadda yadda) - more of an objective (to some level) opinion which language features are badly designed, whether, what are maybe some you're missing in it and so on. If must use another language as a comparison, but only to illustrate a point which would be hard to elaborate on otherwise (i.e. for ease of understanding)


问:
What's the difference between overloading a method and overriding it in Java?
What's the difference between overloading a method and overriding it in Java?

Is there a difference in method signature, access specifier, return type, etc.?

答:
To overload a method with a new method, the new method should have a different signature. I.e. two overloaded methods have the same name, but different parameters. Here's an example of two overloaded methods:

```<code>boolean isOdd(int number) { ... };
boolean isOdd(float number) { ... };
</code>```

Based on the parameter types, the corresponding method will be called. Note that changing the return type is not enough (though you can do this additionally).

When a method is overridden, then the new method has the same signature and replaces the overridden method in some cases. Here's an example of an overridden method:

```<code>public class A
{
     public void someMethod() { ... }
}

public class B extends A
{
     public void someMethod() { ... }
}
</code>```

The choice is made based on the object type. For example,

```<code>A someA = new B();
someA.someMethod();
</code>```

will call the someMethod of B. You can (and should) add the @Override annotation:

```<code>public class B extends A
{
     @Override
     public void someMethod() { ... }
}
</code>```

Now, if you accidentally change the parameters in B, the compiler will inform you, that you are not overriding someMethod() but overloading it.

Body:
To overload a method with a new method, the new method should have a different signature. I.e. two overloaded methods have the same name, but different parameters. Here's an example of two overloaded methods:

boolean isOdd(int number) { ... };
boolean isOdd(float number) { ... };

Based on the parameter types, the corresponding method will be called. Note that changing the return type is not enough (though you can do this additionally).

When a method is overridden, then the new method has the same signature and replaces the overridden method in some cases. Here's an example of an overridden method:

public class A
{
     public void someMethod() { ... }
}

public class B extends A
{
     public void someMethod() { ... }
}

The choice is made based on the object type. For example,

A someA = new B();
someA.someMethod();

will call the someMethod of B. You can (and should) add the @Override annotation:

public class B extends A
{
     @Override
     public void someMethod() { ... }
}

Now, if you accidentally change the parameters in B, the compiler will inform you, that you are not overriding someMethod() but overloading it.


问:
null pointers vs. Null Object Pattern
Attribution: This grew out of a related P.SE question

My background is in C / C++, but I have worked a fair amount in Java and am currently coding C#.  Because of my C background, checking passed and returned pointers is second-hand, but I acknowledge it biases my point of view.

I recently saw mention of the Null Object Pattern where the idea is that an object is always returned.  Normal case returns the expected, populated object and the error case returns empty object instead of a null pointer.  The premise being that the calling function will always have some sort of object to access and therefore avoid null access memory violations.

So what are the pros / cons of a null check versus using the Null Object Pattern?

I can see cleaner calling code with the NOP, but I can also see where it would create hidden failures that don't otherwise get raised.  I would rather have my application fail hard (aka an exception) while I'm developing it than have a silent mistake escape into the wild.

Can't the Null Object Pattern have similar problems as not performing a null check?

Many of the objects I have worked with hold objects or containers of their own.  It seems like I would have to have a special case to guarantee all of the main object's containers had empty objects of their own.  Seems like this could get ugly with multiple layers of nesting.

答:
I'm not a good source of objective information, but subjectively:

I don't want my system to die, ever; to me it's a sign of badly designed or incomplete system; complete system should handle all possible cases and never get into unexpected state; to achieve this I need to be explicit in modeling all the flows and situations; using nulls is not anyhow explicit and groups a lot of different cases under one umrella; I prefer NonExistingUser object to null, I prefer NaN to null, ... such approach allows me to be explicit about those situations and their handling in as much details as I want, while null leaves me with only null option; in such environment like Java any object can be null so why would you prefer to hide in that generic pool of cases also your specific case?

null implementations have drastically different behavior than object and are mostly glued to the set of all objects (why?why?why?); to me such drastical difference seems like a result of design of nulls to be indication of error in which case system most likely will die (I'm supprised so many people actually prefer their system to die in the above posts) unless explicitly handled; to me that's a flawed approach in it's root - it allows the system to die by default unless you explicitly have taken care about it, that's not very safe right? but in any case it makes impossible to write a code that treats the value null and object in same manner - only few basic built in operators (assign, equal, param, etc.) will work, all other code will just fail and you need two completely different paths;

using Null Object scales better - you can put as much information and structure into it as you want; NonExistingUser is a very good example - it can contain an email of the user you tried to recieve and suggest to create new user based on that information, while with the null solution I would need to think how to keep the email that people attempted to access close to the null result handling;

In environment like Java or C# it won't give you the main benefit of explicitness - safety of solution being complete, cause you can still recieve null in the place of any object in the system and Java has no means (except custom annotations for Beans, etc.) to guard you from that except explicit ifs. But in the system free of null implementaitons, approaching problem solution it in such a way (with objects representing exceptional cases) gives all the benefits mentioned. So try to read about something other than mainstream languages, and you'll find yourself changing your ways of coding.

In general Null/Error objects/return types is considered to be very solid error handling strategy and quite mathematically sound, while exceptions handling strategy of Java or C goes like only one step above "die ASAP" strategy - so basically leave all the burden of unstability and unpredictability of the system on developer or maintainer.

There are also monads that can be considered superior to this strategy (also superior in complexity of understanding at first), but those are more about the cases when you need to model external aspects of type, while Null Object models internal aspects. So NonExistingUser is probably better modeled as monad maybe_existing.

And lastly I don't think that there is any connection between Null Object pattern and silently handling error situations. It should be other way around - it should force you to model each and every error case explicitly and handle it accordingly. Now of course you might decide to be sloppy (for what ever reason) and skip handling the error case explicitly but handle it generically - well that was your explicit choice.

Title: null pointers vs. Null Object Pattern


答:
Other than the fact that Erlang was specifically developed to be run in concurrent/parallelized/distributed situations, the two main techniques that it employs making this possible are:

No side effects

This means, when you give a function a piece of data to execute against, it will not except in very strict cases affect anything else in the system/running process. This means that if you execute a function 300 times all at once concurrently, none of those 300 executions of the function will effect any of the others.

The implementation technique for ensuring no side effects is called "immutability" which roughly means, may not be mutated(changed). This means that as soon as you create a variable, the value of that variable may not be modified. Erlang implements this behavior with "single assignment" so after you assign a value to a variable, you may not assign a value to it again.

```<code>X = 1.
X = 2. // This is not a valid operation
</code>```

This ensures no code may accidentally change the value of X causing a race condition, therefore it is inherently thread-safe and concurrent use becomes trivial. This is a very uncommon behavior among software languages and the biggest way Erlang manages to be so well suited for concurrent execution.

The actor model

This is a particular way of modelling that has shown to make the implementation and management of concurrent processing very simple for developers. Straight from Wikipedia:

The Actor model adopts the philosophy that everything is an actor.
This is similar to the everything is an object philosophy used by some
object-oriented programming languages, but differs in that
object-oriented software is typically executed sequentially, while the
Actor model is inherently concurrent. An actor is a computational
entity that, in response to a message it receives, can concurrently:
send a finite number of messages to other actors; create a finite
number of new actors; designate the behavior to be used for the next
message it receives. There is no assumed sequence to the above actions
and they could be carried out in parallel. Decoupling the sender from
communications sent was a fundamental advance of the Actor model
enabling asynchronous communication and control structures as patterns
of passing messages.

Title: What makes Erlang suitable for cloud applications?

Body:
We are starting a new project and implementing on our corporations's instantiation of an openstack cloud (see http://www.openstack.org/). The project is security tooling for our corporation. We currently run many hundreds of dedicated servers for security tools and are moving them to our corporations instantiation of openstack.

Other projects in my company currently use erlang in several distributed server applications, and other Q/A point out erlang is used in several popular cloud services. I am trying to convince others to consider where it might be applicable on our project.

What are erlang's strengths for cloud programming? Where are areas it is particularly appropriate to use erlang?

Body:
Other than the fact that Erlang was specifically developed to be run in concurrent/parallelized/distributed situations, the two main techniques that it employs making this possible are:

No side effects

This means, when you give a function a piece of data to execute against, it will not except in very strict cases affect anything else in the system/running process. This means that if you execute a function 300 times all at once concurrently, none of those 300 executions of the function will effect any of the others.

The implementation technique for ensuring no side effects is called "immutability" which roughly means, may not be mutated(changed). This means that as soon as you create a variable, the value of that variable may not be modified. Erlang implements this behavior with "single assignment" so after you assign a value to a variable, you may not assign a value to it again.

X = 1.
X = 2. // This is not a valid operation

This ensures no code may accidentally change the value of X causing a race condition, therefore it is inherently thread-safe and concurrent use becomes trivial. This is a very uncommon behavior among software languages and the biggest way Erlang manages to be so well suited for concurrent execution.

The actor model

This is a particular way of modelling that has shown to make the implementation and management of concurrent processing very simple for developers. Straight from Wikipedia:

The Actor model adopts the philosophy that everything is an actor.
This is similar to the everything is an object philosophy used by some
object-oriented programming languages, but differs in that
object-oriented software is typically executed sequentially, while the
Actor model is inherently concurrent. An actor is a computational
entity that, in response to a message it receives, can concurrently:
send a finite number of messages to other actors; create a finite
number of new actors; designate the behavior to be used for the next
message it receives. There is no assumed sequence to the above actions
and they could be carried out in parallel. Decoupling the sender from
communications sent was a fundamental advance of the Actor model
enabling asynchronous communication and control structures as patterns
of passing messages.

ContentLicense: CC BY-SA 4.0


答:
I think it's interesting to note that the viability of a Null Object seems to be a little different depending on whether or not your language is statically typed. Ruby is a language that implements an object for Null (or Nil in the language's terminology).

Instead of getting back a pointer to uninitialized memory, the language will return the object Nil. This is facilitated by the fact that the language is dynamically typed. A function isn't guaranteed to always return an int. It can return Nil if that's what it needs to do. It becomes more convoluted and difficult to do this in a statically typed language, because you naturally expect null to be applicable to any object that can be called by reference. You'd have to start implementing null versions of any object that could be null (or go the Scala/Haskell route and have some kind of "Maybe" wrapper).

MrLister brought up the fact that in C++ you're not guaranteed to have an initialize reference/pointer when you first create it. By having a dedicated null object instead of a raw null pointer, you can get some nice additional features. Ruby's Nil includes a to_s (toString) function that results in blank text. This is great if you don't mind getting a null return on a string, and want to skip reporting it without crashing. Open Classes also allow you to manually override the output of Nil if need be.

Granted this can all be taken with a grain of salt. I believe that in a dynamic language, the null object can be a great convenience when used correctly. Unfortunately, getting the most out of it might require you to edit it's base functionality, which could make your program hard to understand and maintain for people used to working with its more standard forms.

Title: null pointers vs. Null Object Pattern

Body:
Attribution: This grew out of a related P.SE question

My background is in C / C++, but I have worked a fair amount in Java and am currently coding C#.  Because of my C background, checking passed and returned pointers is second-hand, but I acknowledge it biases my point of view.

I recently saw mention of the Null Object Pattern where the idea is that an object is always returned.  Normal case returns the expected, populated object and the error case returns empty object instead of a null pointer.  The premise being that the calling function will always have some sort of object to access and therefore avoid null access memory violations.

So what are the pros / cons of a null check versus using the Null Object Pattern?

I can see cleaner calling code with the NOP, but I can also see where it would create hidden failures that don't otherwise get raised.  I would rather have my application fail hard (aka an exception) while I'm developing it than have a silent mistake escape into the wild.

Can't the Null Object Pattern have similar problems as not performing a null check?

Many of the objects I have worked with hold objects or containers of their own.  It seems like I would have to have a special case to guarantee all of the main object's containers had empty objects of their own.  Seems like this could get ugly with multiple layers of nesting.


问:
Are there any conceptual drawbacks to building a web app with C++ and MySQL?
I've inherited a pretty interesting project where there is a good opportunity to take an existing piece of software and turn it into a SaaS web app. As the project is inherited, the code base/ framework is already defined as C++ and MySQL. The app itself is compiled and run as an EXE on Windows Server. The UI is web based and the app works as a kind of server. From what I do know of modern web apps, this is perhaps an unusual choice. These days, most people seem to opt for a PHP framework or Ruby on Rails. Certainly that is the impression I get from reading blogs on the subject. So, I'm very interested to know if a C++ EXE backed by MySQL is a solid foundation for a web app, or whether we should be looking to build in another way?</p>

答:
As others have said, conceptually, C++ is a fine environment for a web server development. There are however, several considerations as you make that decision.

The popularity of scripting languages for web server design is turn around time. Simple changes can be made easily with the demonstration of results nearly immediate. You will find that any good web server design will offer similar capabilities. Indeed, C++ is an excellent environment for achieving that goal.

The key to building a good web server application system is a separation of UI from code. A goal in building a web application environment is to avoid "Your UI is in my code and your code is in my UI."

I would like carefully at systems like cppcms. I would expect that it offers something similar.

You don't need a scripting language to offer flexibility and performance.


问:
Is this the correct way to implement .NET MVC website structure?
I have recently seen a .NET MVC solution in which the markup in the .aspx views which appear to have a Controller as their model i.e the controller seems to be providing the data for the view, and the .ascx user controls they contain use a separate model. I'm new to MVC and I wanted to find out about a few things I'm not clear on.

An example of how the code is implemented:

UserDetails.aspx view has markup that shows it's using the UserDetailsController.cs as the model. It contains RenderPartial("User_Details.ascx", UserDetailsModel) and passes it the UserDetailsModel.

Is this the standard/correct way of implementing MVC? Or just one way to implement it?

I also noticed that the classes used as Models appear to be Service classes that have [DataMember] and [DataContract] attributes on the class name and properties - what is the advantage of this implementation?

答:
Based upon the limited description so far, the best answer I can give is "maybe."

Here's my partial take on MVC, which generally aligns with others' takes.  But there's always bones of contention to be had.  I would recommend Martin Fowler's articles as a good starting point with MVC and the other MVx variants.

The View should not be aware of the Model; it only knows what the Controller feeds it.

The Controller is more than welcome to directly pass a data structure from the Model to the View.  But the Controller is on the hook to maintain that contract with the View if the Model should change.

In other words, the Controller may retrieve a List of users from the Model and then pass that List directly to the View.  In this case, the structures magically aligned and all three layers are able to utilize the same (or similar) structure.

Should the View need additional details later on, then the Controller will be responsible for accessing the Model as necessary in order to provide those additional details back to the View.


问:
"Do you have any questions for us?" In an interview
You know the prospective company fairly well but are asked "Do you have any questions for us?".  To show interest, what are some of your favorite questions to reply?</p>

答:
There's softball stuff I like to ask, eg  "Can you tell me about your day to day work", since that's what matters to me.

However, questions that indicate and understanding of the business, its current issues, or issues the interviewer cares about work very well.


答:
Concepts you ask about are covered in Java tutorials.

Explanation for overriding is given as follows:

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.

When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error. For more information on @Override, see Annotations...

Overloading is explained in tutorial as follows:

The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance".

Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each method—for example, drawString, drawInteger, drawFloat, and so on. In the Java programming language, you can use the same name for all the drawing methods but pass a different argument list to each method. Thus, the data drawing class might declare four methods named draw, each of which has a different parameter list...

Overloaded methods are differentiated by the number and the type of the arguments passed into the method...

You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.

Note: Overloaded methods should be used sparingly, as they can make code much less readable.

Above explanation for overloading mentions qualifications discussed in the lesson titled "Interfaces and Inheritance":

In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods—they are new methods, unique to the subclass.

Body:
What's the difference between overloading a method and overriding it in Java?

Is there a difference in method signature, access specifier, return type, etc.?


答:
Overloading, methods have the same name but different parameters.

Overriding, the implementation given in base class is replaced with that in sub class.

Title: What's the difference between overloading a method and overriding it in Java?


问:
How come verification does not include actual testing?
Having read a lot about this topic --- such as on this Software Testing Fundamentals site on verification and validation and Software Testing and Quality Assurance: Theory and Practice by Naik and Tripathy --- I still do not get it. Verification should prove that you are building the product right, while validation proves that you built the right product. But only static techniques (code reviews, requirements checks...) are mentioned as being verification methods. How can you say if its implemented correctly if you do not test it? It is said that verification ensures that the product meet specified requirements. Again, if the function is specified to work somehow, only by testing I can say that it does.

Could anyone explain this to me please?

答:
Indeed: verification proves that you are building the product right, while validation you build the right product.

Therefore

verification is proving of the process... that you have followed the required standards and procedures, usually checked by static analysis and code review.

validation is proving of the resultant product... that the code does what is required, usually checked by dynamic analysis and testing, to show that specified inputs result in specified outputs

I don't usually cite Wikipedia, but in this case, it's helpful...

A more detailed explaination of the two processes can be found in ISO 12207 Software Life Cycle Processes (one of the other answers posts a link to an uncontrolled copy):

7.2.4.3.2 Verification Tasks

Requirements Verification

Design Verification

Code Verification

Integration Verification

Documentation Verification

7.2.5.3.2 Validation Tasks

Prepare Test Requirements, Cases and Specifications

Conduct the Tests

Now, the opening question asked why verification does not include testing. And despite some of the other answers, by P.SE members of high reputation, I put it to you that that is not the point of the verification activity, but of the validation activity.

Some answers suggest that you have to test to verify code or integration. No - that activity is to prove the modularity and the interfaces, etc, not the execution.

Utimately, what this discussion shows is that there is a lot of confusion as to what is verification and what is validation, and this is not helped by the boundary being a grey area, and defined slightly differently in different standards.

What is important is that both parts of V&V should be covered, and as long as that is the case then semantically, it doesn't really matter whether it's V or V... just V and V.


答:
I think there is a distinction to be made, however it is not necessarily between "Compiled" and "Managed". These are not opposites; a language can be compiled and not managed, or interpreted (not compiled) and managed, or both, or even neither.

A "compiled" language is simply one in which there is a step that transforms the source code written by the developer into some more regular "bytecode" which is what is executed by the machine. The "machine" can be the actual processor, or a "virtual machine" that performs additional operations on the bytecodes to translate them to "native" machine instructions. The antonym for a "compiled" language is an "interpreted" language, in which the source code is transformed into bytecode instructions at runtime, line by line as they are executed, without a compilation step. A hybrid between them is "jitting", from "JIT" (Just In Time), which is usually interpretation as a one-time step by the executing machine; a line of code (or function or source file) is interpreted when first run, but the native instructions produced are kept in memory so the runtime doesn't have to re-do the interpretation again on subsequent executions of that code.

A "managed" language is a language designed to produce programs that are consumed within a specific runtime environment, which almost always includes a bytecode interpreter; a "virtual machine" that takes the program's code and performs some additional machine or environment-specific transformation. The environment may also include memory management, such as a "garbage collector" and other "security" features meant to keep the program operating within its "sandbox" of space and tools, however such features are not the sole domain of "managed" runtimes. Virtually all interpreted languages could be considered managed, because they require the interpreter to be running underneath the lines of "user" code being executed. In addition, JVM and .NET languages (Java, Scala, C#, VB, F#, IronWhatever) are compiled into an intermediate language or IL, which is superficially similar in form and function to a binary assembly language, but doesn't adhere 100% to any "native" instruction set. These instructions are executed by the JVM, or by .NET's CLR, which effectively translates them to native binary instructions specific to the CPU architecture and/or OS of the machine.

So, languages can generally be described as "compiled" or "interpreted", and as "unmanaged" (or "native") and "managed". There are languages that can be described as any combination of these except possible "interpreted native" (which would only be true for hand-written hexadecimal opcodes, where what is written by the developer is what is executed); if you consider the interpretation layer as a "runtime" (which is easy to argue for and hard to argue against), then all interpreted languages are "managed".

If you want to get technical, almost all programs targeting a multitasking OS nowadays are "managed"; the OS will create a "virtual machine" for each program that is running, in which the program thinks (or at least doesn't have to know otherwise) that it is the only thing running. The code may make calls within itself and to other referenced libraries as if that program was the only thing loaded in memory; similarly, calls to allocate RAM and other higher memory to store and manipulate data and control devices are coded as if the entire memory architecture was available. The VM (and the OS behind it) then translates various memory pointers to the actual location of the program, its data, and hooks to device drivers etc. This is most often done by applying a memory offset (each VM gets a block of 2GB or whatever of memory, starting at address X which the program can treat as if that X was address 0) and as such is very cheap to do, but there are other things the OS kernel is responsible for, such as process scheduling and inter-process communication, which are trickier to manage. However, this basic pattern is generally not considered "managed", as the program doesn't have to know that it's being run by a virtual machine and is often still responsible for keeping its allocated memory "clean". A program that was designed to be run on the MS-DOS command line can be run on newer Windows OSes that don't even have the MS-DOS environment underneath them anymore; the program is instead given a "virtual console" environment, and provided it doesn't try to leave this "sandbox" by trying to directly access protected areas of memory, it will run quite happily.


答:
Overloading a method is typically defined as "providing multiple available methods with the same name, differing by the number and type of inputs and outputs". The concept is usually that you want to be able to perform the same basic operation given varying sets of inputs: you can, for instance, "add" any two values of numeric type, however it is usually important to know what the exact type of the value is so that you can take advantage of or plan for specific behaviors of that type. As such, you would define a method for each combination of numeric types (and or collections) you wish to support. All these methods have the same name, but different "signatures"; at compile-time, the compiler will match a call to a particular method name with a given combination of inputs to a specific pointer in the application memory used to store code.

Overriding a method is typically defined as "providing a different implementation in a derived class of a method with a particular signature defined in the base class". There are many reasons to override a method; virtually all of them have in common the fact that the derived class has additional knowledge of what must be done, which cannot be known by the base class. There are two flavors of overriding in most OO languages; overriding can replace the base class method, or it can extend the base class method. The difference is usually that a derived class that is extending a base class implementation will call the base class's overridden version of the method at some point during the execution of the overriding method. This allows overriding classes to "re-use" common areas of the operation which are contained in the base class.


答:
As this question created some controversy, let me start off this answer with my background: Apart from being exposed to V&V in daily project work, I worked for several years in the software engineering department of my alma mater and am a lecturer for software engineering. While this does not guarantee that anything I say is correct, I hope it at least gives me the benefit of the doubt that there might be some truth in this answer.

Let me assure you, that you are not as confused as you may believe you are. What you have stated in your question is as much true as it is misleading. Let me first point out, what you have correctly stated:

Verification = build the product right vs validation = build the right product

Static techniques are part of verification - mainly because they take your program and some formal input derived from the requirements and evaluate them against each other.

Verification ensures correct implementation of the requirements (i.e. that you have built it the right way)

Now let me clean up the confusion about testing. First, as many comments have stated before, dynamic testing of code via automated tests (unit, integration, ...) is indeed part of verification. What causes most of the confusion, however, is that people in validation will talk about testing as well, yet mean something different: in validation, testing usually involves a person using the application for its intended purpose. In the optimal case, this is the customer him-/herself.

However, the "errors" [1] found by testing in verification and in validation differ fundamentally:

verification testing errors: these are errors that violate your requirements in one way or another.

validation testing errors: these are errors with the very product you have built, not its functionality, hence, they reveal errors within the requirements.

For most people, it helps to look at concrete examples of different V&V cases. The following are extreme examples of errors:

You have a low-level requirement that states "f(x) should return x+1" and your implementation of "f" always returns the constant 2. You may find this error by several different verification approaches, but your customer probably won't find it during validation, because you are building an e-shopping site and he neither knows nor cares about "f".

You have a requirement that states "The system should be able to handle 1000 requests per second at a CPU load maximum of 80%". Again, validation will have a hard time, just as much as most static techniques. In fact, the simplest way to verify this is to dynamically test your application by hammering it with requests and monitoring your CPU load during that time.

Consider the above requirement for "f" once more, this time with a "correct" implementation. All your reviews, static analysis and dynamic tests will report a success, but then your customer tests your software and tells you that he misses the shopping cart icon on the webpage. No amount of verification will be able to find this error, as you have made it during the requirements phase.

As you can see, "testing" - if not defined more precisely - is part of both verification and validation, and in fact, "testing" should be performed for both.

[1] "error" is used colloquially here, so as to avoid the distinction between error, failure, mistake, fault, ...

Title: How come verification does not include actual testing?

Body:
Having read a lot about this topic --- such as on this Software Testing Fundamentals site on verification and validation and Software Testing and Quality Assurance: Theory and Practice by Naik and Tripathy --- I still do not get it. Verification should prove that you are building the product right, while validation proves that you built the right product. But only static techniques (code reviews, requirements checks...) are mentioned as being verification methods. How can you say if its implemented correctly if you do not test it? It is said that verification ensures that the product meet specified requirements. Again, if the function is specified to work somehow, only by testing I can say that it does.

Could anyone explain this to me please?


答:
My standbys:

What languages/frameworks to you usually work with?

What development tools- IDEs, Bug Trackers, Version Control, etc do you use?

What's your development methodology like (Agile, Waterfall, Scrum, Crystal, etc)?

Do you have dedicated QA personel?  Even if so, do developers do some amount of their own unit testing?

Also a good list to consider is the Joel Test:

Do you use source control?

Can you make a build in one step?

Do you make daily builds?

Do you have a bug database?

Do you fix bugs before writing new code?

Do you have an up-to-date schedule?

Do you have a spec?

Do programmers have quiet working conditions?

Do you use the best tools money can buy?

Do you have testers?

Do new candidates write code during their interview?

Do you do hallway usability testing?

Some things to help you decide if you really want the job:

What's the best part of your job?  And the worst or most frustrating part?

Why do people tend to leave the company?

If I took this job, what would you most hope I could take care of for you? (Especially to your would-be manager, but also to peers, other managers; it's curiosity not sycophancy.)

What are the goals for this project over the next year or two?  What changes would you like to see in the way the project runs?

How do the short and longer-term project goals get set and how is work distributed?

Title: "Do you have any questions for us?" In an interview

Body: You know the prospective company fairly well but are asked "Do you have any questions for us?".  To show interest, what are some of your favorite questions to reply?</p>


问:
Entity Framework with large systems - how to divide models?
I'm working with a SQL Server database with 1000+ tables, another few hundred views, and several thousand stored procedures.  We are looking to start using Entity Framework for our newer projects, and we are working on our strategy for doing so.  The thing I'm hung up on is how best to split the tables into different models (EDMX or DbContext if we go code first).  I can think of a few strategies right off the bat:

Split by schema

We have our tables split across probably a dozen schemas.  We could do one model per schema.  This isn't perfect, though, because dbo still ends up being very large, with 500+ tables / views.  Another problem is that certain units of work will end up having to do transactions that span multiple models, which adds to complexity, although I assume EF makes this fairly straightforward.

Split by intent

Instead of worrying about schemas, split the models by intent.  So we'll have different models for each application, or project, or module, or screen, depending on how granular we want to get.  The problem I see with this is that there are certain tables that inevitably have to be used in every case, such as User or AuditHistory.  Do we add those to every model (violates DRY I think), or are those in a separate model that is used by every project?

Don't split at all - one giant model

This is obviously simple from a development perspective but from my research and my intuition this seems like it could perform terribly, both at design time, compile time, and possibly run time.

What is the best practice for using EF against such a large database?  Specifically what strategies do people use in designing models against this volume of DB objects?  Are there options that I'm not thinking of that work better than what I have above?

Also, is this a problem in other ORMs such as NHibernate?  If so have they come up with any better solutions than EF?

答:
I would say you can't decide this kind of question from a technical perspective. I would recommend that you build your architecture based on your use cases (user stories, etc.). First find your business objects. An entity object is not per default a business object. Typical you will have a business object in front of the entity objects. Then you can incrementally decide what you really need, based on the user requirements.

"A good architect maximizes the number of decisions not made." Robert C. Martin

http://cleancoder.posterous.com/architecture-deference


答:
I want to say "neither".

First off, consider that you already know what you're going to be doing when you're calling DoInternalStuff.  The flag says as much.  So now, instead of just going ahead and doing it, you're farting around calling a function that now has to decide what to do.

If you want to tell the function what to do, then tell it what to do.  You can pass an actual function you want to run for each iteration as a C# delegate (or a C++ function object, or a Java runnable or the like).

In C#:

```<code>class Thingamajig {
  private delegate WhateverType Behavior(ArgsType args);

  private ResultType DoInternalStuff(Behavior behavior) {
    ResultType res;
    for (... some loop condition ...) {
      ...
      var subResult = behavior(someArgs);
      ...
    }
    ...
    return res;
  }

  private void InteralStuffInvoker(Behavior behavior) {
    ...
    DoInternalStuff(behavior);
    ...
  }

  public void DoThisStuff() {
    ... some code ...
    InternalStuffInvoker(doThisStuffPerIteration);
    ... some more code ...
  }

  public ResultType DoThatStuff() {
    ... some code ...
    ResultType x = DoInternalStuff(doThatStuffPerIteration);
    ... some more code ... further process x ...
    return x;
  }
}
</code>```

You still end up with the argument passing all over the place, but you get rid of most of the if/else crap in DoInternalStuff.  You could also store the delegate as a field if you wanted to.

As for whether to pass the todo-thingie around or store it...if you have to choose one, then pass it around.  Storing it is likely to bite you in the ass later, as you've pretty much neglected thread safety.  Consider that if you intend to do anything with threads, now you have to lock for the entire duration of the loop, or someone can switch todo's right out from under you.  Whereas if you pass it, it's less likely to get trashed...and if you still need to lock or something, you can do it for part of one iteration instead of the whole loop.

Frankly, it's good that it's annoying.  There's probably a much simpler way to do what you want to do, which i couldn't really advise you on since the code is obviously not the real thing.  The best answer varies per case.

Body:
I want to say "neither".

First off, consider that you already know what you're going to be doing when you're calling DoInternalStuff.  The flag says as much.  So now, instead of just going ahead and doing it, you're farting around calling a function that now has to decide what to do.

If you want to tell the function what to do, then tell it what to do.  You can pass an actual function you want to run for each iteration as a C# delegate (or a C++ function object, or a Java runnable or the like).

In C#:

class Thingamajig {
  private delegate WhateverType Behavior(ArgsType args);

  private ResultType DoInternalStuff(Behavior behavior) {
    ResultType res;
    for (... some loop condition ...) {
      ...
      var subResult = behavior(someArgs);
      ...
    }
    ...
    return res;
  }

  private void InteralStuffInvoker(Behavior behavior) {
    ...
    DoInternalStuff(behavior);
    ...
  }

  public void DoThisStuff() {
    ... some code ...
    InternalStuffInvoker(doThisStuffPerIteration);
    ... some more code ...
  }

  public ResultType DoThatStuff() {
    ... some code ...
    ResultType x = DoInternalStuff(doThatStuffPerIteration);
    ... some more code ... further process x ...
    return x;
  }
}

You still end up with the argument passing all over the place, but you get rid of most of the if/else crap in DoInternalStuff.  You could also store the delegate as a field if you wanted to.

As for whether to pass the todo-thingie around or store it...if you have to choose one, then pass it around.  Storing it is likely to bite you in the ass later, as you've pretty much neglected thread safety.  Consider that if you intend to do anything with threads, now you have to lock for the entire duration of the loop, or someone can switch todo's right out from under you.  Whereas if you pass it, it's less likely to get trashed...and if you still need to lock or something, you can do it for part of one iteration instead of the whole loop.

Frankly, it's good that it's annoying.  There's probably a much simpler way to do what you want to do, which i couldn't really advise you on since the code is obviously not the real thing.  The best answer varies per case.