How do I represent the type of an argument in a UML class diagram, when the argument is a function? - function

For example, a class has a method compute() (using Python syntax and dropping the self argument for clarity):
def compute(computation_fn):
return computation_fn(5)
Let's assume that computation_fn maps int to int. In a UML class diagram, should I write something like this?
+ compute(computation_fn: (num: int): int): int
If this has already been answered somewhere, just drop a link! I've been trying to look for an answer.

UML does only have the basic types Integer, Boolean, String, UnlimitedNatural, and Real.
You can also use any class that you define in your model as type. In this regard, you can very well define a class that corresponds to a kind of functions, for example FunctionOfIntToInt. That's usual business in any design that uses callables.
UML may also be enriched with additional types in a profile. Very often, you'll see types of your favourite language used. This assumes the use of a language specific profile. But usually it's fixed type names (e.g. Date, UInt8, ...). You could imagine a type called as (int):int, but this would be ambiguous in regard of UML's syntax that uses already :.
Unfortunately, there's nothing in UML's typing system that would allow to represent functions with arbitrary number of arguments of flexible type. So it all depends how compliant you need to be with UML:
Python programmers would understand any python type that you'd use in the diagram, including function types, even if it's not "pure" UML. So this would be pragmatic approach. I'll recommend nevertheless to replace the : for the return type with -> to avoid lexical confusion
But if you have to go by the book, profiles don't allow for a syntax extension that would allow to compose types on the top of existing UML mechanisms. There's a workaround. You could use an UML template class to represent functions. The first argument would be the return type, and the remaining template arguments the argument types. You'd then use UML's native template binding syntax to instantiate the template for typing purpose. But I agree, it's more clumsy (even if it'd seem familiar to any user of C++ std::function template.

Related

How to define my function from a string?

This is normal definition of some function as I know:
real function f(x)
real x
f = (sin(x))**2*exp(-x)
end function f
But I want to define a function from some string, for example the program will ask me to write it, and then it will define the function f in a program. Is this possible in Fortran?
What you are looking for is possible in reflective programming languages, and is not possible in Fortran.
Quote from the link above:
A language supporting reflection provides a number of features available at runtime that would otherwise be very obscure to accomplish in a lower-level language. Some of these features are the abilities to:
Discover and modify source code constructions (such as code blocks, classes, methods, protocols, etc.) as a first-class object at runtime.
Convert a string matching the symbolic name of a class or function into a reference to or invocation of that class or function.
Evaluate a string as if it were a source code statement at runtime.
Create a new interpreter for the language's bytecode to give a new meaning or purpose for a programming construct.
I worked on a project once that tried to achieve something similar. We read in a string that contained a string with named variables and mathematical operations (a function if you will). In this string the variables then got replaced by their numerical values and the terms were evaluated.
The basic idea is not to too difficult, but it requires a lot of string manipulations - and it is not a function in the context of a programming language.
We did it like this:
Recursively divide the string at +,-,/,*, but remember to honor brackets
If this is not possible (without violating bracketing), evaluate the remaining string:
Does it contain a mathematical expression like cos? Yes => recurse into arguments
No => evaluate the mathematical expression (no variables allowed, but they got replaced)
This works quite well, but it requires:
Splitting strings
Matching in strings
Replacing strings with other strings, etc.
This is not trivial to do in Fortran, so if you have other options (like calling an external tool/script that returns the value), I would look into that - especially if you are new to Fortran!

Is the quality of a language where it's not required to declare a variables type an example of weak typing or dynamic typing

Is the quality of a language where it's not required to declare a variables type (such as PHP and Perl) known as weak typing or dynamic typing? I'm having trouble getting my head around the two terms.
Am I right that dynamic/static typing pertains to type conversion whereas weak/strong typing pertains to the deceleration of a variable?
According to: http://en.wikipedia.org/wiki/Type_system#Static_and_dynamic_type_checking_in_practice
Weak typing means that a language implicitly converts (or casts) types when used.
whereas:
A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time.
So, strong/weak and static/dynamic are two different dimensions. A language will be one of strong/weak, and also one of static dynamic. For instance, Ruby and Javascript are both dynamically typed, but Ruby is strongly typed while Javascript is weakly typed. That is, in Ruby the following code with give an error:
1.9.2p290 :001 > 'a'+1
TypeError: can't convert Fixnum into String
whereas in JavaScript, you get:
> 'a'+1
>> 'a1'
So, a strongly typed language requires you to convert two variables to the same type in order to combine them (eg. using 1.to_s), while a weakly typed language will attempt to coerce the two variables into the same type using some extra built-in language logic - in JavaScript's case, combining anything with a String will convert it into a String value.
See: http://www.artima.com/weblogs/viewpost.jsp?thread=7590 for a further explanation.
In simple terms, strong typing has more to do with how objects are bound (essentially early binding vs. late binding) than they have to do with how they are declared.
Let's say in C# I have this class:
public class Foo
{
public int Bar;
public double Baz;
}
And I declare a variable of type foo:
var myFoo = new Foo();
When I reference Foo, like this:
foo.
Visual Studio will display a list containing Bar and Baz when I type the ., because it already knows that myFoo contains those members; it is of type Foo. This is strong typing; it means that if I misspell Bar or Baz, my program won't even compile.
However, let's say I declare a variable of type dynamic This causes object binding to be deferred until the program is executed:
dynamic myFoo = new Foo();
myFoo.Grapes = 6;
This will compile. I won't get an error until the program is run; a runtime exception will be thrown because Grapes doesn't exist on Foo.
This is an old question, but for future readers this great article may clear things up: http://blogs.perl.org/users/ovid/2010/08/what-to-know-before-debating-type-systems.html
It's kind of long but it definitively worth it.
Strong and Weak Typing:
Probably the most common way type systems are classified is "strong"
or "weak." This is unfortunate, since these words have nearly no
meaning at all. It is, to a limited extent, possible to compare two
languages with very similar type systems, and designate one as having
the stronger of those two systems. Beyond that, the words mean nothing
at all.
Static and Dynamic Types
This is very nearly the only common classification of type systems
that has real meaning. As a matter of fact, it's significance is
frequently under-estimated [...] Dynamic and static type systems are
two completely different things, whose goals happen to partially
overlap.
A static type system is a mechanism by which a compiler examines
source code and assigns labels (called "types") to pieces of the
syntax, and then uses them to infer something about the program's
behavior. A dynamic type system is a mechanism by which a compiler
generates code to keep track of the sort of data (coincidentally, also
called its "type") used by the program. The use of the same word
"type" in each of these two systems is, of course, not really entirely
coincidental; yet it is best understood as having a sort of weak
historical significance. Great confusion results from trying to find a
world view in which "type" really means the same thing in both
systems. It doesn't.
Explicit/Implicit Types:
When these terms are used, they refer to the extent to which a
compiler will reason about the static types of parts of a program. All
programming languages have some form of reasoning about types. Some
have more than others. ML and Haskell have implicit types, in that no
(or very few, depending on the language and extensions in use) type
declarations are needed. Java and Ada have very explicit types, and
one is constantly declaring the types of things. All of the above have
(relatively, compared to C and C++, for example) strong static type
systems.

What are better ways to create a method that takes many arguments? (10+?)

I was looking at some code of a fellow developer, and almost cried. In the method definition there are 12 arguments. From my experience..this isn't good. If it were me, I would have sent in an object of some sort.
Is there another / more preferred way to do this (in other words, what's the best way to fix this and explain why)?
public long Save (
String today,
String name,
String desc,
int ID,
String otherNm,
DateTime dt,
int status,
String periodID,
String otherDt,
String submittedDt
)
ignore my poor variable names - they are examples
It highly depends on the language.
In a language without compile-time typechecking (e.g. python, javascript, etc.) you should use keyword arguments (common in python: you can access them like a dictionary passed in as an argument) or objects/dictionaries you manually pass in as arguments (common in javascript).
However the "argument hell" you described is sometimes "the right way to do things" for certain languages with compile-time typechecking, because using objects will obfuscate the semantics from the typechecker. The solution then would be to use a better language with compile-time typechecking which allows pattern-matching of objects as arguments.
Yes, use objects. Also, the function is probably doing too much if it needs all of this information, so use smaller functions.
Use objects.
class User { ... }
User user = ...
Save(user);
It decision provides easy way for adding new parameters.
It depends on how complex the function is. If it does something non-trivial with each of those arguments, it should probably be split. If it just passes them through, they should probably be collected in an object. But if it just creates a row in a table, it's not really big deal. It's less of a deal if your language supports keyword arguments.
I imagine the issue you're experiencing is being able to look at the method call and know what argument is receiving what value. This is a pernicious problem in a language like Java, which lacks something like keyword arguments or JSON hashes to pass named arguments.
In this situation, the Builder pattern is a useful solution. It's more objects, three total, but leads to more comprehensible code for the problem you're describing. So the three objects in this case would be as such:
Thing: stateful entity, typically immutable (i.e. getters only)
ThingBuilder: factory class, creates a Thing entity and sets its values.
ThingDAO: not necessary for using the Builder pattern, but addresses your question.
Interaction
/*
ThingBuilder is a static inner class of Thing, where each of its
"set" method calls returns the ThingBuilder instance being worked with
while the final "build()" call returns the instantiated Thing instance.
*/
Thing thing = Thing.createBuilder().
.setToday("2012/04/01")
.setName("Example")
// ...etc...
.build();
// the Thing instance as get methods for each property
thing.getName();
// get your reference to thingDAO however it's done
thingDAO.save(thing);
The result is you get named arguments and an immutable instance.

Too many arguments for function

I'm starting to learn Lisp with a Java background. In SICP's exercise there are many tasks where students should create abstract functions with many parameters, like
(define (filtered-accumulate combiner null-value term a next b filter)...)
in exercise 1.33. In Java (language with safe, static typing discipline) - a method with more than 4 arguments usually smells, but in Lisp/Scheme it doesn't, does it? I'm wondering how many arguments do you use in your functions? If you use it in production, do you make as many layers?
SICP uses a subset of Scheme
SICP is a book used in introductory computer science course. While it explains some advanced concepts, it uses a very tiny language, a subset of the Scheme language and a sub-subset of any real world Scheme or Lisp a typical implementation provides. Students using SICP are supposed to start with a simple and easy to learn language. From there they learn to implement more complex language additions.
Only positional parameters are being used in plain educational Scheme
There are for example no macros developed in SICP. Add that standard Scheme does have only positional parameters for functions.
Lisp and Scheme offer also more expressive argument lists
In 'real' Lisp or Scheme one can use one or more of the following:
objects or records/structures (poor man's closures) which group things. An object passed can contain several data items, which otherwise would need to be passed 'spread'.
defaults for optional variables. Thus we need only to pass those that we want to have a certain non-default value
optional and named arguments. This allows flexible argument lists which are much more descriptive.
computed arguments. The value or the default value of arguments can be computed based on other arguments
Above leads to more complicated to write function interfaces, but which are often easier to use.
In Lisp it is good style to have descriptive names for arguments and also provide online documentation for the interface. The development environment will display information about the interface of a function, so this information is typically only a keystroke away or is even display automatically.
It's also good style for any non-trivial interface which is supposed to be used interactively by the user/developer to check its arguments at runtime.
Example for a complex, but readable argument list
When there are more arguments, then Common Lisp provides named arguments, which can appear in any order after the normal argument. Named arguments provide also defaults and can be omitted:
(defun order-product (product
&key
buyer
seller
(vat (local-vat seller))
(price (best-price product))
amount
free-delivery-p)
"The function ORDER-PRODUCT ..." ; documentation string
(declare (type ratio vat price) ; type declarations
(type (integer 0) amount)
(type boolean free-delivery-p))
...)
We would use it then:
(order-product 'sicp
:seller 'mit-press
:buyer 'stan-kurilin
:amount 1)
Above uses the seller argument before the buyerargument. It also omits various arguments, some of which have their values computed.
Now we can ask whether such extensive arguments are good or bad. The arguments for them:
the function call gets more descriptive
functions have standard mechanisms to attach documentation
functions can be asked for their parameter lists
type declarations are possible -> thus types don't need to be written as comments
many parameters can have sensible default values and don't need to be mentioned
Several Scheme implementations have adopted similar argument lists.

What is the difference between Type and Class?

What makes a type different from class and vice versa?
(In the general language-agnostic sense)
The following answer is from Gof book (Design Patterns)
An object's class defines how the
object is implemented. The class
defines object's internal state and
the implementation of its
operations.
In contrast, an object's
type only refers to its interface - a
set of requests to which it can
respond.
An object can have many types,
and objects of different classes can
have the same type.
//example in c++
template<typename T>
const T & max(T const &a,T const &b)
{
return a>b?a:b; //> operator of the type is used for comparison
}
max function requires a type with operation > with its own type as one of it interface any class that satisfies the above requirement can be used to generate specific max<particular class/primitive type> function for that class.
Inspired by Wikipedia...
In type theory terms;
A type is an abstract interface.
Types generally represent nouns, such as a person, place or thing, or something nominalized,
A class represents an implementation of the type.
It is a concrete data structure and collection of subroutines
Different concrete classes can produce objects of the same abstract type (depending on type system).
*For example, one might implement the type Stack with two classes: SmallStack (fast for small stacks, but scales poorly) and ScalableStack (scales well but high overhead for small stacks).*
Similarly, a given class may have several different constructors.
The banana example.
A Banana type would represent the properties and functionality of bananas in general.
The ABCBanana and XYZBanana classes would represent ways of producing bananas.
(Different banana suppliers in real life, or different data structures and functions to represent and draw bananas in a video game).
The ABCBanana class could then produce particular bananas which are
instances of the ABCBanana class, they would be objects of type Banana.
It is not rare the programmer provide a single and only implementation for a type. In this case the class name is often identical with the type name. But there is still a type (which could be extracted in an interface if required), and an implementation (which would implement the separate interface) which builds instances (objects) of the class.
I always think of a 'type' as an umbrella term for 'classes' and 'primitives'.
int foo; // Type is int, class is nonexistent.
MyClass foo; // Type is MyClass, class is MyClass
Type is the umbrella term for all the available object templates or concepts. A class is one such object template. So is the structure type, the Integer type, the Interface type etc. These are all types
If you want, you can look at it this way: A type is the parent concept. All the other concepts: Class, Interface, Structure, Integer etc inherit from this concept.i.e They are types
Taken from the GoF citation from below:
An objects's class defines how the
object is implemented .The class
defines the object's internal state and
the implementation of its
operations.
In contrast, an objects's
type only refers to its interface - the
set of requests to which it can
respond.
I want to provide an example using Java:
public interface IType {
}
public class A implements IType {
public A{};
}
public class B implements IType {
public B{};
}
Both classes A and B implement the interface and thus are of the type IType. Additionally in Java, both classes produce their own type (respectively to their class name). Thus the class A is of type A and IType and the class B is of type B and IType satisfying:
An object can have many types,
and objects of different classes can
have the same type.
The difference between subtypes and subclass probably helps to understand that issue as well:
https://www.cs.princeton.edu/courses/archive/fall98/cs441/mainus/node12.html
In general language-agnostic sense - Class is an realization of the Type.
Often when this is the only realization of that type, you can use both terms to reference it in some context.
On the contrary, for example, in C# context - Class is just one of the many more implementations of a Type concept like primitives, structs, pointers etc.
Type contains description of the data (i.e. properties, operations, etc),
Class is a specific type - it is a template to create instances of objects.
Strictly speaking class is a special concept, it can be seen as a package containing subset of metadata describing some aspects of an object.
For example in C# you can find interfaces and classes. Both of them are types, but interface can only define some contract and can not be instantiated unlike classes.
Simply speaking class is a specialized type used to encapsulate properties and behavior of an object.
Wikipedia can give you a more complete answer:
Definition of class
Definition of data type
Type is conceptually a superset of class. In the broader sense, a class is one form of type.
Closely related to classes are interfaces, which can bee seen as a very special kind of class - a purely abstract one. These too are types.
So "type" encompasses classes, interfaces and in most languages primitives too. Also platforms like the dot-net CLR have structure types too.
To illustrate it the fastest way:
A Struct is a Type, but a Struct is not a Class.
As you can see, a Type is an "abstract" term for not only definitions of classes, but also structs and primitive data types like float, int, bool.
I think of a type as being the set of things you can do with a particular value. For instance, if you have an integer value, you can add it to other integers (or perform other arithmetic operations), or pass it to functions which accept an integer argument. If you have an object value, you can call methods on it that are defined by its class.
Because a class defines what you can do with objects of that class, a class defines a type. A class is more than that though, since it also provides a description of how the methods are implemented (something not implied by the type) and how the fields of the object are laid out.
Note also that an object value can only have one class, but it may have multiple types, since every superclass provides a subset of the functionality available in the object's class.
So although objects and types are closely related, they are really not the same thing.
To add another example of distinction: in C++ you have pointer and reference types which can refer to classes, but are not classes in and of themselves.
Bar b; // b is of type "class Bar"
Bar *b2 = &b; // b2 is of type "pointer to Class Bar"
Bar &b3 = b; // b3 is of type "reference to Class Bar"
Bar *b4[7]; // b4 is of type "7-element array of pointers to Class Bar"
Bar ***b5; //b5 is of type "pointer to a pointer to a pointer to Class Bar"
Note that only one class is involved, but a near infinite number of types can be used. In some languages, function are considered "first-class-objects" in which case, the type of a function is a class. In others, the type of a function is merely a pointer. Classes generally have the concepts of being able to hold data, as well as operations on that data.
My thoughts are pretty much in line with aku's answer.
I see classes as a template for building objects, while types are a way to classify those objects, and provide us with an interface to them.
Python also adds metaclasses, that are just a mechanism to build classes, in the same way as classes build objects (and well, classes and metaclasses are both objects).
This response to the same question in lamba the ultimate seems to me like a perfect explanation.
Types in C, like Int Float, char etc define data that can be acted on with specific methods that can operate on them. It's no more complicated than that. Like for int I can add, subtract multiply and maybe divide. Those are my methods (or operations) for int. A Class is simply a definition of a new type. I first define what the data looks like. Maybe its a single bit. Maybe it's two words like a complex with a real and imaginary part. Or maybe its this complex thingy with 309734325 bytes representing the atomic makeup of a weird particle on Jupiter. I don't care. Just like an integer, I get to make up the operations I can do with this new data type. In the case of the integer I had add, subtract, etc. With this new data type I can define whatever operations I think make sense. They might be add subtract etc. but they may add other things. These are whatever methods I decide to add to my class.
The bottom line is that with a type in C, you have a definition of what the data is, ie; a byte, word, float, char etc. But any of these also implies what operations are legal and will produce reliable results.
A class is no different except it is up to you to define the interface and acceptable operations. The class defines these things and when you instantiate it in an Object it defines the behavior of the object just like a type definition defines the behavior of an integer when you operate on it.
Classes just give you the flexibility to define new types and everything about how they operate.
Once this is defined, every time I instantiate an object of class "thingy", it has the data structure I defined and the operations (methods) that I said you can do with it. The class "thingy" is clearly nothing more or less than a new type that C++ lets me define.
Type generally refers to the classification of primitive values - integers, strings, arrays, booleans, null, etc. Usually, you can't create any new types.
Class refers to the named set of properties and methods which an object is associated with when it is created. You can usually define as many new classes as you want, although some languages you have to create a new object and then attach methods to it.
This definition is mostly true, but some languages have attempted to combine types and classes in various ways, with various beneficial results.
Types and classes are related but not identical. My take is that classes are used for implementation inheritance, whereas types are used for runtime substitution.
Here is a link explaining the substitution principle and why subclasses and subtypes are not always the same thing (in Java for example). The wikipedia page on covariance and contravariance has more information on this distinction.
In langugages like Haskell, the concept of Class doesn't exist. It only has Types. (And Type Class. Not to be confused with Class, Type Class is more of an abstracted version of Type).
Monad is a Type Class.
class Monad m where
(>>=) :: m a -> ( a -> m b) -> m b
(>>) :: m a -> m b -> m b
return :: a -> m a
fail :: String -> m a
From a (pure) functional programming perspective, Type is more fundemental than Class as one can trace its root to Type Theory (e.g. from a PTL perspective, lambda calculus with types and without types behave quite differently), while Class is really just a construct to enable OO.
In languages that only support Type and don't support Class, functions are often treated as first-class citizen.
Meanwhile, when a language makes a distinction between Type and Class, functions are more of a second-class citizens that can be attached to Objects, etc. And yup, often you can attach a function onto a Class itself (aka a static function).
Interesting question. I think aku's answer is spot on. Take the java ArrayList class as an example
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
An instance of the ArrayList class is said to be of type of every superclass it extends and every interface it implements. Therefore, an instance of the ArrayList class has a type ArrayList, RandomAccess, Cloneable, and so forth. In other words, values (or instances) belong to one or more types, classes define what these types are.
Different classes may describe the same type.
Type consists of these parts:
Operations = syntax
Description of operations = semantics
Class consists of these parts:
Operations = syntax
Implementation (= various implementations describe same semantics)
Some notes:
Interface (as in Java) is not type, because it does not describe semantics (describes only syntax)
Subclass is not subtype, because subclass may change semantics defined in superclass, subtype cannot change supertype semantics (see Liskov Substitution Principle, e.g. this LSP example).
Obviously, as there are languages with type system that are not OO programming languages, type must be a broader concept than class
Even in languages like Java, int is a (primitive) type, but not a class.
Hence: every class is a type, but not every type is a class.
If we think to this question in C# context, we reach bellow answer.
C# type system is divided into following categories:
Value types:
Simple types: like int, long, float, etc.
Enum types
Struct types
Nullable types
Reference types:
Class types
Interface types
Array types
Delegate types
As you can see there are many types in C# which Class is only one of them.
There is just one important note:
C#’s type system is unified such that a value of any type can be treated as an object. Every type in C# directly or indirectly derives from the object class type, and object is the ultimate base class of all types. Values of reference types are treated as objects simply by viewing the values as type object. Values of value types are treated as objects by performing boxing and unboxing operations.
so as I see, type is an umbrella over many items which class is one of them.
Referece: CSahrp Language Specification doc, page 4
This was a good question for me, which made me think hard. I would dare to say that Class is a compiletime thingy and Type is a runtime thingy. I say this because you write classes not types. The compiler then creates types from classes, and the runtime use types to create instances of objects.
types are programming constructs that helps the compiler to perform type checking and ensure that the variables have the right properties for an operation.
classes are user defined types that an objects or variables referencing them could have. These are also subjected to type checking.