Wrox Programmer Forums
Go Back   Wrox Programmer Forums > .NET > Other .NET > General .NET
| Search | Today's Posts | Mark Forums Read
General .NET For general discussion of MICROSOFT .NET topics that don't fall within any of the other .NET forum subcategories or .NET language forums.  If your question is specific to a language (C# or Visual Basic) or type of application (Windows Forms or ASP.Net) try an applicable forum category. ** PLEASE BE SPECIFIC WITH YOUR QUESTION ** When posting here, provide details regarding the Microsoft .NET language you are using and/or what type of application (Windows/Web Forms, etc) you are working in, if applicable to the question. This will help others answer the question without having to ask.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the General .NET section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old July 24th, 2008, 04:21 PM
Authorized User
 
Join Date: Jun 2008
Location: , , .
Posts: 75
Thanks: 15
Thanked 0 Times in 0 Posts
Default I have a question re: Oject Oriented Programming

I am very new to OOP. Therefore I thought I would do extensive research on this topic especially if I plan to make my living from now on programming using the .Net Framework. Well I was reading an article concerning Object Oriented Programming and it stated that most developers do not make their fields public as it makes the class easy to break and violates encapsulation. Instead, they use properties or methods to manipulate private or protected fields and ensure that the fields never have an illegal value. My question is encapsulation only about hiding data, and is that the only reason why we use objects? Also is the only reason why classes have properties is for data access? And when answering these questions please be as long winded as possible with real world examples, no paraphrasing please. One more thing before the light turns green I was wondering does any one no of a really really GOOD book to increase my understanding of OOP. Thanks In Advance for Any assistance provided.

 
Old July 24th, 2008, 04:51 PM
Imar's Avatar
Wrox Author
Points: 70,322, Level: 100
Points: 70,322, Level: 100 Points: 70,322, Level: 100 Points: 70,322, Level: 100
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Hi there,

No, properties are not only about hiding data; they are also about about hiding implementation and validation. Consider this field:

public string EmailAddress;

What happens when you have this field on a Person class and set it to an illegal value:

myPerson.EmailAddress = "http://www.somesite.com";

Since the field is a string, and the URL is also a string, you can never check its value when it's set and reject its value when necessary. Now consider this property:
Code:
private string _emailAddress;
public string EmailAddress
{
  get { return _emailAddress; }
  set
  {
    if (!ValidateEmailAddress(value))
    {
      throw new ArgumentException("Email is not valid.")
    }
    _emailAddress = value;
  }
}
This allows the class to protect its data when it receives an invalid value. (Note the ValidateEmailAddress method is fictitious and check a string to see if it contains a valid e-mail address)

Also, properties allow you to combine data, or add logic to them. Consider a FullName property of a Person:
Code:
public string FullName
{
  get { return string.Format("{0} {1}", _firstName, _lastName); }
}
The FullName property, implemented as read-only, returns a combination of other fields. By making it read-only you can avoid calling code from setting the value directly; something you cannot do with a public field.

It's also perfectly OK to have properties for classes that have nothing to do with data access. The FullName is a good example; it uses derived data and is never stored in a database itself; instead only the first name and last name are stored in the database. But, other than that, there are many other situations where properties make a lot of sense, even if they don't deal with data access. For example, configuration settings, calculations, collections etc are all useful without the need for a database.

This is just the tip of the iceberg. Google for .NET properties and you'll find many useful articles, including this one

http://www.c-sharpcorner.com/UploadF...rtiesInCS.aspx

Tip of the day: add some line breaks to your posts here and there; makes it much easier to read and understand for others.

Hope this helps,

Imar


---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of Beginning ASP.NET 3.5 : in C# and VB, ASP.NET 2.0 Instant Results and Dreamweaver MX 2004
Want to be my colleague? Then check out this post.
 
Old July 24th, 2008, 05:33 PM
Friend of Wrox
 
Join Date: Jun 2008
Location: Snohomish, WA, USA
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

To try to not write my own treatise, I thought I'd see what Wikipedia has to say:
http://en.wikipedia.org/wiki/Encapsu...-_computers%29

I think that this sentence from that article expresses my own feelings on the subject just about perfectly:
Not all agree on the distinctions between the two though one can think of information hiding as being the principle and encapsulation being the technique.


So, now let's tackle your specific questions:

is encapsulation only about hiding data

No. It's also about data *safety*. Just for instance, suppose that you have a value that *must* be in the range of 0 through 9, integers only. In most languages, there's no good way to express that limitation (Pascal being a notable exception). So, instead, you do it via encapsulation:
Code:
    Public Property rating( ) As Integer
        Set( r As Integer )
            If r < 0 OrElse r > 10 Then
                Throw New RatingOutOfRangeException("Rating " & r & " is invalid")
            End If
            mRating = rating
        End Set
        ...
    End Property


Also, No. It's about hiding of *implementation*. If the class wants to derive a "property" from various internal elements without disclosing how the elements are connected.
Code:
    Public Property price() As Double
        Get
           Return 100.0 + 200.0 * RND() ' random price from 100 to 300 dollars
        End Get
    End Property


You say you have a boolean data member of your class and it's fine for it to be either True or False and you don't care which? So why make it a property? Why not just make it a public data member?

Realistically, no good reason not to. Though certain OO purists would shoot me for saying so. <shrug>Let them.</shrug>

*************

and is that the only reason why we use objects?

Oh, my goodness no! In fact, nobody even said you HAVE to use properties! You could just as easily use standard *METHODS* and forget all about properties, per se. (Though many would argue that I'm just changing the implementation; the hidden data is still the key to it all. Hard to say they are wrong.)

No, in my own mind, the strongest reason to use classes (objects) is Polymorphism. A completely different *KIND* of "hiding". The ability to hide the fact that two objects are COMPLETELY DIFFERENT under the covers and yet, from certain points of view, have all the same capabilities (including properties).

Don't get me wrong, there are tons of other reasons to use objects. Just the ability to have data and code tightly coupled is almost enough, alone, to make me want to use them. In non-OO languages, there's no easy way to say "this price value is associated with that invoice item" or "the profit on this item is ITS OWN price minus ITS OWN cost." That is, the data is grouped, the code is grouped, it's all a single unit.

Don't get all hung up on properties. As Wikipedia said, they are only *ONE* technique used in OO programming.

*****************

Also is the only reason why classes have properties is for data access?

First of all, remember that any public data member of a class *IS* a property of that class! (Technically, even the private ones are class properties; they just aren't accessible outside the class.)

So are you using the term "properties" here to mean *all* properties or only encapsulated properties??

Not that it matters, in the end.

Given that a property--either data member or a method encapsulating a property--either accepts or returns a data value, what else COULD they be used for? You can shove data in. You can pull data out.

But, to be fair, there's no reason that the implementation of an encapsulated property can't have "side effects". Just as a for instance, maybe the 137th time you ask for the score of a given football game, where the game is implemented as an object, the method sends an email to your boss telling him you are only playing games. Rotten OO design, no doubt, but perfectly legal.

So "only reason" may be too strong, but "general reason" would certainly be true.

**********************

I see that Imar has also answered you. I should have refreshed the page before posting. Still, you'll note that we both say pretty much the same thing.

My gut feeling is that you are concentrating on unimportant parts of OO programming. Oh, not that they don't have important uses and reasons for being and and and... But I think that understanding the makeup of classes, the whole reason for using them in the first place, is where you need to start.

I'm not sure what to point you at. My own learning experience began 17 or 18 years ago with a copy of the original C++ book from Stroustrup. His attitude was pretty much "well, if you don't see the point of doing OO programming, then why should I tell you?" So it's pretty much been a bunch of self-teaching from there.

Wait until you discover generic classes ("templated classes" in C++). They first appeared after I started learning C++. In my never as humble as it should be opinion, *THEY* are what makes a given OO language viable in the market. When VB.NET and C# appeared without them, I wasn't convinced they would matter in the long run. Thankfully, we now have generics, and reasonbly well implemented, to boot. Generics and polymorphism. And go rule the world.




Similar Threads
Thread Thread Starter Forum Replies Last Post
Object Oriented Programming jgrant C# 2005 0 March 16th, 2007 03:04 AM
Object oriented programming with VB6 james gold Pro VB 6 3 September 27th, 2003 02:31 PM
Object oriented programming with VB6 james gold VB How-To 2 September 23rd, 2003 09:29 AM
Object oriented programming with VB6 james gold Beginning VB 6 3 September 18th, 2003 02:56 PM
Object Oriented VB6 programming and DAO warthog Pro VB Databases 0 June 19th, 2003 08:35 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.