Naming conversion functions - language-agnostic

Which naming convention for conversions is standard across most languages?
convert_from_typea_to_typeb(arg)
or
convert_to_typeb_from_typea(arg)
Or is there another standard?

I'm going for the OO approach here, (in the relevant namespace) have a Convert class with a bunch of overloads To<TypeName> like so:
public class Convert
{
public Foo ToFoo(Bar instance);
public Foo ToFoo(Baz instance);
public Bar ToBar(Foo instance);
public Bar ToBar(Baz instance);
public Baz ToBaz(Foo instance);
public Baz ToBaz(Bar instance);
}
addition since php came specifically into the conversation; you cannot really do "overloading" in php, but there is a way to do it:
class ConversionException extends Exception
{
}
class Convert
{
public static function ToFoo($instance)
{
$from_type = get_class($instance);
$my_convert_method = $from_type . 'ToFoo';
if (method_exists(__CLASS__, $my_convert_method))
{
return self::$my_convert_method($instance);
}
else
{
throw new ConversionException(sprintf('Cannot convert %s to Foo.', $from_type));
}
}
protected static function BarToFoo(Bar $instance)
{
/* conversion implementation here */
}
protected static function BazToFoo(Bar $instance)
{
/* conversion implementation here */
}
/* you get the point */
}

My answer, and purely subjective, would be the one that flows logically with source to destination.
ConvertStringToInt()
or
ConvertVisitorToCustomer()

I guess in C(++) you would do it with cast operators, so none of these names would fit.
In Objective-C I've seen something like NSPointFromCGPoint(...), or you would give the old type simply in the constructor.
The only thing that I've seen very rarely are those functions with convert_x_to_y :-)

There is no cross-language standard for this kind of thing. Most languages either provide a built-in way to do this (C/C++) or encourage you to find another way around it (Java/C#).
In most object-oriented languages you shouldn't need this sort of functionality. You should try to restructure your program so that you do not need to do any explicit conversions.
However, if you really need to do this, I'd say drop the "convert" at the beginning and do <source>_to_<target>. Examples: string_to_int, int_to_float, foo_to_bar, etc. (Of course, write these in whatever case your language prefers. For example, in C#: StringToInt; in JavaScript: stringToInt.)

Related

Do function arguments violate encapsulation?

This question is related to OOP practice in general.
Say we have a class with a public function accepting passed in arguments from outside of the object. Is that not a violation of encapsulation in itself? On the other hand why is this practice used so widely? After all the constructor of the class and member variables are kind of "by-passed" when calling the function. As an relatively new programmer to OOP and my understanding of encapsulation my function parameters are passed into the object through setters, so that I keep all of my functions without any arguments using the passed in member variables only.
I know that certain arguments can be passed in through the constructor (BTW, I use dependency injection), but what if those parameters change after the object is being instantiated? There must be a way to change those values after the object is created. So far I found no other option than using setters to accomplish this task, but there is a long lasting discussion among programmers about getters and setters to be "evil" or at least considered no good programming practice.
Can anyone tell my where I missed the point and how to solve this dilemma in a clean way?
Many thanks in advance for any support.
Here is a concrete very simple example using C#:
we have a form in a windows form project holding 3 textboxes ,named textBox1 and textBox2 and textBox3.
The task is to add values of textBox1 and textBox2 and returning the result to textBox3 using class AddTextboxValues instantiated by event handler any time the value of textBox1 or textBox2 changes:
The way I see it often and ask if is violation of encapsulation:
public class AddTextBoxValues
{
public double TextBoxValueSum(double textBox1value, double textBox2Value)
{
return textBox1value + textBox2Value;
}
}
This is the way I use at the moment as per my understanding of encapsulation:
public class AddTextBoxValues
{
private double textBox1Value;
private double textBoxValue2;
private double textBoxValue3;
public double TextBox1Value
{
set { textBox1Value = value; }
}
public double TextBoxValue2
{
set { textBoxValue2 = value; }
}
public double TextBoxValue3
{
get { return textBoxValue3; }
}
public void TextBoxValueSum()
{
textBoxValue3= textBox1Value + textBoxValue2;
}
}
This has also the advantage that it can be injected into the form constructor.
Any comment is highly appreciated.
Thank you very much Jon Skeet, you are a real professional.
You diagnosed my problem exactly and opened my eyes for the lack of knowledge to understand and find a solution to my own question. It was indeed a deeper understanding of encapsulation and "object state" which built the missing piece of my puzzle.
Everything seems logic and clear now for me and I hope it will help others in the future,too.
Both examples are not object oriented programming. They are examples of procedural programming.
First "class" is, in fact, just a namespace wrapping TextBoxValueSum function.
Second "class" is just a structure with public fields (there is no difference between getters-setters and public fields).
If you want to use real object oriented programming, you should think of objects, that they are representation of things.
In your case, I'd write class Sum which is a real thing that represent one, specific sum:
class Sum {
private double a, b;
public Sum (double a, double b) { this.a = a; this.b = b; }
public double value() { return this.a + this.b; }
}

OOP Proper use of interfaces in AS3

I'm designing a framework and in the process I have come across an interesting but most likely basic problem. I have a base class called CoreEngine and two other classes that extend it: CoreEngine1 and CoreEngine2. I created an interface that each of these classes would implement to increase the flexibility of my project. However, I have a problem... The definition of my methods in the interface do not match the definition in each inherited class! Each class must implement the following method:
function get avatar():AvatarBase;
The problem is that CoreEngine1 and CoreEngine2 expect a different type of avatar:
CoreEngine1
function get avatar():AvatarScaling
CoreEngine2
function get avatar():AvatarPlatform
As you can see, the return type for avatar in CoreEngine1 and CoreEngine2 do NOT match the type as specified in the interface. I was hoping that since both AvatarScaling and AvatarPlatform inherit AvatarBase that I wouldn't have a problem compiling. However, this is not the case. According to Adobe's documentation, the types MUST match the interface. I am trying to follow one of the core concepts of object oriented programming to extend the flexibility of my framework: "Program to an interface rather than an implementation". The first thing that comes to my mind is that the return type of the accessor method should be of an interface type (Maybe I just answered my own question).
I'm certain this is a common problem others have run into before. Architecturally, what do you think is the best way to solve this problem? Thanks in advance!
Regards,
Will
This is a limitation of how interfaces work and are declared.
If there's inheritance that can happen with the return types, as you've described with AvatarBase and subclasses, then I think the right approach is to make the return type the lowest common denominator and just handle the resulting object on the other end. So, if you're dealing with a CoreEngine1 object, you know you can cast the result from AvatarBase to AvatarScaling. Alternately, if you don't know the object type that you are calling get avatar() on, then you can type check the returned value. The type check would then only be needed if you're looking to call a method that exists on AvatarScaling but not on AvatarBase. I don't think returning an interface type will buy you much in this case because the only things that interface can implement would be things that all forms of Avatar share, which wouldn't be any different than methods in AvatarBase.
Like HotN and Dinko mentioned, it would be best to allow get avatar() to return AvatarBase allways and then cast the returned object as the concrete subclass.
Using Dinko's example:
public /* abstract */ class CoreEngine
{
public /* abstract */ function get avatar():AvatarBase {}
}
public function CoreEngine1 extends CoreEngine
{
override public function get avatar():AvatarBase { return new AvatarScaling(); }
}
public function CoreEngine2 extends CoreEngine
{
override public function get avatar():AvatarBase { return new AvatarPlatform(); }
}
public /* abstract */ class AvatarBase {}
public class AvatarScaling extends AvatarBase
{
public function someAvatarScalingMethod():void {}
}
public class AvatarPlatform extends AvatarBase
{
public function someAvatarPlatformMethod():void {}
}
To use a method from AvatarScaling, cast the returned object:
var c1:CoreEngine1 = new CoreEngine1();
var avatarScaling:AvatarScaling = AvatarScaling(c1.avatar());
avatarScaling.someAvatarScalingMethod();
hth
I think you answered your own question... the return type would still be AvatarBase, you need to follow the signature that you specified in the interface... but you can technically return ANY descendent of AvatarBase in that function. So doing something like
return new AvatarScaling();
in CoreEngine1 would be perfectly acceptable.
Of course in your calling function you will get back an AvatarBase instance, and you will have to know what this is in order to cast to a specific subclass.
CoreEngine1 ce1 = new CoreEngine1();
AvatarScaling avatar = ce1.avatar() as AvatarScaling;

AS3 - Retype/Cast an inherited variable permanently in a subclass?

Possibly bad practice but I'm not well versed in software design anyway (I'm sure this question would have been asked before but I can't seem to find the right terminology)...Anyhow, it's just another curiosity of mine I'd like to have answered.
So I have worked in a way where I type a base class variable to type Object or Sprite or something similar so that in my subclasses, I can instantiate my custom classes into them and store it. And when I access it, I just cast that variable to ensure I can access the methods.
Take this example, so that you know what I'm talking about:
public class BaseClass
{
protected var the_holder_var:Object;
public function BaseClass()
{
//Whatever abstract implementation here...
}
}
Now, my subclasses of that base class usually use an interface but for simplicity sake, I'll just write it without it.
public class AnExtendedClass extends BaseClass
{
public function AnExtendedClass()
{
//Instantiate my own class into the base class variable
this.the_holder_var = new ACustomClassOfMine();
//Then I can use the 'hackish' getter function below to
//access the var's functions.
this.holder_var.somefunction()
}
private function get holder_var():ACustomClassOfMine
{
return this.the_holder_var as ACustomClassOfMine;
}
}
This works and I'm sure it will make some ppl cringe (I sometimes cringe at it too).
So now, my question, is there a way to recast/retype that base var in my extended subclass?
kinda like this:
public class ExtendedClass extends BaseClass
{
//Not possible I know, but as a reference to see what I'm asking about
//Just want to change the type....
override protected var the_holder_var:ACustomClassOfMine;
public function ExtendedClass()
{
//Then I can forget about having that hackish getter method.
this.the_holder_var = new ACustomClassOfMine();
this.the_holder_var.somefunction();
}
}
I was thinking of typing most of my base class vars that I use as holders as type * and retyping them as I extend the class. (I could use it here too but yeah...)
Thoughts? Comments? Ideas?
I actually think your code (apart from the hypothetical addition at the end) is pretty alright. The practise of adding accessors to solve the type issue you're dealing with is a solid one. I would advise to rename the accessor to show it is a cast, maybe get holderVarAsCustom():ACustomClassOfMine (I'm also not a big fan of the underscores, that's another language's convention), but that's personal preference. What I'd do to solve your last problem is just create a matching setter function:
private function set holderVarAsCustom(value:ACustomClassOfMine):void {
this.the_holder_var = value;
}
This way you can access the correctly typed holder var for both read and write operations with complete type safety:
holderVarAsCustom = new ACustomClassOfMine();
holderVarAsCustom.someFunction();
I would definately advise against dropping the type safety by including arrays and what not, that just makes it unstable.
I must admit that i'm a little confused as to why you want to do this, but here goes. Could you not utilise the fact that Array's can hold different data types. So something like this:
public class BaseClass
{
protected var customStorage:Array;
public function BaseClass()
{
//Whatever abstract implementation here...
}
}
You could then access it with an associative method and a property:
public class AnExtendedClass extends BaseClass
{
private static const myName:String = "myName";
public function AnExtendedClass()
{
//Instantiate my own class into the base class variable
customStorage[myName] = new ACustomClassOfMine();
objectIWant.somefunction()
}
private function get objectIWant():ACustomClassOfMine
{
return ACustomClassOfMine(customStorage[myName]);
}
}
Is that any better?
I would not try to tinker this behaviour, since you can't change the declared type of a variable once declared, no matter how hard you try.
What I do in such cases, I either cast the variable if I use it sparingly or the object it references may change, or I add another variable with the type I want and let the other variable point to the new one. Like this:
public class A {
protected var object:Object;
public function A() {
//Whatever abstract implementation here...
}
}
and
public class B extends A {
protected var other:MyClass;
public function B() {
super();
this.other = new MyClass();
this.object = this.other;
}
}
Having it this way, class A uses the object via the this.object reference, and class B can use the this.other or both. But both references point to the same object. The only issues with this are:
having two references for in the same class to the same object is ugly (so are untyped variables and casts)
if the object one of them may point can change during runtime, you must be really carefull to synchronize these changes

What is the best practice for returning a subclass or interface implementation from a method?

Disclaimer
Please don't just vote to close this because the title looks subjective, and if it's been asked before please point me to the previous question in the comments and I'll delete this one -- I really did look high and low trying to find a previous question on the subject.
Background
Given I have the following interface and concrete implementation:
public interface IFoo
{
// Some stuff
}
public class Foo : IFoo
{
// Concrete implementations of stuff
}
And somewhere I have the following method:
public Foo GiveMeAFoo()
{
return new Foo();
}
I have traditionally always returned Foo, seeing as it is inherently an IFoo anyway, so it can be consumed at the other end as an IFoo:
IFoo foo = GiveMeAFoo();
The main advantage of this that I can see is that if I really need to consume Foo somewhere as the concrete implementation, I can.
Actual Question
I recently came across some comments on another question, giving someone a hard time for doing this, suggesting the return type should be IFoo.
Am I wrong or are they? Can anyone give me a reason why returning the concrete implementation is a bad idea?
I know that it makes sense to require an IFoo when receiving a parameter to a method, because the less specific a parameter is, the more useful a method is, but surely making the return type specific is unreasonably restrictive.
Edit
The use of IFoo and Foo might have been too vague. Here's a specific example from .NET (in .NET, arrays implement IEnumerable -- i.e. string[] : IEnumerable<string>)
public string[] GetMeSomeStrings()
{
return new string[] { "first", "second", "third" };
}
Surely it's a bad idea to return IEnumerable here? To get the length property you'd now have to call Enumerable.Count(). I'm not sure about how much is optimised in the background here, but logic would suggest that it's now going to have to count the items by enumerating them, which has got to be bad for performance. If I just return the array as an array, then it's a straight property lookup.
If you want your method to be the most flexible that it can be, you should return the least derived type (in your case, IFoo):
public interface IFoo { }
public class Foo : IFoo { }
public IFoo GiveMeAFoo() { return new Foo(); }
That will allow you to change the concrete implementation of IFoo internal to your method without breaking anybody that is consuming your method:
public interface IFoo { }
public class Foo : IFoo { }
public class Foo2 : IFoo { }
public IFoo GiveMeAFoo() { return new Foo2(); }
You can create a bunch of interfaces and give it to different teams. Taking your own example
public interface IFoo
{
// Some stuff
}
public interface IBar
{
public IFoo getMeAFoo();
}
Then you can give these interfaces to a person developing a front end app and he doesn't have to know what the concrete implementation is. The guy developing the front end can use the getMeAFoo() method knowing that it returns an object of IFoo whereas the concrete implementation can be developed separately as:
public class Foo implements IFoo
{
// more stuff
}
public class MoreFoo implements IFoo
{
//
}
public class WunderBar implements IBar
{
public IFoo getMeAFoo()
{
case 1:
return new Foo();
case 2:
return new MoreFoo();
}
}
Hope this makes sense :)
In my opinion, it's always better to return the most abstract type you can. If you find yourself in need for anything that's specific to the type you ar actually returning, I would consider it a code smell.
The main advantage of this is that you can change your mind about which type you really want to return. The called method is made more decoupled from its callers.
Also, you can possibly remove dependencies. The caller code don't need to know anything about the actual type you chose to create.
My final remark is a quotation from Eric Lippert: "You probably should not return an array as the value of a public method or property". (His article is focused in C#, but the general idea is language-agnostic)
Fine, everywhere you use it, you use IFoo foo = GiveMeAFoo();
Then someone else uses your code and doesn't use it that way, for whatever reason, they use Foo foo = GiveMeAFoo();
Now they see all the functionality of Foo that isn't (for good reason) part of IFoo. Now they can use parts of the implementation that aren't part of the interface. Now you can't change your implementation without breaking their code, your implementation is now the public API and you are going to tick people off if you try to change your implementation details that they are counting on.
Not good.

When does it make sense to return this-reference?

Currently I can think of only three good reasons to return this in a (public) method, namely:
(mmyers) when implementing fluent interfaces, e.g.
public class X
{
...
public X enableValidation()
{
setValidation(true);
return this;
}
...
}
(Jon Skeet) for identity conversions, e.g.
public class X
{
...
public X toX()
{
return this;
}
...
}
(Dave Ray) implementing a clone() or copy() method on an immutable object, e.g.
#Immutable
public class X
{
...
public X copy()
{
return this;
}
...
}
Are there any other useful scenarios in an object-oriented language in which you would return this or self from a method?
If you are creating chaining operations (however this might not be very OOP'ish - Law of Demeter, etc).
Example (not that it makes a lot of sense):
public class X
{
public X Add(int i)
{
this.Value += i;
return this;
}
public X Subtract(int i)
{
this.Value -= i;
return this;
}
public int Value
{
get;
set;
}
}
new X().Add(4).Subtract(5).Value;
String.toString() :)
On a more serious note, there are similar "convert to [x]" scenarios where it's okay to just return "this"... but I can't think of very many other situations.
Any implementation of a clone() or copy() method on an immutable object.
C++ does this all the time to allow cascading operators.
for example the << operator always returns itself (ostream) so that you can cascade the calls in such a way:
std::cout << "call 1" << "call2" << std::endl;
The only language which I believe this cascading effect is popular is C++.
Quick addition when it comes to fluent interfaces:
As mentioned in this "A simple example of a fluent interface" article (at the end of the comments), :
You'll hit a brick when using inheritance along with fluent interfaces because:
using polymorphic methods break your call chains and
you definitely don't want to make your interfaces non-fluent by using ugly casting and parenthesis where they are not needed or by doing lots of un-useful overrides in the children that do the casting
alt text http://withasmiletomeltathousandhearts.files.wordpress.com/2009/02/fluent_interfaces_order_class_hierarchy.jpg?w=300&h=255
In this article about a more robust pattern for complex (and yet fluent) hierarchy of classes , "this" is used to return the instance of the base class "Builder", whereas Builder for concrete classes uses casting.
Take the following implementation.
public interface Monitorable {
public Statistics getStatistics();
}
public interface MonitorManager {
public Monitorable getMonitorable();
}
class MonitorableService implements Monitorable, MonitorManager {
public Monitorable getMonitorable() {
return this;
}
}
// Meanwhile somwhere else...
MonitorManager manager = getMonitorManagerFromSomewhere();
Monitorable monitorable = manager.getMonitorable();
I admit this is rather contrived, but the overal pattern/message should be clear.
Here I do not need to know the MonitorManager is implemented by the Application class. Nor do I need to know that Monitorable is implemented by Application.
Here polymorphism is used to encapsulate the implementation details of Application. Which is not a public class. This is a very common pattern, and can be seen in a wide variety of projects.