CSC/ECE 517 Fall 2012/ch1 1w51: Difference between revisions
No edit summary |
No edit summary |
||
(46 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
=Introduction= | =Introduction= | ||
It is often that we talk about classes and types in the context of a programming language. A programming language can be a strongly typed language or non-typed language with respect to its classes Every programming language has a way to define a variable which can be an object of a class. A variable is a named address location which stores a particular value. Now a class of an object (variable) defines the internal state and implementation details of the object whereas the type of the object define the behaviour of the object. Let us look into the concepts of classes and types in more detail. | It is often that we talk about classes[http://en.wikipedia.org/wiki/Classes_(computer_science)] and types in the context of a programming language[http://en.wikipedia.org/wiki/Programming_language]. A programming language can be a strongly typed language or non-typed language with respect to its classes Every programming language has a way to define a variable which can be an object[http://en.wikipedia.org/wiki/Object_(computer_science)] of a class. A variable[http://en.wikipedia.org/wiki/Variable_(computer_science)] is a named address location which stores a particular value. Now a class of an object (variable) defines the internal state and implementation details of the object whereas the type of the object define the behaviour of the object. Let us look into the concepts of classes and types in more detail. | ||
= Types = | = Types = | ||
Let us explain the concept of a type and class using an analogy. Imagine a variable to be a vacant house. It could have animals, humans, robots, or another smaller house..There should be a way, from a third party perspective, so as to be cognizant of the kind of things that reside in the house. So in this case the house is the class and the thing (one of many possible) residing inside the house is type of the class i.e. house. A typed language or a strongly typed language is one where the type of a variable has to be declared so as to avoid any wrong dealings of the value during run time. Here, values are restricted from performing certain operations based on the different data types assigned. | Let us explain the concept of a type and class using an analogy. Imagine a variable to be a vacant house. It could have animals, humans, robots, or another smaller house..There should be a way, from a third party perspective, so as to be cognizant of the kind of things that reside in the house. So in this case the house is the class and the thing (one of many possible) residing inside the house is type of the class i.e. house. A typed language or a strongly typed language is one where the type of a variable has to be declared so as to avoid any wrong dealings of the value during run time. Here, values are restricted from performing certain operations based on the different data types assigned<ref>http://en.wikipedia.org/wiki/Strong_typing</ref>. For example, Consider the strongly typed language - Java[http://en.wikipedia.org/wiki/Java_(programming_language)]. If I need to use two integers for addition, I would explicitly have to mention them as an integer as shown in the below example. | ||
int integer1; | int integer1; | ||
int integer2; | int integer2; | ||
However, we can’t then re-initialize the declared integer variables to any other type in its defined scope. The following example throws an error, since we are trying to assign a string type to the integer variable. | However, we can’t then re-initialize the declared integer variables to any other type in its defined scope. The following example throws an error, since we are trying to assign a string type to the integer variable. | ||
integer1 = “Hello World”; // cannot map an int to a String | integer1 = “Hello World”; // cannot map an int to a String | ||
In the case of non-typed languages or weakly typed languages such as Ruby | In the case of non-typed languages or weakly typed languages such as Ruby[http://en.wikipedia.org/wiki/Ruby_(programming_language)], Visual Basic, etc, we don’t need to explicitly specify the type of the variable being declared. Consider the example shown below. | ||
def variable1; | def variable1; | ||
def variable2; | def variable2; | ||
Now, the above defined variables, could be initialized with any type of data. Hence, weakly typed languages are less restrictive | Now, the above defined variables, could be initialized with any type of data. Hence, weakly typed languages are less restrictive<ref>http://en.wikipedia.org/wiki/Weak_typing </ref> mainly because they support changing one data type to another implicitely [http://en.wikipedia.org/wiki/Implicit_type_conversion#Implicit_type_conversion] . The reason could also be that they support ad-hoc polymorphism where a uniform interface takes care of different data types assigned during run time.<ref>http://en.wikipedia.org/wiki/Polymorphism_(computer_science) </ref>. Sometimes both implicit conversion and ad-hoc Polymorphism[http://en.wikipedia.org/wiki/Polymorphism] are supported. Now let us assign different values for the defined variables. | ||
variable1 = 3 | variable1 = 3 | ||
as well as | as well as | ||
variable1 = “Good morning Vietnam” | variable1 = “Good morning Vietnam” | ||
The above example shows that the variable1 can be assigned values of different types. | The above example shows that the variable1 can be assigned values of different types. | ||
= Classes= | = Classes= | ||
A class is a blueprint from which its instances can be created | A class is a blueprint from which its instances can be created. A class contains data field members to maintain the state and methods to define the desired behaviour of the class.<ref>http://en.wikipedia.org/wiki/Class_(computer_programming) </ref> The basic difference between a class and a regular primitive type is that a class: | ||
1. consists of one or more primitive or non-primitive variables. | 1. consists of one or more primitive or non-primitive variables. | ||
2. is a pre-defined structure. | 2. is a pre-defined structure. | ||
3. defines methods which operate on the internal state of the object. | 3. defines methods which operate on the internal state of the object. | ||
The Type of Class is “Class”, just like the Type of integer is “integer” in case of strongly typed languages. | The Type of Class is “Class”, just like the Type of integer is “integer” in case of strongly typed languages. | ||
In case of Java:- | In case of Java:- | ||
“The types of the Java programming language are divided into two categories: primitive types and reference types. The primitive types are the boolean type and the numeric types. The numeric types are the integral types byte, short, int, long, and char, and the floating-point types float and double. The reference types are class types, interface types, and array types. There is also a special null type. An object is a dynamically created instance of a class type or a dynamically created array. The values of a reference type are references to objects. All objects, including arrays, support the methods of class Object. String literals are represented by String objects.” | “The types of the Java programming language are divided into two categories: primitive types and reference types. The primitive types are the boolean type and the numeric types. The numeric types are the integral types byte, short, int, long, and char, and the floating-point types float and double. The reference types are class types, interface types, and array types. There is also a special null type. An object is a dynamically created instance of a class type or a dynamically created array. The values of a reference type are references to objects. All objects, including arrays, support the methods of class Object. String literals are represented by String objects.”<ref>http://www.khelll.com/blog/ruby/ruby-reflection/ </ref> | ||
Now, let us look at 2 data types available in Java. They are: | Now, let us look at 2 data types available in Java. They are: | ||
i. Primitive Types. | i. Primitive Types. | ||
ii. Reference Types. | ii. Reference Types. | ||
Classes, Interfaces, Arrays are all consolidations of Primitive types, so they just need to “point” to or reference the primitive ones, hence the name. It is sometimes confusing and difficult to come up with a clear and robust distinction between Types and Classes. One might think "Class to be a Type of Type". It is, however, important to know that in strict Object Oriented Languages, Type is a union of Classes and Primitives. | Classes, Interfaces, Arrays[http://en.wikipedia.org/wiki/Array_data_structure] are all consolidations of Primitive types, so they just need to “point” to or reference the primitive ones, hence the name. It is sometimes confusing and difficult to come up with a clear and robust distinction between Types and Classes. One might think "Class to be a Type of Type". It is, however, important to know that in strict Object Oriented Languages[http://en.wikipedia.org/wiki/Object-oriented_programming], Type is a union of Classes and Primitives. | ||
Let us look into the types and classes in few different languages defined below: | Let us look into the types and classes in few different languages defined below: | ||
Line 38: | Line 38: | ||
==Ruby== | ==Ruby== | ||
Ruby claims to be a strong object oriented language | Ruby claims to be a strong object oriented language<ref>http://www.ruby-doc.org/docs/ProgrammingRuby/</ref>. It is object oriented to the extent that every thing is an object. Primitive datatypes are objects, and we can make use of the object oriented techniques,even on primitive data types.. As mentioned before, Ruby is a dynamic typed language, as the type is bound at compile time. Everything in Ruby has a class. Every class in Ruby is inherited from class Class. | ||
Type in Ruby is well defined as well. Using self inspection ( | Type in Ruby is well defined as well. Using self inspection [http://en.wikipedia.org/wiki/Reflection_(computer_programming)], we can find out information about a class or object, during run time. Let us see this in action. | ||
In the below example, as we can see, the “class” of number “5” is Fixnum and class of string “hello” is String. | In the below example, as we can see, the “class” of number “5” is Fixnum and class of string “hello” is String. | ||
5.class #=> Fixnum | 5.class #=> Fixnum | ||
"hello".class #=> String | "hello".class #=> String | ||
But have you thought of your class as an object? Well that seems odd, but that’s how ruby works: | But have you thought of your class as an object? Well that seems odd, but that’s how ruby works: | ||
5.class #=> Fixnum | 5.class #=> Fixnum | ||
class Foo;end #=> nil | class Foo;end #=> nil | ||
Foo.class #=> Class | Foo.class #=> Class | ||
What does the above snippet of code mean exactly? It means 2 things : Foo is a constant and that constant holds(refers to) an object of type “Class”.Let us prove that in the following example. | What does the above snippet of code mean exactly? It means 2 things : Foo is a constant and that constant holds(refers to) an object of type “Class”.Let us prove that in the following example. | ||
Foo = Class.new | Foo = Class.new | ||
(irb):8 warning: already initialized constant Foo | (irb):8 warning: already initialized constant Foo | ||
=> Foo | => Foo | ||
As we can see, we received a warning because we tried to initialize the constant Foo again. | As we can see, we received a warning because we tried to initialize the constant Foo again. | ||
Therefore ,when we define some class ‘Foo’ in ruby, we are mainly doing the following:: | Therefore ,when we define some class ‘Foo’ in ruby, we are mainly doing the following:: | ||
1. Instantiating an object of type Class. | 1. Instantiating an object of type Class. | ||
2. Initializing the constant Foo that refers to that created object . | 2. Initializing the constant Foo that refers to that created object . | ||
Hence, when we say “object” ,then we do mean any object; an object of Class type, or any object of any type. | Hence, when we say “object” ,then we do mean any object; an object of Class type, or any object of any type.<ref>http://www.khelll.com/blog/ruby/ruby-reflection/ </ref> | ||
==Java== | ==Java== | ||
Line 62: | Line 62: | ||
* Primitive Types:- boolean and numeric. The numeric types are the integral types byte, short, int, long, and char, and the | * Primitive Types:- boolean and numeric. The numeric types are the integral types byte, short, int, long, and char, and the | ||
floating-point types float and double. | floating-point types float and double. | ||
* Reference Types:- class types, interface types and array types. | * Reference Types:- class types, interface types and array types. <ref>http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html </ref> | ||
Java is an object-oriented language, but it does make a clear distinction between the primitive type and Classes. The data types i.e. int, float, char etc. are primitive data types , and the data types, other than the primitives are references. It is an interesting distinction to note, because of the differences in in the way methods are called in different languages. Java makes a distinction by using "call-by-value" when a primitive data types are passed as parameters, and using "call-by-reference" when objects are passed. In fact, if a primitive data type is passed, a call-by-value is invoked, but when a Class object is passed, only a reference is passed to the object. | Java is an object-oriented language, but it does make a clear distinction between the primitive type and Classes. The data types i.e. int, float, char etc. are primitive data types , and the data types, other than the primitives are references. It is an interesting distinction to note, because of the differences in in the way methods are called in different languages. Java makes a distinction by using "call-by-value" when a primitive data types are passed as parameters, and using "call-by-reference" when objects are passed. In fact, if a primitive data type is passed, a call-by-value is invoked, but when a Class object is passed, only a reference is passed to the object. | ||
For a more language specific treatment of types and classes, you can refer: http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2007/wiki2_6_ap | For a more language specific treatment of types and classes, you can refer: [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2007/wiki2_6_ap] | ||
Discussion of Issues | =Discussion of Issues= | ||
Now, the question is, how do we make a choice between primitive data types and Class? | Now, the question is, how do we make a choice between primitive data types and Class? | ||
There are several features that each of the types provide. The decision is hard to make. Let us look into the advantages and disadvantages of each of the data types. | There are several features that each of the types provide. The decision is hard to make. Let us look into the advantages and disadvantages of each of the data types. | ||
Line 79: | Line 79: | ||
3. Perform the required calculation. | 3. Perform the required calculation. | ||
4. Return the result. | 4. Return the result. | ||
It is important to note that the primitive types themselves are left unchanged, and the result is returned from the operation, giving the programmer the ability to place the result elsewhere. | It is important to note that the primitive types themselves are left unchanged, and the result is returned from the operation, giving the programmer the ability to place the result elsewhere.<ref>http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html</ref> | ||
Line 87: | Line 87: | ||
== Disadvantages== | == Disadvantages== | ||
===Single-state storage=== | ===Single-state storage=== | ||
One of the biggest disadvantages of primitive types is that, they are generally capable of only holding a single dimension state. | One of the biggest disadvantages of primitive types is that, they are generally capable of only holding a single dimension state.<ref>http://www.sitepoint.com/beginning-java-data-types-variables-and-arrays/ </ref> This limitation requires the programmer to use other variables in conjunction if they desire to hold more than one field of data. | ||
===Refactoring=== | ===Refactoring=== | ||
Since primitive types do not allow you to encapsulate your data, if you ever desire to change the behavior of your program, you are forced to manually check each use of the variable for enforcement. | Since primitive types do not allow you to encapsulate your data, if you ever desire to change the behavior of your program, you are forced to manually check each use of the variable for enforcement. | ||
For example, suppose you have a system designed in Java that maintains an integer value to represent the number of books you have in a library. | For example, suppose you have a system designed in Java that maintains an integer value to represent the number of books you have in a library. | ||
int numBooks; | int numBooks; | ||
... | ... | ||
numBooks = 0; | numBooks = 0; | ||
... | ... | ||
numBooks++; | numBooks++; | ||
... | ... | ||
numBooks--; | numBooks--; | ||
... | ... | ||
A few days later, you realize that you should probably refactor your system to maintain a log to capture the updates on this variable. You immediately face a problem since, as it is, your code directly manipulates a single-state type integer. Without resorting to a more object-oriented solution, you would have to update each location in the code, where a change takes place, in order to establish this bookkeeping (pun intended). Example is shown below: | A few days later, you realize that you should probably refactor your system to maintain a log to capture the updates on this variable. You immediately face a problem since, as it is, your code directly manipulates a single-state type integer. Without resorting to a more object-oriented solution, you would have to update each location in the code, where a change takes place, in order to establish this bookkeeping (pun intended). Example is shown below: | ||
public static void integerValueChanged(){ | public static void integerValueChanged(){ | ||
// records that the value has been changed | // records that the value has been changed | ||
... | ... | ||
} | } | ||
public static void main(String[]args){ | |||
public static void main(String[]args){ | |||
int numBooks; | int numBooks; | ||
... | ... | ||
Line 118: | Line 117: | ||
integerValueChanged(); | integerValueChanged(); | ||
... | ... | ||
} | } | ||
To generalize this concept, it is often necessary, to modify "what happens" when something is updated, and this cannot be easily accomplished by merely using primitive types. | To generalize this concept, it is often necessary, to modify "what happens" when something is updated, and this cannot be easily accomplished by merely using primitive types. | ||
Line 128: | Line 127: | ||
Oftentimes, it is necessary to refactor a system. to execute the code when a change happens. In object-land, we are able to do this through the ability to control what happens in our methods. | Oftentimes, it is necessary to refactor a system. to execute the code when a change happens. In object-land, we are able to do this through the ability to control what happens in our methods. | ||
Taking our example from above, we can give a quick example of how a class could be defined to handle the situation much more elegantly. | Taking our example from above, we can give a quick example of how a class could be defined to handle the situation much more elegantly. | ||
public class RecordedNumber{ | public class RecordedNumber{ | ||
// The integer value, kept concealed in the class | // The integer value, kept concealed in the class | ||
private int value; | private int value; | ||
public RecordedNumber(int value){ | public RecordedNumber(int value){ | ||
this.value = value; | this.value = value; | ||
} | } | ||
public int getValue(){ | public int getValue(){ | ||
return value; | return value; | ||
} | } | ||
public void setValue(int newValue){ | public void setValue(int newValue){ | ||
// code to do any necessary recording. | // code to do any necessary recording. | ||
Line 145: | Line 141: | ||
this.value = newValue; | this.value = newValue; | ||
} | } | ||
} | } | ||
public class MyExample{ | public class MyExample{ | ||
public static void main(String[]args){ | public static void main(String[]args){ | ||
RecordedNumber numBooks = new RecordedNumber(0); | RecordedNumber numBooks = new RecordedNumber(0); | ||
Line 157: | Line 153: | ||
===Code-reuse=== | ===Code-reuse=== | ||
Another useful feature of class-types, is the encapsulation of the concept of code re-usability, especially in topics such as inheritance. | Another useful feature of class-types, is the encapsulation of the concept of code re-usability, especially in topics such as inheritance.<ref>http://www.javaworld.com/javatips/jw-javatip107.html </ref> Classes allow the programmer to enhance an already existing class-type and to make it more specific with additional features. This helps prevent excessive code duplication. | ||
===Application Structure=== | ===Application Structure=== | ||
Line 167: | Line 163: | ||
===Complexity=== | ===Complexity=== | ||
Oftentimes one doesn't need the functionality provided by classes to handle the problem they are trying to solve. Consequently, such an unnecessary use, over-complicates the principle design and may add unnecessary burden to maintain the code. This is more so geared towards small-programs where objects and classes may not be the best fit for their implementation. Examples of this situation vary, since it is highly opinionated, but are more so an example of bad design in an object-oriented sense: to quote Albert Einstein, "Everything should be made as simple as possible, but no simpler." | Oftentimes one doesn't need the functionality provided by classes to handle the problem they are trying to solve. Consequently, such an unnecessary use, over-complicates the principle design and may add unnecessary burden to maintain the code. This is more so geared towards small-programs where objects and classes may not be the best fit for their implementation. Examples of this situation vary, since it is highly opinionated, but are more so an example of bad design in an object-oriented sense: to quote Albert Einstein, "Everything should be made as simple as possible, but no simpler." | ||
=See Also= | |||
*Refactoring [http://en.wikipedia.org/wiki/Refactoring] | |||
*Code Reuse [http://en.wikipedia.org/wiki/Code_reuse] | |||
*Java[http://en.wikipedia.org/wiki/Java_(programming_language)] | |||
*Ruby[http://en.wikipedia.org/wiki/Ruby_(programming_language)] | |||
=References= | =References= | ||
<references /> | |||
Latest revision as of 02:05, 11 October 2012
Introduction
It is often that we talk about classes[1] and types in the context of a programming language[2]. A programming language can be a strongly typed language or non-typed language with respect to its classes Every programming language has a way to define a variable which can be an object[3] of a class. A variable[4] is a named address location which stores a particular value. Now a class of an object (variable) defines the internal state and implementation details of the object whereas the type of the object define the behaviour of the object. Let us look into the concepts of classes and types in more detail.
Types
Let us explain the concept of a type and class using an analogy. Imagine a variable to be a vacant house. It could have animals, humans, robots, or another smaller house..There should be a way, from a third party perspective, so as to be cognizant of the kind of things that reside in the house. So in this case the house is the class and the thing (one of many possible) residing inside the house is type of the class i.e. house. A typed language or a strongly typed language is one where the type of a variable has to be declared so as to avoid any wrong dealings of the value during run time. Here, values are restricted from performing certain operations based on the different data types assigned<ref>http://en.wikipedia.org/wiki/Strong_typing</ref>. For example, Consider the strongly typed language - Java[5]. If I need to use two integers for addition, I would explicitly have to mention them as an integer as shown in the below example.
int integer1; int integer2;
However, we can’t then re-initialize the declared integer variables to any other type in its defined scope. The following example throws an error, since we are trying to assign a string type to the integer variable.
integer1 = “Hello World”; // cannot map an int to a String
In the case of non-typed languages or weakly typed languages such as Ruby[6], Visual Basic, etc, we don’t need to explicitly specify the type of the variable being declared. Consider the example shown below.
def variable1; def variable2;
Now, the above defined variables, could be initialized with any type of data. Hence, weakly typed languages are less restrictive<ref>http://en.wikipedia.org/wiki/Weak_typing </ref> mainly because they support changing one data type to another implicitely [7] . The reason could also be that they support ad-hoc polymorphism where a uniform interface takes care of different data types assigned during run time.<ref>http://en.wikipedia.org/wiki/Polymorphism_(computer_science) </ref>. Sometimes both implicit conversion and ad-hoc Polymorphism[8] are supported. Now let us assign different values for the defined variables.
variable1 = 3
as well as
variable1 = “Good morning Vietnam”
The above example shows that the variable1 can be assigned values of different types.
Classes
A class is a blueprint from which its instances can be created. A class contains data field members to maintain the state and methods to define the desired behaviour of the class.<ref>http://en.wikipedia.org/wiki/Class_(computer_programming) </ref> The basic difference between a class and a regular primitive type is that a class:
1. consists of one or more primitive or non-primitive variables. 2. is a pre-defined structure. 3. defines methods which operate on the internal state of the object.
The Type of Class is “Class”, just like the Type of integer is “integer” in case of strongly typed languages. In case of Java:- “The types of the Java programming language are divided into two categories: primitive types and reference types. The primitive types are the boolean type and the numeric types. The numeric types are the integral types byte, short, int, long, and char, and the floating-point types float and double. The reference types are class types, interface types, and array types. There is also a special null type. An object is a dynamically created instance of a class type or a dynamically created array. The values of a reference type are references to objects. All objects, including arrays, support the methods of class Object. String literals are represented by String objects.”<ref>http://www.khelll.com/blog/ruby/ruby-reflection/ </ref> Now, let us look at 2 data types available in Java. They are:
i. Primitive Types. ii. Reference Types.
Classes, Interfaces, Arrays[9] are all consolidations of Primitive types, so they just need to “point” to or reference the primitive ones, hence the name. It is sometimes confusing and difficult to come up with a clear and robust distinction between Types and Classes. One might think "Class to be a Type of Type". It is, however, important to know that in strict Object Oriented Languages[10], Type is a union of Classes and Primitives. Let us look into the types and classes in few different languages defined below:
Types and Classes in Languages
Ruby
Ruby claims to be a strong object oriented language<ref>http://www.ruby-doc.org/docs/ProgrammingRuby/</ref>. It is object oriented to the extent that every thing is an object. Primitive datatypes are objects, and we can make use of the object oriented techniques,even on primitive data types.. As mentioned before, Ruby is a dynamic typed language, as the type is bound at compile time. Everything in Ruby has a class. Every class in Ruby is inherited from class Class. Type in Ruby is well defined as well. Using self inspection [11], we can find out information about a class or object, during run time. Let us see this in action. In the below example, as we can see, the “class” of number “5” is Fixnum and class of string “hello” is String.
5.class #=> Fixnum "hello".class #=> String
But have you thought of your class as an object? Well that seems odd, but that’s how ruby works:
5.class #=> Fixnum class Foo;end #=> nil Foo.class #=> Class
What does the above snippet of code mean exactly? It means 2 things : Foo is a constant and that constant holds(refers to) an object of type “Class”.Let us prove that in the following example.
Foo = Class.new (irb):8 warning: already initialized constant Foo => Foo
As we can see, we received a warning because we tried to initialize the constant Foo again. Therefore ,when we define some class ‘Foo’ in ruby, we are mainly doing the following:: 1. Instantiating an object of type Class. 2. Initializing the constant Foo that refers to that created object . Hence, when we say “object” ,then we do mean any object; an object of Class type, or any object of any type.<ref>http://www.khelll.com/blog/ruby/ruby-reflection/ </ref>
Java
As mentioned before, Java is a strongly typed language. The type of data needs to be declared before using. The types of "types" in Java are:
* Primitive Types:- boolean and numeric. The numeric types are the integral types byte, short, int, long, and char, and the floating-point types float and double. * Reference Types:- class types, interface types and array types. <ref>http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html </ref>
Java is an object-oriented language, but it does make a clear distinction between the primitive type and Classes. The data types i.e. int, float, char etc. are primitive data types , and the data types, other than the primitives are references. It is an interesting distinction to note, because of the differences in in the way methods are called in different languages. Java makes a distinction by using "call-by-value" when a primitive data types are passed as parameters, and using "call-by-reference" when objects are passed. In fact, if a primitive data type is passed, a call-by-value is invoked, but when a Class object is passed, only a reference is passed to the object. For a more language specific treatment of types and classes, you can refer: [12]
Discussion of Issues
Now, the question is, how do we make a choice between primitive data types and Class? There are several features that each of the types provide. The decision is hard to make. Let us look into the advantages and disadvantages of each of the data types.
Primitive Types
Advantages
Simplicity
In strongly typed languages, primitive types are ideal for data which doesn't necessarily need to be partitioned into several smaller components. If you are looking to store and represent a simple throw-away integer for looping, for example, there's little reason why one would want to construct a class for this throw-away integer purpose. Primitive types are also often coupled with native operations. For example, in Java, variables of type integer, are automatically given operations such as addition, subtraction, multiplication, and so on. In simple terms, these operations work as follows: 1. Receive both inputs required for performing the operation. 2. Cast if necessary (for example, from an integer to a double) 3. Perform the required calculation. 4. Return the result. It is important to note that the primitive types themselves are left unchanged, and the result is returned from the operation, giving the programmer the ability to place the result elsewhere.<ref>http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html</ref>
Efficiency
In efficiency-critical applications, primitive types and their operations are often mapped directly to hardware-supported equivalents, thus operations can be performed very quickly. This style of downgrading the logic to the hardware level has been replaced over the years for general applications, since improvements to hardware components have eradicated the once-imperative necessity to program efficiently. Another point of view concerning efficiency could be from development time: if the program, one is writing doesn't require complex design, it would be quicker to use the language's built-in types instead of taking the time to design a class, to do the same feature.
Disadvantages
Single-state storage
One of the biggest disadvantages of primitive types is that, they are generally capable of only holding a single dimension state.<ref>http://www.sitepoint.com/beginning-java-data-types-variables-and-arrays/ </ref> This limitation requires the programmer to use other variables in conjunction if they desire to hold more than one field of data.
Refactoring
Since primitive types do not allow you to encapsulate your data, if you ever desire to change the behavior of your program, you are forced to manually check each use of the variable for enforcement. For example, suppose you have a system designed in Java that maintains an integer value to represent the number of books you have in a library.
int numBooks; ... numBooks = 0; ... numBooks++; ... numBooks--; ...
A few days later, you realize that you should probably refactor your system to maintain a log to capture the updates on this variable. You immediately face a problem since, as it is, your code directly manipulates a single-state type integer. Without resorting to a more object-oriented solution, you would have to update each location in the code, where a change takes place, in order to establish this bookkeeping (pun intended). Example is shown below:
public static void integerValueChanged(){ // records that the value has been changed ... } public static void main(String[]args){ int numBooks; ... numBooks = 0; integerValueChanged(); ... numBooks++; integerValueChanged(); ... numBooks--; integerValueChanged(); ... }
To generalize this concept, it is often necessary, to modify "what happens" when something is updated, and this cannot be easily accomplished by merely using primitive types.
Class Types
Advantages
Multi-dimensional Storage
Unlike primitive types, classes allow programmers to couple a varying number of fields. Grouping fields of data into a single class, then instantiating such an object and manipulating it is much more convenient than keeping track of several individual variables.
Refactoring
Oftentimes, it is necessary to refactor a system. to execute the code when a change happens. In object-land, we are able to do this through the ability to control what happens in our methods. Taking our example from above, we can give a quick example of how a class could be defined to handle the situation much more elegantly.
public class RecordedNumber{ // The integer value, kept concealed in the class private int value; public RecordedNumber(int value){ this.value = value; } public int getValue(){ return value; } public void setValue(int newValue){ // code to do any necessary recording. ... this.value = newValue; } }
public class MyExample{ public static void main(String[]args){ RecordedNumber numBooks = new RecordedNumber(0); ... numBooks.setValue(4); // the object handles all necessary bookkeeping ... }
}
Code-reuse
Another useful feature of class-types, is the encapsulation of the concept of code re-usability, especially in topics such as inheritance.<ref>http://www.javaworld.com/javatips/jw-javatip107.html </ref> Classes allow the programmer to enhance an already existing class-type and to make it more specific with additional features. This helps prevent excessive code duplication.
Application Structure
Designing an application in an object-oriented / class-specific style can reduce the challenges of designing and building a difficult system into merely making objects successfully interact. It is from this concept that languages such as Unified Modeling Language (UML) have been created, allowing software engineers to build around the notion of classes and their relationships to one another.
Disadvantages
Speed Considerations
In computational-intensive applications, objects built from classes tend to be less efficient than primitive data types built around procedural context. This is due in part because of the object's creation, since it isn't supported directly at hardware level. Consideration is placed more so on good-design and coding-practices when implementing functionality around classes.
Complexity
Oftentimes one doesn't need the functionality provided by classes to handle the problem they are trying to solve. Consequently, such an unnecessary use, over-complicates the principle design and may add unnecessary burden to maintain the code. This is more so geared towards small-programs where objects and classes may not be the best fit for their implementation. Examples of this situation vary, since it is highly opinionated, but are more so an example of bad design in an object-oriented sense: to quote Albert Einstein, "Everything should be made as simple as possible, but no simpler."
See Also
References
<references />