OOP: What is the correct terminology for talking about methods and attributes? Both of classes, and their instances? [closed] - oop

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Say I have a class in a programming language:
class name {
variable_name = 1;
method_name(x) {
// return something
}
}
foo = new name();
print(foo.method_name(foo.variable_name));
How correct is the following? Can we make it more correct?
If I want to talk about a specific instance of a method (foo.method_name), would I say 'the method_name-method of the object foo'? Or something else? Or does talking about the instance of a variable of method make no sense?
If I want to talk about a general object of any name, and refer to its method_name-method or variable, what would I say? Would I say 'the method_name-method/variable_name-variable of the class name?' or something else?
Thank you for your time.
Kind regards,
Marius

Talking about a specific instance of a method doesn't really make any sense as you say. Usually we talk about instances of classes - objects - and their methods. Thus one would normally talk about something like "calling method_name on foo" or simply foo dot method_name.
That's a fine way of saying it. In my experience it doesn't really matter all that much in day to day communication as the method really does the same thing anyways, just with different values in it's scope. It's what it does that really matters (e.g. accelerate() or toString()). Perhaps the most important part when talking about methods, variables etc. is communicating clearly if they happen to be static - i.e. not belonging to any given instances. In day to day speak I wouldn't make any effort to differentiate very clearly between "then we can just call accelerate on our car instance" and "the car class has a method named accelerate" (it's given that this is a non-static method) - I might however specify that "our car class has a static method to help us calculate acceleration.

In a nutshell:
Classes: (which may be instantiated to objects)
can have -
(non-static / instance) members
- public
- methods
- properties
- private
- methods
- properties
(static / class) members
- public
- methods
- properties
- private
- methods
- properties
However, methods have/can also be called messages, selectors, or behaviours (depending on the language in question, and in particular contexts.) It's occasionally considered incorrect to call them functions, however no one in their right mind should take you to task over such things. (notably the appearance of the keyword function in ECMAScript shows its level of acceptability. As a rule of thumb, the language domain would always define correctness, otherwise generally the term is fine/understandable but can lead to ambiguity.) Similarly properties are variously called, fields, attributes or variables.
An alternative name for non-static methods or properties is to call them instance methods or properties. While static methods / properties may be referred to as class methods / properties. By the way, ommitting the non-static qualifier, is usual and implicit.
As a general guideline, refer to the language under use to determine the correct terms, as they are specific to the various language cultures.
The assumption in writing this, is that there's no need to outline the scope/access differences of these class members. If that's required, I'd be happy to add a note.

Related

Having problems understanding OOP. Public members or getters and setters? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
i'm trying to learn OOP and i did read a lot of topics about OOP but I still don't fully grasp the concepts.
I'm asking for some clarification regarding that matter, in particular:
Is it fine to have public members in a class, or should I always use getters and setters?
OOP or Object Oriented Programing is a paradigm (method) of writting programs. Basically, it simplifies creating programs by considering everything as an object represented by classes.
The basic concepts of OOP (applies for all languages) are clear:
Inheritance: Object A (or class) is able to inherit from another object, let's say Object B. That means that Object A, in this case the child, will inherit the attributes and methods of object B which is in this case the parent. This concepts means that you can re-use your code.
Polymorphism: As the name indicates, it means than an object, more specifically, a method can take several forms. How? This concept goes with Inheritance. Say you have a parent class that is Animalthat has a method called talk() that prints some text, and you have two child classes respectively called dog and cat. Both child classes would inherit the method talk() from their parent class being Animal. Both dogs and cats are Animals, but they do not talk the same way. To solve this, we would re-define the method talk()in the child classes using the concept of polymorphism without needing to changing the method's name or signature.
Encapsulation: Last, understanding this concept should answer question 2 and 3. Basically, this means that each object or class will contain inside its own members (which provide data) and methods (which provide data manipulation). With this, what you are doing is binding the data with the methods in one container being the object. For example, let's take an Air Conditioner AC for short. An AC has attributes, let's say: make, model, isOn, temperature. Additionally, it encapsulates methods to manipulate the temperature: tempDown() and tempUp() to lower and raise the temperature by one degree.
What you need to understand here that, the AC's methods to lower or raise the temperature are already built inside it. It is not us people who lower or raise the temperature, sure we do press the button but that only triggers the method that does that. The functionalities themselves are build inside the AC not outside it, that is to say that the methods that manipulate the AC should be encasulated inside the AC. The attributes on the other side are supposed to be private by concept. The AC's attributes, for example the temperature, belongs to the AC itself, it should not be public. It is bad practice to set a class' attributes as public because it defies the encapsulation concept. And so only the methods encapsulated with the attributes should have access to them. If you need to edit the attributes of an object from outside the class, you can create a method that does that for you. Methods are public.
At last, regarding the use of getters and setters, there are a lot of debates about the subject, some even describe them as "Evil". If you create methods just to access the class attributes, you might as well just set them as public and spare yourself the extra lines of code. Some languages even have better ways to manage members like using properties in Python. Like I said before, attributes should remain private and should only be edited/accessed by the object itself, not from the outside. The way to do that is via the methods that will manipulate them. For example, let's say you have a bank account that has an attribute : balance. If you were to set the attributes as public or have getters/setters, it means anyone can access your balance from outside the class and change it to whatever value they like. On the other side, if you had the attributes private, the class decides what sort of data manipulations you can have via the methods. A method that would only print the balance, or that would only add money if it is extracted from another account, you can even add an extra layer of secury via logging each action inside each method.
You can add Abstraction (basically separating the declaration and implementation of code through interfaces) and Overloading to the mix. You can read more information here :
https://www.tutorialspoint.com/cplusplus/cpp_object_oriented.htm

When is a class too big? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I tend to create very large classes that have 30-40 (or more) methods. How many methods are too many? Are there any "smells" or rules of thumb to use?
Step one is to adhere to the Single Responsibility Principle. If you can't say in one sentence what your class does, then it probably does too much.
Once you've narrowed that down, I don't know that the number of methods really matters as long as your methods don't do too much.
I'll bite. Without doing much more than wading into the very shallow edges of the deep waters of O-O design, I'll through a couple of my rules of thumb:
Static properties are highly questionable. Question yourself strongly about whether or not they are really needed.
Most properties/attributes of a class should be private (accessable only by the object instance) or protected, accessable only by an instance of the class or of a derived class (subclass).
If a property/attribute of a class is visible to the general public, it should most likely be read-only. For the most part, the state of an object instance should change only by its responding to a method asking it to do something useful (e.g., you request that a window move itself, rather than explicitly setting is origin on the coordinate plane).
Public Getter/Setter methods or properties are questionable as they primarily expose object state (which see item #2 above).
Public methods should primarily expose the logical operations (messages) to which an object instance responds. These operations should be atomic (e.g., for the object to be in a logically consistent internal state, it should not depend on an external actors sending it a particular sequence of messages). Object state should change are as result of responding to these messages and should be exposed as a side effect of the message (e.g., a window reporting its location as a side effect of asking it to move is acceptable).
The above should cut down the public interface to your objects considerably.
Finally, if your object has more than a few messages to which it responds, you likely have a candidate for refactoring: is it really one monolithic object, or is it an assembly of discrete objects? "More than a few", of course, is a highly subjective (and contextual) number -- I'll throw out 10-12 as a reasonable limit.
Hope this helps.
There are lots of books out there on O-O design, analysis and modelling.
As others have said, a class is too big when it is trying to do more than one thing and violates the Single Responsibility Principle.
An excellent book on this and other topics (and one I strongly recommend for any developer) is Clean Code by Bob Martin.
static classes such as Math are likely to have lots of methods. It would be confusing to split them.
A general guideline for design: if a reasonable person's first reaction to a <set of things> could plausibly be "That's too many <thing>s!", then it's too many <thing>s.
Number of methods by itself is not a reliable indicator. What if 20 of those are just property getters?
Try metrics that are more concrete, though this is always a judgment call. There is a list of 'code smells' here.
It's all relative but check out the single responsibility principle:
In object-oriented programming, the
single responsibility principle states
that every object should have a single
responsibility, and that
responsibility should be entirely
encapsulated by the class
A rule of thumb i've thought of for SRP: Count your usings/imports/includes. If your class has more than half a dozen there's a good chance that you're violating the SRP. But that's a relative idea as well. Certain patterns such as facades will violate this rule out of necessity. E.g. as in simplifying and hiding a complex subsytem.
A point about it is taken in the "Effective C++" 3rd edition:
"Prefer non-member, non-friend functions to member functions". What this means that you should keep your class reasonable small because big classes tend to be difficult to expand (the do not scale well)
You could also check you class for branches. If your class contains may "if's" or "switch'es" there is a high chance that your class responsibility has dissolved. If this is the case refactoring and cutting the responsibilities into smaller parts may lead to smaller classes.
Best Regards,
Marcin
It depends.
If you are in Java with get/set pairs for each field, I'm not surprised. But if each of those methods are 100+ line beasts, that would be a smell.
It depends on whether or not you can split the class in to subclasses.
Edit: What I mean is that you should ask yourself "does this method apply to this class or would it belong to a subclass?"
For example,
Class Animal
- dog_bark()dog_bark() could be moved to a class named Dog, and the method renamed to bark()
There is never a thing as too large of a class, when the PHP interpreter reads your code it compiles into one large executable black of code so splitting them up makes little difference on performance.
BUT:
When it comes down to programming you should never really need 40+ methods in one class, and should be split up into there entites.
Example
class HTTP
{
/*
* Base functions for HTTP Fetching / transferring / Sending
* so when it comes to single responsibility this would be the the fetch / set in HTTP
*/
}
then you would be more specific with your subclasses such as
class YoutubeUploader extends HTTP
{
/*
* This class is responsible for uploading to youtube only
*/
}
class YoutubeDownload extends HTTP
{
/*
* This class is responsible for downloading to youtube only
*/
}
class CronRunner extends HTTP
{
/*
* This class is responsible for Running your HTTP Cron Tasks
*/
}
no if you did not have that BASE HTTP Class you would have to define methods in all three sub classes to transfer data via the HTTP Protocol.
Splitting your classes up unto single responsibilities gives a more structured framework resulting in less code and more outcome.
Everyone ahs already mentioned the: Single Responsibility Principal but its something you should really understand.
There's also ways to reduce code in classes, take this example
class User
{
public function getUsername()
{
return $data['username'];
}
public function getPermissions()
{
return $data['permissions'];
}
public function getFirstname()
{
return $data['firstname'];
}
}
this are not really needed when you can do:
class User
{
public function __call($method,$params = array())
{
if(substr(0,3,$method) == "get")
{
$var_name = substr(3,strlen($method),$method);
return $data[$var_name];
}
}
}
This would take car of any method called that starts with 'get' and it takes the last portion of the string and searches the array.
In general a class should be designed to do one thing and to do it well. Now, with your example of the Math class, it can act as a facade to seperate implementations. Or it can be split up into hierarchy:
public abstract class Math
{
abstract Solve(IMathPayload);
abstract CanSolve(IMathPayload);
}
public class LinearMath : Math {}
public class DifferentialEquasionMath: Math {}
One strategy I like to follow is to create a 'Handle' class for each data model object. Because the handle is responsible for only modification of
that data object, it follows SRP. If I need to create classes outside of data object modification, at least I know most of the code already is SRP compliant.

How should I document a inherited members? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Consider that I have a complex class structure where many elements inherit from other elements. I may have a method GetStuff(string stuffName, int count) defined in an interface, which is inherited by other interface, which is then implemented abstractly by an abstract class, which is then implement explicit in a concrete class etc. etc...
How should I handle inherited members such as GetStuff() when documenting my code with XML comments which will be used with a tool such as Doxygen or Sandcastle? It seems wrong to just copy and paste the same description at each level. Should I be considering a different audience at the interface level vs the concrete class level? For example the documentation for GetStuff() at the interface may consider people implementing the interface, whereas the documentation at the concrete level may instead consider people who will be using the class?
Document the interface method according to its code contract. Do not comment on its implementation, only on its semantic purpose, i.e. what it’s supposed to do, not how. The audience for this documentation is both your implementors and your users: the method will both be implemented as well as called.
Document the abstract method simply by saying that it implements the interface method and linking to it. There is nothing extra to be said about it, and duplicating the comment violates the DRY (Don’t Repeat Yourself) principle: you would have to remember to make any change to it in both places. (Of course, in the case of an abstract method that doesn’t implement an interface method, document it in the same way that you would document an interface method.)
Document the concrete implementation by saying that it implements the interface method and/or that it overrides the abstract member. Optionally add information about its implementation if it is relevant to the caller — for example, its performance characteristics, or situations in which it might throw, etc.
remark
on part of post
by Eric Anastas
It seems wrong to just copy and paste
the same description at each level.
I can imagine it being wrong to just copy. It is however possible to let doxygen copy it for you and then change what you would like to change for that implementation/scope.
For more information, you can look at the description for #copydoc.

Can I say a Constructor is a Method? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I wonder if can I say that a constructor is a special case of a method?
You can say anything. Whether anyone will disagree with you depends on the context. Some language communities and standards define things that way.
More elaborately, it depends on what you mean by a 'method.' In C++, for example, one way to analyze the creation process is to say that it consists of a call to an operator new (perhaps just placement) followed by a call to a constructor method. From an implementation standpoint, a constructor looks, walks, and quacks like a method. In some compilers, you can even invoke one explicitly.
From a more theoretical viewpoint, someone might claim that constructors are some distinctive species. However, there is no single, true, privileged conceptual model of methods, constructors, or purple unicorns.
Gosh this is all subjective.
You could say so, just as you can say that a human is a special case of animal, however in most contexts mentioning animals implies non-human animals and mentioning methods implies non-constructor methods.
Technically, a constructor usually is a method. Whether it really is or is not depends largely on the particular environment. For example, in .NET constructors are methods called actually after an object is created. However, it's also possible to create an object without having a constructor called right after.
Update: Regarding .NET, or the Common Language Infrastructure to be more precise, ECMA 335, section 8.9.6.6 Constructors states:
New values of an object type are created via constructors. Constructors shall be instance methods, defined via a special form of method contract, which defines the method contract as a constructor for a particular object type.
I think a constructor is too special to be called a method
It doesn't return anything
It modifies the object before the object is initialized
It cannot call itself (imagine that)
blah blah blah
There might be difference between languages, but I don't think I'm going as far as calling a constructor "special method".
In languages that have constructors, you can usually think of a constructor as a special case of a factory method. (Note: I don't mean the GoF Factory Method Software Design Pattern, I'm just talking about any class method that creates new instances.) Usually, this "special casing" generally takes the form of annoying restrictions (e.g. in Java, you can only call the parent constructor at the beginning of the constructor), which is why even in languages that do have constructors, you often end up using or writing factory methods anyway.
So, if constructors are basically factory methods with restrictions, there is really no need to have them both, and thus many languages simply get rid of constructors. Examples include Objective-C, Ruby, Smalltalk, Self, Newspeak, ECMAScript/JavaScript, Io, Ioke, Seph and many others.
In Ruby, the closest thing to a constructor is the method Class#allocate, which simply allocates an empty object and sets that object's class pointer. Nothing more. Since such an empty object is obviously unusable, it needs to initialized. Per convention, this initialization is performed by #initialize. As a convenience, because it is cumbersome to always have to remember to both allocate and initialize (as any Objective-C developer can probably attest), there is a helper method called Class#new, which looks something like this:
class Class
def new(*args, &block)
obj = allocate
obj.initialize(*args, &block)
return obj
end
end
This allows you to replace this:
foo = Foo.allocate
foo.initialize(bar)
With this:
foo = Foo.new(bar)
It is important to note that there is nothing special about any of these methods. Well, with one exception: Class#allocate obviously has to be able to set the class pointer and to allocate memory, which is something that is not possible in Ruby. So, this method has to somehow come from outside the system, which e.g. in MRI means that it is written in C, not Ruby. But that only concerns the implementation. There are no special dispatch rules, no special override rules. It's just a method like any other that can e.g. call super whereever, whenever and how often it wants and can return what it wants.
"Special" is the magic word here. There's absolutely nothing wrong with calling a constructor a special method, but what "special" implies can vary depending on the language.
In most cases, "special" means they can't return values or be called as a method without creating a new object. But there are always exceptions: a prime example is JavaScript, where a constructor is no different from a normal function, it can return its own values and it can be called either as a constructor or as a simple function.
At least in vb.net, constructors can have a non-standard control flow. If the first statement of a constructor is a call to New (of either the same type or a base type), the sequence of events will be: (1) perform the call; (2) initialize all the fields associated with the type; (3) finish handling the rest of the constructor. No normal method has that sort of control flow. This control flow makes it possible to do things like pass constructor parameters to field initializers of a derived type, if the base type is written to allow such.
#Tom Brito, personally I would agree with you that a constructor is a special case of method.
Also, see below:
A constructor in a class is a special type of subroutine called at the creation of an object.
... A constructor resembles an instance method, but it differs from a method in that it never has an explicit return-type...
Source:
Wikipedia
Also, you may read my comments on others' comment (woot4moo, phunehehe).

Where do I use delegates? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What are some real world places that call for delegates? I'm curious what situations or patterns are present where this method is the best solution. No code required.
As stated in "Learning C# 3.0: Master the fundamentals of C# 3.0"
General Scenario: When a head of state dies, the President of the United States typically does not have time to attend the funeral
personally. Instead, he dispatches a delegate. Often this delegate is
the Vice President, but sometimes the VP is unavailable and the
President must send someone else, such as the Secretary of State or
even the First Lady. He does not want to “hardwire” his delegated
authority to a single person; he might delegate this responsibility to
anyone who is able to execute the correct international protocol.
The President defines in advance what responsibility will be delegated
(attend the funeral), what parameters will be passed (condolences,
kind words), and what value he hopes to get back (good will). He then
assigns a particular person to that delegated responsibility at
“runtime” as the course of his presidency progresses.
In programming Scenario: You are often faced with situations where you need to execute a particular action, but you don’t know in
advance which method, or even which object, you’ll want to call upon
to execute it.
For Example: A button might not know which object or objects need to be notified. Rather than wiring the button to a particular
object, you will connect the button to a delegate and then resolve
that delegate to a particular method when the program executes.
A delegate is a named type that defines a particular kind of method. Just as a class definition lays out all the members for the given kind of object it defines, the delegate lays out the method signature for the kind of method it defines.
Based on this statement, a delegate is a function pointer and it defines what that function looks like.
A great example for a real world application of a delegate is the Predicate. In the example from the link, you will notice that Array.Find takes the array to search and then a predicate to handle the criteria of what to find. In this case it passes a method ProductGT10 which matches the Predicate signature.
One common use of delegates for generic Lists are via Action delegates (or its anonymous equivalent) to create a one-line foreach operation:
myList.Foreach( i => i.DoSomething());
I also find the Predicate delegate quite useful in searching or pruning a List:
myList.FindAll( i => i.Name == "Bob");
myList.RemoveAll( i => i.Name == "Bob");
I know you said no code required, but I find it easier to express its usefulness via code. :)
Binding Events to Event Handlers is usually your first introduction to delegates...You might not even know you were using them because the delegate is wrapped up in the EventHandler class.
I had the same question as you and went to this site for an answer.
Apparently, I didn't understood it better even though I skimmed through the examples on this thread.
I found a great use for delegates now that I read: http://www.c-sharpcorner.com/UploadFile/thiagu304/passdata05172006234318PM/passdata.aspx
This might seem more obvious for new users because Forms is much more complicated to pass values than ASP.NET websites with POST/GET (QueryString) ..
Basically you define a delegate which takes "TextBox text" as parameters.
// Form1
// Class Property Definition
public delegate void delPassData(TextBox text);
// Click Handler
private void btnSend_Click(object sender, System.EventArgs e)
{
Form2 frm= new Form2();
delPassData del=new delPassData(frm.funData);
del(this.textBox1);
frm.Show();
}
// SUMMARY: Define delegate, instantiate new Form2 class, assign funData() function to delegate, pass in your textBox to the delegate. Show the form.
// Form2
public void passData(TextBox txtForm1)
{
label1.Text = txtForm1.Text;
}
// SUMMARY: Simply take TextBox txtForm1 as parameters (as defined in your delegate) and assign label text to textBox's text.
I hope this enlightens some use on delegates :) ..
If you're interested in seeing how the Delegate pattern is used in real-world code, look no further than Cocoa on Mac OS X. Cocoa is Apple's preferred UI toolkit for programming under Mac OS X, and is coded in Objective C. It's designed so that each UI component is intended to be extended via delegation rather than subclassing or other means.
For more information, I recommend checking out what Apple has to say about delegates here.
I had a project which used win32 Python.
Due to various reasons, some modules used odbc.py to access the DB, and other modules - pyodbc.py.
There was a problem when a function needed to be used by both kinds of modules. It had an connection object passed to it as an argument, but then it had to know whether to use dbi.dbiDate or datetime to represent times.
This was because odbc.py expected, as values in SQL statements, dates as dbi.dbiDate whereas pyodbc.py expected datetime values.
One further complication was that the connection objects created by odbc.py and pyodbc.py did not allow one to set additional fields.
My solution was to wrap the connection objects returned by odbc.odbc(...) and pyodbc.pyodbc(...) by a delegate class, which contains the desired time representation function as the value of an extra field, and which delegates all other field requests to the original connection object.
A quick google search came up with this http://en.wikipedia.org/wiki/Delegation_pattern . Basically, anytime that you use an object that forwards it's calls to another object then you are delegating.