Are preconditions and postconditions needed in addition to invariants in member functions if doing design by contract? - design-by-contract

I understand that in the DbC method, preconditions and postconditions are attached to a function.
What I'm wondering is if that applies to member functions as well.
For instance, assuming I use invariants at the beginning at end of each public function, a member function will look like this:
edit: (cleaned up my example)
void Charcoal::LightOnFire() {
invariant();
in_LightOnFire();
StartBurning();
m_Status = STATUS_BURNING;
m_Color = 0xCCCCCC;
return; // last return in body
out_LightOnFire();
invariant();
}
inline void Charcoal::in_LightOnFire() {
#ifndef _RELEASE_
assert (m_Status == STATUS_UNLIT);
assert (m_OnTheGrill == true);
assert (m_DousedInLighterFluid == true);
#endif
}
inline void Charcoal::out_LightOnFire() {
#ifndef _RELEASE_
assert(m_Status == STATUS_BURNING);
assert(m_Color == 0xCCCCCC);
#endif
}
// class invariant
inline void Charcoal::invariant() {
assert(m_Status == STATUS_UNLIT || m_Status == STATUS_BURNING || m_Status == STATUS_ASHY);
assert(m_Color == 0x000000 || m_Color == 0xCCCCCC || m_Color == 0xEEEEEE);
}
Is it okay to use preconditions and postconditions with global/generic functions only and just use invariants inside classes?
This seems like overkill, but maybe its my example is bad.
edit:
Isn't the postcondition just checking a subset of the invariant?
In the above, I am following the instructions of http://www.digitalmars.com/ctg/contract.html that states, "The invariant is checked when a class constructor completes, at the start of the class destructor, before a public member is run, and after a public function finishes."
Thanks.

Restricting the contracts in the classes to invariants is not optimal.
Preconditions and Postconditions are not just a subset of the invariants.
Invariants, Pre-conditions and Post-conditions have very different roles.
Invariants confirms the internal coherence of the object. They should be valid at the end of the constructor and before and after each method call.
Pre-conditions are checking that the status of the object and the arguments are suitable for the execution of the method. Preconditions are complementary to the invariants. They cover the check of the arguments (a stronger check that the type itself, i.e. not null, > 0,.. etc) but also could check for the object internal status (i.e. a call to file.write("hello") is a valid call only if file.is_rw and file.is_open are true).
Post-conditions are cheking that the method satisfied its obligation Post-conditions are also complementary to the invariants. Of course the status of the object has to be coherent after the method execution, but the Post-conditions are checking that the expected action was performed (i.e. list.add(i) should have as consequence that list.has(i) is true and list.count = old list.count + 1).

Yes.
Class C's invariant is a common property of all of its instances (objects). The invariant evaluates to true if and only if the object is in a semantically valid state.
An elevator's invariant may contain information such as ASSERT(IsStopped() || Door.IsClosed()), because it is invalid for an elevator to be in a state different than stopped (say, going up) and with the door open.
In contrast, a member function such as MoveTo(int flat) may have CurrentFlat()==flat as a postcondition; because after a call to MoveTo(6) the current flat is 6. Similarly, it may have IsStopped() as a precondition, because (depending on the design) you can't invoke function MoveTo if the elevator is already moving. First, you have to query its state, make sure that it is stopped, and then call the function.
Of course I may be totally oversimplifying how an elevator works.
In any case, the preconditions and postconditions will make no sense, in general, as invariant conditions; an elevator doesn't need to be at floor 6 to be in a valid state.
A more concise example can be found here: Interception and Attributes: A Design-By-Contract Sample by Sasha Goldshtein.

Well, the point of an invariant is that it describes something that's true of the object at all times. In this case, something is on the grill, or not (nothing in between). They normally describe a property of the entire state of the object.
Pre and post conditions describe things that are true just before a method executes, and just after, and will concern just the state that should have been touched by the method. This is different, presumably, from the state of the object. Pre and post conditions might be thought of as describing the footprint of a method - just what it needed, just what it touched.
So, to the specific question, the ideas do different things, so you may well want both. You certainly cannot just use invariants instead of pre and post conditions - in this instance, part of the object invariant is "Something is on the grill or not", but the precondition of lightOnFire needs to know that the item is on the grill. You can never infer this from the object invariant. It is true that from pre and postconditions and a known start state, you can (assuming that the objects structure is only mutable through methods, and the pre and post conditions describe all the environmental changes), infer an object invariant. However, this can be complex, and when you're stating things "in language", it's easier to just provide both.
Of course, doing in variants that state a boolean item is either true or false is a bit pointless - the type system ensures that.

Related

In OOP, is function same things as a method? [duplicate]

Can someone provide a simple explanation of methods vs. functions in OOP context?
A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.
A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:
A method is implicitly passed the object on which it was called.
A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).
(this is a simplified explanation, ignoring issues of scope etc.)
A method is on an object or is static in class.
A function is independent of any object (and outside of any class).
For Java and C#, there are only methods.
For C, there are only functions.
For C++ and Python it would depend on whether or not you're in a class.
But in basic English:
Function: Standalone feature or functionality.
Method: One way of doing something, which has different approaches or methods, but related to the same aspect (aka class).
'method' is the object-oriented word for 'function'. That's pretty much all there is to it (ie., no real difference).
Unfortunately, I think a lot of the answers here are perpetuating or advancing the idea that there's some complex, meaningful difference.
Really - there isn't all that much to it, just different words for the same thing.
[late addition]
In fact, as Brian Neal pointed out in a comment to this question, the C++ standard never uses the term 'method' when refering to member functions. Some people may take that as an indication that C++ isn't really an object-oriented language; however, I prefer to take it as an indication that a pretty smart group of people didn't think there was a particularly strong reason to use a different term.
In general: methods are functions that belong to a class, functions can be on any other scope of the code so you could state that all methods are functions, but not all functions are methods:
Take the following python example:
class Door:
def open(self):
print 'hello stranger'
def knock_door():
a_door = Door()
Door.open(a_door)
knock_door()
The example given shows you a class called "Door" which has a method or action called "open", it is called a method because it was declared inside a class. There is another portion of code with "def" just below which defines a function, it is a function because it is not declared inside a class, this function calls the method we defined inside our class as you can see and finally the function is being called by itself.
As you can see you can call a function anywhere but if you want to call a method either you have to pass a new object of the same type as the class the method is declared (Class.method(object)) or you have to invoke the method inside the object (object.Method()), at least in python.
Think of methods as things only one entity can do, so if you have a Dog class it would make sense to have a bark function only inside that class and that would be a method, if you have also a Person class it could make sense to write a function "feed" for that doesn't belong to any class since both humans and dogs can be fed and you could call that a function since it does not belong to any class in particular.
Simple way to remember:
Function → Free (Free means it can be anywhere, no need to be in an object or class)
Method → Member (A member of an object or class)
A very general definition of the main difference between a Function and a Method:
Functions are defined outside of classes, while Methods are defined inside of and part of classes.
The idea behind Object Oriented paradigm is to "treat" the software is composed of .. well "objects". Objects in real world have properties, for instance if you have an Employee, the employee has a name, an employee id, a position, he belongs to a department etc. etc.
The object also know how to deal with its attributes and perform some operations on them. Let say if we want to know what an employee is doing right now we would ask him.
employe whatAreYouDoing.
That "whatAreYouDoing" is a "message" sent to the object. The object knows how to answer to that questions, it is said it has a "method" to resolve the question.
So, the way objects have to expose its behavior are called methods. Methods thus are the artifact object have to "do" something.
Other possible methods are
employee whatIsYourName
employee whatIsYourDepartmentsName
etc.
Functions in the other hand are ways a programming language has to compute some data, for instance you might have the function addValues( 8 , 8 ) that returns 16
// pseudo-code
function addValues( int x, int y ) return x + y
// call it
result = addValues( 8,8 )
print result // output is 16...
Since first popular programming languages ( such as fortran, c, pascal ) didn't cover the OO paradigm, they only call to these artifacts "functions".
for instance the previous function in C would be:
int addValues( int x, int y )
{
return x + y;
}
It is not "natural" to say an object has a "function" to perform some action, because functions are more related to mathematical stuff while an Employee has little mathematic on it, but you can have methods that do exactly the same as functions, for instance in Java this would be the equivalent addValues function.
public static int addValues( int x, int y ) {
return x + y;
}
Looks familiar? That´s because Java have its roots on C++ and C++ on C.
At the end is just a concept, in implementation they might look the same, but in the OO documentation these are called method.
Here´s an example of the previously Employee object in Java.
public class Employee {
Department department;
String name;
public String whatsYourName(){
return this.name;
}
public String whatsYourDeparmentsName(){
return this.department.name();
}
public String whatAreYouDoing(){
return "nothing";
}
// Ignore the following, only set here for completness
public Employee( String name ) {
this.name = name;
}
}
// Usage sample.
Employee employee = new Employee( "John" ); // Creates an employee called John
// If I want to display what is this employee doing I could use its methods.
// to know it.
String name = employee.whatIsYourName():
String doingWhat = employee.whatAreYouDoint();
// Print the info to the console.
System.out.printf("Employee %s is doing: %s", name, doingWhat );
Output:
Employee John is doing nothing.
The difference then, is on the "domain" where it is applied.
AppleScript have the idea of "natural language" matphor , that at some point OO had. For instance Smalltalk. I hope it may be reasonable easier for you to understand methods in objects after reading this.
NOTE: The code is not to be compiled, just to serve as an example. Feel free to modify the post and add Python example.
In OO world, the two are commonly used to mean the same thing.
From a pure Math and CS perspective, a function will always return the same result when called with the same arguments ( f(x,y) = (x + y) ). A method on the other hand, is typically associated with an instance of a class. Again though, most modern OO languages no longer use the term "function" for the most part. Many static methods can be quite like functions, as they typically have no state (not always true).
Let's say a function is a block of code (usually with its own scope, and sometimes with its own closure) that may receive some arguments and may also return a result.
A method is a function that is owned by an object (in some object oriented systems, it is more correct to say it is owned by a class). Being "owned" by a object/class means that you refer to the method through the object/class; for example, in Java if you want to invoke a method "open()" owned by an object "door" you need to write "door.open()".
Usually methods also gain some extra attributes describing their behaviour within the object/class, for example: visibility (related to the object oriented concept of encapsulation) which defines from which objects (or classes) the method can be invoked.
In many object oriented languages, all "functions" belong to some object (or class) and so in these languages there are no functions that are not methods.
Methods are functions of classes. In normal jargon, people interchange method and function all over. Basically you can think of them as the same thing (not sure if global functions are called methods).
http://en.wikipedia.org/wiki/Method_(computer_science)
A function is a mathematical concept. For example:
f(x,y) = sin(x) + cos(y)
says that function f() will return the sin of the first parameter added to the cosine of the second parameter. It's just math. As it happens sin() and cos() are also functions. A function has another property: all calls to a function with the same parameters, should return the same result.
A method, on the other hand, is a function that is related to an object in an object-oriented language. It has one implicit parameter: the object being acted upon (and it's state).
So, if you have an object Z with a method g(x), you might see the following:
Z.g(x) = sin(x) + cos(Z.y)
In this case, the parameter x is passed in, the same as in the function example earlier. However, the parameter to cos() is a value that lives inside the object Z. Z and the data that lives inside it (Z.y) are implicit parameters to Z's g() method.
Historically, there may have been a subtle difference with a "method" being something which does not return a value, and a "function" one which does.Each language has its own lexicon of terms with special meaning.
In "C", the word "function" means a program routine.
In Java, the term "function" does not have any special meaning. Whereas "method" means one of the routines that forms the implementation of a class.
In C# that would translate as:
public void DoSomething() {} // method
public int DoSomethingAndReturnMeANumber(){} // function
But really, I re-iterate that there is really no difference in the 2 concepts.
If you use the term "function" in informal discussions about Java, people will assume you meant "method" and carry on. Don't use it in proper documents or presentations about Java, or you will look silly.
Function or a method is a named callable piece of code which performs some operations and optionally returns a value.
In C language the term function is used. Java & C# people would say it a method (and a function in this case is defined within a class/object).
A C++ programmer might call it a function or sometimes method (depending on if they are writing procedural style c++ code or are doing object oriented way of C++, also a C/C++ only programmer would likely call it a function because term 'method' is less often used in C/C++ literature).
You use a function by just calling it's name like,
result = mySum(num1, num2);
You would call a method by referencing its object first like,
result = MyCalc.mySum(num1,num2);
Function is a set of logic that can be used to manipulate data.
While, Method is function that is used to manipulate the data of the object where it belongs.
So technically, if you have a function that is not completely related to your class but was declared in the class, its not a method; It's called a bad design.
In OO languages such as Object Pascal or C++, a "method" is a function associated with an object. So, for example, a "Dog" object might have a "bark" function and this would be considered a "Method". In contrast, the "StrLen" function stands alone (it provides the length of a string provided as an argument). It is thus just a "function." Javascript is technically Object Oriented as well but faces many limitations compared to a full-blown language like C++, C# or Pascal. Nonetheless, the distinction should still hold.
A couple of additional facts: C# is fully object oriented so you cannot create standalone "functions." In C# every function is bound to an object and is thus, technically, a "method." The kicker is that few people in C# refer to them as "methods" - they just use the term "functions" because there isn't any real distinction to be made.
Finally - just so any Pascal gurus don't jump on me here - Pascal also differentiates between "functions" (which return a value) and "procedures" which do not. C# does not make this distinction explicitly although you can, of course, choose to return a value or not.
Methods on a class act on the instance of the class, called the object.
class Example
{
public int data = 0; // Each instance of Example holds its internal data. This is a "field", or "member variable".
public void UpdateData() // .. and manipulates it (This is a method by the way)
{
data = data + 1;
}
public void PrintData() // This is also a method
{
Console.WriteLine(data);
}
}
class Program
{
public static void Main()
{
Example exampleObject1 = new Example();
Example exampleObject2 = new Example();
exampleObject1.UpdateData();
exampleObject1.UpdateData();
exampleObject2.UpdateData();
exampleObject1.PrintData(); // Prints "2"
exampleObject2.PrintData(); // Prints "1"
}
}
Since you mentioned Python, the following might be a useful illustration of the relationship between methods and objects in most modern object-oriented languages. In a nutshell what they call a "method" is just a function that gets passed an extra argument (as other answers have pointed out), but Python makes that more explicit than most languages.
# perfectly normal function
def hello(greetee):
print "Hello", greetee
# generalise a bit (still a function though)
def greet(greeting, greetee):
print greeting, greetee
# hide the greeting behind a layer of abstraction (still a function!)
def greet_with_greeter(greeter, greetee):
print greeter.greeting, greetee
# very simple class we can pass to greet_with_greeter
class Greeter(object):
def __init__(self, greeting):
self.greeting = greeting
# while we're at it, here's a method that uses self.greeting...
def greet(self, greetee):
print self.greeting, greetee
# save an object of class Greeter for later
hello_greeter = Greeter("Hello")
# now all of the following print the same message
hello("World")
greet("Hello", "World")
greet_with_greeter(hello_greeter, "World")
hello_greeter.greet("World")
Now compare the function greet_with_greeter and the method greet: the only difference is the name of the first parameter (in the function I called it "greeter", in the method I called it "self"). So I can use the greet method in exactly the same way as I use the greet_with_greeter function (using the "dot" syntax to get at it, since I defined it inside a class):
Greeter.greet(hello_greeter, "World")
So I've effectively turned a method into a function. Can I turn a function into a method? Well, as Python lets you mess with classes after they're defined, let's try:
Greeter.greet2 = greet_with_greeter
hello_greeter.greet2("World")
Yes, the function greet_with_greeter is now also known as the method greet2. This shows the only real difference between a method and a function: when you call a method "on" an object by calling object.method(args), the language magically turns it into method(object, args).
(OO purists might argue a method is something different from a function, and if you get into advanced Python or Ruby - or Smalltalk! - you will start to see their point. Also some languages give methods special access to bits of an object. But the main conceptual difference is still the hidden extra parameter.)
for me:
the function of a method and a function is the same if I agree that:
a function may return a value
may expect parameters
Just like any piece of code you may have objects you put in and you may have an object that comes as a result. During doing that they might change the state of an object but that would not change their basic functioning for me.
There might be a definition differencing in calling functions of objects or other codes. But isn't that something for a verbal differenciations and that's why people interchange them? The mentions example of computation I would be careful with. because I hire employes to do my calculations:
new Employer().calculateSum( 8, 8 );
By doing it that way I can rely on an employer being responsible for calculations. If he wants more money I free him and let the carbage collector's function of disposing unused employees do the rest and get a new employee.
Even arguing that a method is an objects function and a function is unconnected computation will not help me. The function descriptor itself and ideally the function's documentation will tell me what it needs and what it may return. The rest, like manipulating some object's state is not really transparent to me. I do expect both functions and methods to deliver and manipulate what they claim to without needing to know in detail how they do it.
Even a pure computational function might change the console's state or append to a logfile.
From my understanding a method is any operation which can be performed on a class. It is a general term used in programming.
In many languages methods are represented by functions and subroutines. The main distinction that most languages use for these is that functions may return a value back to the caller and a subroutine may not. However many modern languages only have functions, but these can optionally not return any value.
For example, lets say you want to describe a cat and you would like that to be able to yawn. You would create a Cat class, with a Yawn method, which would most likely be a function without any return value.
To a first order approximation, a method (in C++ style OO) is another word for a member function, that is a function that is part of a class.
In languages like C/C++ you can have functions which are not members of a class; you don't call a function not associated with a class a method.
IMHO people just wanted to invent new word for easier communication between programmers when they wanted to refer to functions inside objects.
If you are saying methods you mean functions inside the class.
If you are saying functions you mean simply functions outside the class.
The truth is that both words are used to describe functions. Even if you used it wrongly nothing wrong happens. Both words describe well what you want to achieve in your code.
Function is a code that has to play a role (a function) of doing something.
Method is a method to resolve the problem.
It does the same thing. It is the same thing. If you want to be super precise and go along with the convention you can call methods as the functions inside objects.
Let's not over complicate what should be a very simple answer. Methods and functions are the same thing. You call a function a function when it is outside of a class, and you call a function a method when it is written inside a class.
Function is the concept mainly belonging to Procedure oriented programming where a function is an an entity which can process data and returns you value
Method is the concept of Object Oriented programming where a method is a member of a class which mostly does processing on the class members.
I am not an expert, but this is what I know:
Function is C language term, it refers to a piece of code and the function name will be the identifier to use this function.
Method is the OO term, typically it has a this pointer in the function parameter. You can not invoke this piece of code like C, you need to use object to invoke it.
The invoke methods are also different. Here invoke meaning to find the address of this piece of code. C/C++, the linking time will use the function symbol to locate.
Objecive-C is different. Invoke meaning a C function to use data structure to find the address. It means everything is known at run time.
TL;DR
A Function is a piece of code to run.
A Method is a Function inside an Object.
Example of a function:
function sum(){
console.log("sum")l
}
Example of a Method:
const obj = {
a:1,
b:2,
sum(){
}
}
So thats why we say that a "this" keyword inside a Function is not very useful unless we use it with call, apply or bind .. because call, apply, bind will call that function as a method inside object ==> basically it converts function to method
I know many others have already answered, but I found following is a simple, yet effective single line answer. Though it doesn't look a lot better than others answers here, but if you read it carefully, it has everything you need to know about the method vs function.
A method is a function that has a defined receiver, in OOP terms, a method is a function on an instance of an object.
A class is the collection of some data and function optionally with a constructor.
While you creating an instance (copy,replication) of that particular class the constructor initialize the class and return an object.
Now the class become object (without constructor)
&
Functions are known as method in the object context.
So basically
Class <==new==>Object
Function <==new==>Method
In java the it is generally told as that the constructor name same as class name but in real that constructor is like instance block and static block but with having a user define return type(i.e. Class type)
While the class can have an static block,instance block,constructor, function
The object generally have only data & method.
Function - A function in an independent piece of code which includes some logic and must be called independently and are defined outside of class.
Method - A method is an independent piece of code which is called in reference to some object and are be defined inside the class.
General answer is:
method has object context (this, or class instance reference),
function has none context (null, or global, or static).
But answer to question is dependent on terminology of language you use.
In JavaScript (ES 6) you are free to customising function context (this) for any you desire, which is normally must be link to the (this) object instance context.
In Java world you always hear that "only OOP classes/objects, no functions", but if you watch in detailes to static methods in Java, they are really in global/null context (or context of classes, whithout instancing), so just functions whithout object. Java teachers could told you, that functions were rudiment of C in C++ and dropped in Java, but they told you it for simplification of history and avoiding unnecessary questions of newbies. If you see at Java after 7 version, you can find many elements of pure function programming (even not from C, but from older 1988 Lisp) for simplifying parallel computing, and it is not OOP classes style.
In C++ and D world things are stronger, and you have separated functions and objects with methods and fields. But in practice, you again see functions without this and methods whith this (with object context).
In FreePascal/Lazarus and Borland Pascal/Delphi things about separation terms of functions and objects (variables and fields) are usually similar to C++.
Objective-C comes from C world, so you must separate C functions and Objective-C objects with methods addon.
C# is very similar to Java, but has many C++ advantages.
In C++, sometimes, method is used to reflect the notion of member function of a class. However, recently I found a statement in the book «The C++ Programming Language 4th Edition», on page 586 "Derived Classes"
A virtual function is sometimes called a method.
This is a little bit confusing, but he said sometimes, so it roughly makes sense, C++ creator tends to see methods as functions can be invoked on objects and can behave polymorphic.

Declaration vs. Prototype vs. Symbol vs. Definition vs. Implementation

I see the terms "declaration," "prototype" and "symbol" thrown around interchangeably a lot when it comes to code like the following:
void MyUndefinedFunction();
The same goes for "definition" and "implementation" for things like this:
void MyClass::MyMethod()
{
// Actual code here.
}
Are there any distinctions between the terms, as with "argument" and "parameter?" Or are they truly synonymous?
Note: I'm not sure if this belongs here or on Programmers, so I posted it on both sites. If anyone has any objections, let me know and I'll delete one.
Unless you run into a purist, they are generally interchangable, except for symbol and prototype (difficult to give absolutes on language-agnostic)
symbol generally refers to a hook point for linking 2 bits of code together, such as a library entry point, or a target for resolving static linking
prototype generally refers to a definition of what a function/method looks like (arguments, return type, name, various types of visibility), but doesn't include an implementation.
You missed function vs. method, but my definition is:
function a callable bit of code that isn't bound to an object
method a callable bit of code in an object's namespace. Generally implemented by the compiler as a function that takes the object instance as it's first argument.
Possibly parameter hints at limiting scope, and therefore read-only.
Note If you ask a purist, you're more likely to have an argument than a parameter.
The difference between declaration and prototype is mainly in C, where the following is a non-prototype declaration:
int foo();
Note that this is different from:
int foo(void);
The latter is a prototype for a function taking no arguments, while the former is a declaration for a function whose argument types are not specified in the declaration. This can actually be useful to avoid function-pointer-type casts with certain uses of function pointers, but it's very easy to mess up, and messing it up invokes undefined behavior. Many C programmers consider non-prototype declarations harmful, and gcc has a warning option to flag them.

What is the advantage of having this/self pointer mandatory explicit?

What is the advantage of having this/self/me pointer mandatory explicit?
According to OOP theory a method is supposed to operate mainly (only?) on member variables and method's arguments. Following this, it should be easier to refer to member variables than to external (from the object's side of view) variables... Explicit this makes it more verbose thus harder to refer to member variables than to external ones. This seems counter intuitive to me.
In addition to member variables and method parameters you also have local variables. One of the most important things about the object is its internal state. Explicit member variable dereferencing makes it very clear where you are referencing that state and where you are modifying that state.
For instance, if you have code like:
someMethod(some, parameters) {
... a segment of code
foo = 42;
... another segment of code
}
when quickly browsing through it, you have to have a mental model of the variables defined in the preceding segment to know if it's just a temporary variable or does it mutate the objects state. Whereas this.foo = 42 makes it obvious that the objects state is mutated. And if explicit dereferencing is exclusively used, you can be sure that the variable is temporary in the opposite case.
Shorter, well factored methods make it a bit less important, but still, long term understandability trumps a little convenience while writing the code.
You need it to pass the pointer/reference to the current object elsewhere or to protect against self-assignment in an assignment operator.
What if the arguments to a method have the same name as the member variables? Then you can use this.x = x for example. Where this.x is the member variable and x is the method argument.
That's just one (trivial) example.
I generally use this (in C++) only when I am writing the assignment operator or the copy constructor as it helps in clearly identifying the variables. Other place where I can think of using it is if your function parameter variable names are same as your member variable names or I want to kill my object using delete this.
Eg would be where member names are same as those passed to method
public void SetScreenTemplate(long screenTemplateID, string screenTemplateName, bool isDefault)
{
this.screenTemplateID = screenTemplateID;
this.screenTemplateName = screenTemplateName;
this.isDefault = isDefault;
}

When to check function/method parameters?

when writing small functions I often have the case that some parameters are given to a function which itself only passes them to different small functions to serve its purpose.
For example (C#-ish Syntax):
public void FunctionA(object param)
{
DoA(param);
DoB(param);
DoC(param);
// etc.
}
private void DoA(object param)
{
DoD(param);
}
private void DoD(object param)
{
// Error if param == null
param.DoX();
}
So the parameters are not used inside the called function but "somewhere" in the depths of the small functions that do the job.
So when is it best to check if my param-Object is null?
When checking in FunctionA:
Pro:
-There is no overhead through the use of further methods which at last will do nothing because object is null.
Con:
-My syntactically wonderful FunctionA is dirtied by ugly validation code.
When checking only when param-object is used:
Pro:
-My syntactically wonderful FunctionA keeps a joy to read :)
Cons:
-There will be overhead through calling methods which will do nothing because the param-object is null.
-Further cons I don't think about at the moment.
Always put it as far down the call stack as possible, so that if you later refactor the code and something else calls DoD other than DoA you have the check in place and don't have to rework your parameter checks. The overhead of a small null check and possibly a few extra method calls is going to be trivial in most cases and doing the check an extra few times is not something you should be worrying about.
Unless you think the value is likely to be null the vast majority of the time, I'd put the validation in DoD(). If you put it in FunctionA() you'll have to repeat the validation code later when you decide FunctionB() also needs to use DoD(). To me, the extra overhead is worth not having to repeat myself.
As a guideline, I make a habit of it to check every parameter that is used by the method, even including my own private variables. I would therefore only check for nil in your DoD method.
You might want to check out Bertrand Meyers Design By Contract mantra.
Fail early. Unless a partial result is preferable to no result at all, execution should stop as soon as the code can detect that there is a problem. Why should the code run through several methods when the result downstream is going to be an invalid or missing argument?
If it is possible that the downstream methods could be called separately then validation could be handled by a call to ca common validation methed as has already been suggested.
Always check everything :) Coming from the deep bowels of coding libraries for embedded systems, this is the method I'd use:
public void FunctionA(object param)
{
assert(param != null && param.canDoX());
DoA(param);
DoB(param);
DoC(param);
// etc.
}
private void DoA(object param)
{
assert(param != null && param.canDoX());
DoD(param);
}
private void DoD(object param)
{
assert(param != null && param.canDoX());
if ( param != null )
param.DoX();
else
// Signal error, for instance by throwing a runtime exception
// This error-handling is then verified by a unit test that
// uses a release build of the code.
}
To de-clutter this, the obvious solution is to break out the validation to a separate validator function. Using a C-style preprocessor, or just sticking to asserts, it should be trivial to have this "paranoid" validation excluded from release builds.
It's the caller's responsibility to pass a valid parameter. In this case:
if(param != null)
{
FunctionA(param);
}

Exception handling: Contract vs Exceptional approach

I know two approaches to Exception handling, lets have a look at them.
Contract approach.
When a method does not do what it says it will do in the method header, it will throw an exception. Thus the method "promises" that it will do the operation, and if it fails for some reason, it will throw an exception.
Exceptional approach.
Only throw exceptions when something truly weird happens. You should not use exceptions when you can resolve the situation with normal control flow (If statements). You don't use Exceptions for control flow, as you might in the contract approach.
Lets use both approaches in different cases:
We have a Customer class that has a method called OrderProduct.
contract approach:
class Customer
{
public void OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
throw new NoCreditException("Not enough credit!");
// do stuff
}
}
exceptional approach:
class Customer
{
public bool OrderProduct(Product product)
{
if((m_credit - product.Price) < 0)
return false;
// do stuff
return true;
}
}
if !(customer.OrderProduct(product))
Console.WriteLine("Not enough credit!");
else
// go on with your life
Here I prefer the exceptional approach, as it is not truly Exceptional that a customer has no money assuming he did not win the lottery.
But here is a situation I err on the contract style.
Exceptional:
class CarController
{
// returns null if car creation failed.
public Car CreateCar(string model)
{
// something went wrong, wrong model
return null;
}
}
When I call a method called CreateCar, I damn wel expect a Car instance instead of some lousy null pointer, which can ravage my running code a dozen lines later. Thus I prefer contract to this one:
class CarController
{
public Car CreateCar(string model)
{
// something went wrong, wrong model
throw new CarModelNotKnownException("Model unkown");
return new Car();
}
}
Which do style do you use? What do you think is best general approach to Exceptions?
I favor what you call the "contract" approach. Returning nulls or other special values to indicate errors isn't necessary in a language that supports exceptions. I find it much easier to understand code when it doesn't have a bunch of "if (result == NULL)" or "if (result == -1)" clauses mixed in with what could be very simple, straightforward logic.
My usual approach is to use contract to handle any kind of error due to "client" invocation, that is, due to an external error (i.e ArgumentNullException).
Every error on the arguments is not handled. An exception is raised and the "client" is in charge of handling it. On the other hand, for internal errors always try to correct them (as if you can't get a database connection for some reason) and only if you can't handle it reraise the exception.
It's important to keep in mind that most unhandled exception at such level will not be able to be handled by the client anyway so they will just probably go up to the most general exception handler, so if such an exception occurs you are probably FUBAR anyway.
I believe that if you are building a class which will be used by an external program (or will be reused by other programs) then you should use the contract approach. A good example of this is an API of any kind.
If you are actually interested in exceptions and want to think about how to use them to construct robust systems, consider reading Making reliable distributed systems in the presence of software errors.
Both approaches are right. What that means is that a contract should be written in such a way as to specify for all cases that are not truly exceptional a behavior that does not require throwing an exception.
Note that some situations may or may not be exceptional based upon what the caller of the code is expecting. If the caller is expecting that a dictionary will contain a certain item, and absence of that item would indicate a severe problem, then failure to find the item is an exceptional condition and should cause an exception to be thrown. If, however, the caller doesn't really know if an item exists, and is equally prepared to handle its presence or its absence, then absence of the item would be an expected condition and should not cause an exception. The best way to handle such variations in caller expectation is to have a contract specify two methods: a DoSomething method and a TryDoSomething method, e.g.
TValue GetValue(TKey Key);
bool TryGetValue(TKey Key, ref TValue value);
Note that, while the standard 'try' pattern is as illustrated above, some alternatives may also be helpful if one is designing an interface which produces items:
// In case of failure, set ok false and return default<TValue>.
TValue TryGetResult(ref bool ok, TParam param);
// In case of failure, indicate particular problem in GetKeyErrorInfo
// and return default<TValue>.
TValue TryGetResult(ref GetKeyErrorInfo errorInfo, ref TParam param);
Note that using something like the normal TryGetResult pattern within an interface will make the interface invariant with respect to the result type; using one of the patterns above will allow the interface to be covariant with respect to the result type. Also, it will allow the result to be used in a 'var' declaration:
var myThingResult = myThing.TryGetSomeValue(ref ok, whatever);
if (ok) { do_whatever }
Not quite the standard approach, but in some cases the advantages may justify it.