The Artima Developer Community
Sponsored Link

Artima Developer Spotlight Forum
Structural Typing in Scala

15 replies on 2 pages. Most recent reply: Oct 15, 2008 8:41 AM by Jack Flint

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 15 replies on 2 pages [ 1 2 | » ]
Frank Sommers

Posts: 2642
Nickname: fsommers
Registered: Jan, 2002

Structural Typing in Scala Posted: Jun 12, 2008 8:59 PM
Reply to this message Reply
Advertisement

Interfaces are often preferred in place of inheritance in an object model: Instead of having to inherit from a common class, objects can specify shared behavior by implementing a common interface.

At the same time, once an object declares the interfaces it implements, evolving the interface becomes more difficult, since all objects implementing the interface would have to be changed.

Easy type evolution is one reason some developers prefer dynamic languages. Larger projects, however, often benefit from a static type system. Structural typing is a technique that combines some of the best features of interfaces with the sort of type evolution typical of dynamic language.

Instead of explicit declarations, structural typing lets the compiler determine shared type information. Among the major languages supporting structural typing is Scala. As Debasish Ghosh explains in a recent article, Java to Scala - Smaller Inheritance hierarchies with Structural Typing, Scala's structural typing can lead to more nimble object hierarchies:

Interface driven programming has its advantages in promoting loose coupling between the contracts that it exposes and their concrete implementations. But interfaces in Java also pose problems when it comes to evolution of an API - once an interface is published, it is not possible to make any changes without breaking client code. No wonder we find design patterns like The Extension Object or strict guidelines for evolution of abstractions being enforced in big projects like Eclipse...

Structural typing offers the ability to reduce the scope of polymorphism only over the subset of behaviors that need to be common between the classes. Just as in duck typing, commonality in abstractions does not mean that they belong to one common type; but only the fact that they respond to a common set of messages...

Scala offers the benefit of both ... worlds through its implementation of structural typing - a compile time checked duck typing. Hence we have a nice solution to unify certain behaviors of otherwise unrelated classes. The entire class hierarchy need not be related through static compile time subtyping relationship in order to be processed polymorphically over a certain set of behaviors...

We can generalize this commonality into an anonymous type that implements a method having the same signature. All classes that implement a method salary returning an Int are said to be structurally conformant to this anonymous type { def salary: Int }. And of course we can use this anonymous type as a generic parameter to a Scala List.

What do you think of structural typing?


nes

Posts: 137
Nickname: nn
Registered: Jul, 2004

Re: Structural Typing in Scala Posted: Jun 13, 2008 10:47 AM
Reply to this message Reply
As a fan of dynamic languages I like how static type checking finds silly bugs even before starting the program, it is just that in the past most implementations of static typed languages were sorely lacking in my opinion. Structural typing should make software easier to evolve by allowing many implicit interfaces to exist at the cost of making programs using them more difficult to understand. Now the only thing missing is a type system that performs checks based on configuration files of an application without having to recompile everything again.

Frank Sommers

Posts: 2642
Nickname: fsommers
Registered: Jan, 2002

Re: Structural Typing in Scala Posted: Jun 13, 2008 11:38 AM
Reply to this message Reply
> Now the only thing missing is a type system
> that performs checks based on configuration files of an
> application without having to recompile everything again.

It's interesting, because you can apparently write plug-ins to the Scala compiler that could possibly do that.

John Zabroski

Posts: 272
Nickname: zbo
Registered: Jan, 2007

Re: Structural Typing in Scala Posted: Jun 14, 2008 10:27 AM
Reply to this message Reply
Neither the Java code nor the Scala code appeals to me that much.

It seems Debasish and others misunderstand the implication behind InheritanceBreaksEncapsulation. The real issue is that inheritance breaks the class-based data model. Furthermore, because data and methods are co-located together, it is hard to discern whether an inherited method breaks the data model or the process model. All we can say is that it breaks the class model. This makes maintaining code frustrating, and a lexicon of terms like fragile base class problem sprout up from the ground. Research shows that this isn't even the biggest issue, though: the important thing is to preserve mathematical invariants, yet research shows that in deep inheritance hierarchies the classes in the middle are often the most brittle. What this means is that the fragile base class problem of 'what data and methods should be located in all objects implementing this type contract' is the least of your worries.

/endrant

Christopher Diggins

Posts: 1215
Nickname: cdiggins
Registered: Feb, 2004

Re: Structural Typing in Scala Posted: Jun 15, 2008 10:48 AM
Reply to this message Reply
> The real issue is
> that inheritance breaks the class-based data model.
> ... it is hard to discern whether an inherited
> method breaks the data model or the process
> model.

This is logical contradiction. Could you clarify?

Christopher Diggins

Posts: 1215
Nickname: cdiggins
Registered: Feb, 2004

Re: Structural Typing in Scala Posted: Jun 15, 2008 10:56 AM
Reply to this message Reply
I wonder if this post had any influence on the introduction of structural typing in Scala:
http://osdir.com/ml/lang.scala/2005-06/msg00028.html?

John Zabroski

Posts: 272
Nickname: zbo
Registered: Jan, 2007

Re: Structural Typing in Scala Posted: Jun 15, 2008 1:26 PM
Reply to this message Reply
> This is logical contradiction.
> Could you clarify?

Yes, that was awkward. I'm trying to describe two things at once: our cognitive approach and the machine's obedience. Here's hoping this next shot is clearer:

The class-based model of data is defined in terms of visibility modifiers and object responsibilities. For any given problem, there is a set of compositional units that when transformed provide you with the semantics of a specification. These compositional units can be transformed by arbitrarily many transformers and all will have the same semantics. Considering this, the fundamental question becomes how to ensure the object is in a known state at all times when it is run on whatever machine we target.

In OOA/D/P, responsibilities for an object define how the object will collaborate with the rest of the system, and, in doing so, should define the nature of those collaborations in terms of role dependencies (as opposed to complete dependencies on the object as though it were fundamentally unique and not re-usable). Responsibilities form the seams of an object, gluing an object together at its natural joints: objects are peers, and how they relate to one another is the central emphasis of object-oriented analysis. In order to preserve the design constraints imposed by these responsibilities, any data contained within the object should not be visible if the responsibilities of the object can be subverted. In other words, so long as you can't break methods by redefining them (and technology does not encourage this practice because it runs contrary to protecting and hiding of state-process), the only place in the class-based model to assign blame is the data model. When you set a watch in your debugger, you are checking for unexpected values in your data model; when you run unit tests, you are checking for unexpected output to automate searching for bugs.

Now, there is nothing problematic with borrowing from one specification to fulfill another. However, keeping those specifications in sync means you have two different objects borrowing from the same lifecycle, and that means understanding state-process dependencies, including implementation defined details. This is troubling, because inheritance is supposed to enable derivation and therefore you really want a step between the parent-child chain that defines a specification between the two. However, in doing so, you may need to set forth some facts about protected and private data members. Yet, that means details you'd prefer to keep closed (actually, unspecified) must be opened for the special case of a child (changing it from unspecified semantics to implementation defined semantics).

That's a little too much work for me. There's nothing wrong with doing that, but I prefer systems that are easier to specify and require less consistency management, since consistency management (internal) is far harder than dependency management (external), and makes re-use that much harder. As the research shows, we can't be trusted to get it right. I'd much prefer using other ways to model subsumption relations, but that isn't always wise or possible, either.

James Watson

Posts: 2024
Nickname: watson
Registered: Sep, 2005

Re: Structural Typing in Scala Posted: Jun 16, 2008 7:24 AM
Reply to this message Reply
> What do you think of structural typing?

It's something I've wanted since I started using Python but I didn't know what to call it.

There are some many great things about Scala but I feel it cannot become the next Java as intended. It's just too hifalutin for the average Java shop. Even if you get past that, when I look at the Scala Docs for the standard libraries, it's a big turn off to see classes Tuple1...Tuple22. Do we really need to see that? Maybe I'm being a little silly but it's just icky.

Jeff Heon

Posts: 40
Nickname: jfheon
Registered: Feb, 2005

Re: Structural Typing in Scala Posted: Jun 16, 2008 9:03 AM
Reply to this message Reply
> There are some many great things about Scala but I feel it
> cannot become the next Java as intended.

I don't really think Scala is intended to be the next Java. Of course, I could be wrong. I keep seeing comments to the effect of "if we want mass migration", "need IDE for adoption by millions of users", etc.

Personally, I got interested in Scala because it was one way to learn more about functional programming and actors, which was getting mentioned more and more on Artima. One of the initial key factor for me was that it was even framework agnostic at the beginning. I could use to target either .net or Java. But I disgress...

What I really want to say is that a huge user base adds a particular strain to the language designers. I'm pretty sure Bjarne Stroustrup made a comment to that effect in a FAQ or interview, I just can't find the reference anymore.

I'm really speaking out of my hat here, because I am not in touch with the Scala community, but I think Scala's leaders are just happy that people are getting interested in it and are using it, without wanting to replace Java with it, and without wanting millions of users.

Just my two cents 8)

James Watson

Posts: 2024
Nickname: watson
Registered: Sep, 2005

Re: Structural Typing in Scala Posted: Jun 16, 2008 10:45 AM
Reply to this message Reply
> > There are some many great things about Scala but I feel
> it
> > cannot become the next Java as intended.
>
> I don't really think Scala is intended to be the next
> Java. Of course, I could be wrong. I keep seeing comments
> to the effect of "if we want mass migration", "need IDE
> for adoption by millions of users", etc.

Martin Odersky has stated that is the intention unless I'm greatly misunderstanding him.

> I'm really speaking out of my hat here, because I am not
> in touch with the Scala community, but I think Scala's
> leaders are just happy that people are getting interested
> in it and are using it, without wanting to replace Java
> with it, and without wanting millions of users.

I can't speak to the community but Martin Odersky's aim is to create a next generation Java in Scala. I will venture that a number of people in the Scala community are definitely working against that aim.

The problem I see is that Scala entertains some features that don't provide value in the kind of shop that uses Java. In fact the mere existence of some of these features represents intolerable risk in those shops. Java isn't popular because of it's features, I can't count the number of languages that beat it hands-down in that regard. What makes Java popular is that it's manageable (or at least it was prior to 1.5 anyway); there aren't a lot of surprises in Java code. What you see is what you get.

I think Martin Odersky is a brilliant and very well meaning person but I think he might be struggling with trying to put himself on the level of someone trying to manage a bunch of developers right out of a 6-week programmer training course. Features like structural typing and traits are straightforward and are worthwhile improvements to Java. Things like global implicit defs which can change the meaning of all the code in your base invisibly negate the value of those improvements.

And don't get me started on the native XML debacle. Didn't we learn not to couple a language to document format (basically a view) with COBOL?

Raoul Duke

Posts: 127
Nickname: raoulduke
Registered: Apr, 2006

Re: Structural Typing in Scala Posted: Jun 16, 2008 1:48 PM
Reply to this message Reply
> > This is logical contradiction.
> > Could you clarify?
>
> Yes, that was awkward. I'm trying to describe two things
> at once: our cognitive approach and the machine's
> obedience. Here's hoping this next shot is clearer:

i think that was still awkward, but appreciated since i think what you are getting at is important.

food for thought are things like: Aldrich's paper http://lambda-the-ultimate.org/classic/message12271.html

James Watson

Posts: 2024
Nickname: watson
Registered: Sep, 2005

Re: Structural Typing in Scala Posted: Jun 16, 2008 2:58 PM
Reply to this message Reply
> In other words, so long as you can't break methods by
> y redefining them (and technology does not encourage this
> practice because it runs contrary to protecting and hiding
> of state-process), the only place in the class-based model
> to assign blame is the data model.

Maybe I'm missing the point here but when I define an interface it makes no assumptions about the data model. In fact, often my implementations of interfaces have no state. Sharing a specification (interface) in no way implies any sharing of a data model. Bugs exist only in executable code. Unexpected values can only expose bugs if that data was created by incorrect code. Bad data on it's own can never be a bug.

What is it that you are trying to say? An please consider Einstein's maxim (paraphrased): if you can't explain something in plain terms, you don't really understand it.

John Zabroski

Posts: 272
Nickname: zbo
Registered: Jan, 2007

Re: Structural Typing in Scala Posted: Jun 16, 2008 9:12 PM
Reply to this message Reply
> An please consider Einstein's maxim
> (paraphrased): if you can't explain
> something in plain terms, you don't
> really understand it.

This is funny, though, because when it comes to why, Einstein's best answer was 'God doesn't play dice.'

I know the importance of plain terms, and I've seen geniuses give lectures from both ends of the spectrum. I've seen physicists talk about how their 60 million dollar taxpayer-funded project's goal was 'to get a more accurate estimate of a presently unquantified variable in a matrix', without any explanation at all as to 'why' (despite how excited the answer would make the layman iff only explained in plain terms!).

Rule one of explaining things in plain terms is 'don't use math' (but make sure you test it with math to prove your intuition). I learned that from Dr. Emilio Mendez, the head of BNL's Center for Functional Nanomaterials, who is one of the best scientific speakers in the world. I didn't use any math, and explain it in plain terms, albeit awkwardly.

> when I define an interface it makes no
> assumptions about the data model.

Always? That's silly. Any non-functional requirement exposes some details about the input parameter.

> In fact, often my implementations of
> interfaces have no state.

Often? Does that mean degenerate cases exist e.g. sometimes a car crashes into a wall? ...and what do you mean by 'no state'. Do you mean they don't mutate state?

> Sharing a specification (interface) in
> no way implies any sharing of a data model.

You meant to say, 'sharing a specification in no way implies any sharing of anything, except for the shared spec', which is trivially true by statement of definition. And.. it does imply that you should take note of how that specification is shared. All the bugs I encounter in the GUI I am rewriting resulted from shared specifications that were invisible to the maintenance programmer (me). Some of those bugs are now 'features' that we need to phase out (which entails a specification for the bug/feature, the workaround spec to remove it from the system, and the legacy support spec to ensure the user can still view the bug) or just plain keep b/c users pay for features and not bug fixes that are 0.000001% likely to occur and don't really cost them money (the best 'bug' scenario).

James Watson

Posts: 2024
Nickname: watson
Registered: Sep, 2005

Re: Structural Typing in Scala Posted: Jun 17, 2008 6:32 AM
Reply to this message Reply
> > An please consider Einstein's maxim
> > (paraphrased): if you can't explain
> > something in plain terms, you don't
> > really understand it.
>
> This is funny, though, because when it comes to why,
> Einstein's best answer was 'God doesn't play dice.'

Not really. That had to do with the empirical evidence conflicting with his religion. It wasn't an explanation. It was a denial. In fact Einstein was a great contributor to early Quantum physics. It wasn't that he didn't understand, he just didn't want to believe.

> I know the importance of plain terms, and I've seen
> geniuses give lectures from both ends of the spectrum.
> I've seen physicists talk about how their 60 million
> n dollar taxpayer-funded project's goal was 'to get a more
> accurate estimate of a presently unquantified variable in
> a matrix', without any explanation at all as to 'why'
> (despite how excited the answer would make the layman iff
> only explained in plain terms!).
>
> Rule one of explaining things in plain terms is 'don't use
> math' (but make sure you test it with math to prove your
> intuition). I learned that from Dr. Emilio Mendez, the
> head of BNL's Center for Functional Nanomaterials, who is
> one of the best scientific speakers in the world. I
> didn't use any math, and explain it in plain terms, albeit
> awkwardly.
>
> > when I define an interface it makes no
> > assumptions about the data model.
>
> Always? That's silly. Any non-functional requirement
> exposes some details about the input parameter.

Parameters to a method are not part of the host object's data model.

> > In fact, often my implementations of
> > interfaces have no state.
>
> Often? Does that mean degenerate cases exist e.g.
> sometimes a car crashes into a wall?

http://www.google.com/search?hl=en&q=define%3A+often&btnG=Google+Search

> ...and what do you
> mean by 'no state'. Do you mean they don't mutate state?

The object has no member variables i.e. no data.

> > Sharing a specification (interface) in
> > no way implies any sharing of a data model.
>
> You meant to say, 'sharing a specification in no way
> implies any sharing of anything, except for the shared
> spec
', which is trivially true by statement of
> definition. And.. it does imply that you should take note
> of how that specification is shared. All the bugs I
> encounter in the GUI I am rewriting resulted from shared
> specifications that were invisible to the maintenance
> programmer (me). Some of those bugs are now 'features'
> that we need to phase out (which entails a specification
> for the bug/feature, the workaround spec to remove it from
> the system, and the legacy support spec to ensure the user
> can still view the bug) or just plain keep b/c users pay
> for features and not bug fixes that are 0.000001% likely
> to occur and don't really cost them money (the best 'bug'
> scenario).

Fine but your diatribe about how bugs in OO are only in data or whatever still doesn't make any sense to me.

Johan Torp

Posts: 2
Nickname: thorpe
Registered: Jun, 2008

Re: Structural Typing in Scala Posted: Jun 22, 2008 11:41 AM
Reply to this message Reply
> <p>Interfaces are often preferred in place of inheritance
> in an object model: Instead of having to inherit from a
> common class, objects can specify shared behavior by
> implementing a common interface. </p>
>
> <p>At the same time, once an object declares the
> interfaces it implements, evolving the interface becomes
> more difficult, since all objects implementing the
> interface would have to be changed. </p>
>
> <p>Easy type evolution is one reason some developers
> prefer dynamic languages. Larger projects, however, often
> benefit from a static type system. Structural typing is a
> technique that combines some of the best features of
> interfaces with the sort of type evolution typical of
> dynamic language.</p>
>
> <p>Instead of explicit declarations, structural typing
> lets the compiler determine shared type information. Among
> the major languages supporting structural typing is Scala.
> As
> Debasish Ghosh explains in a recent article, <a
> href="http://debasishg.blogspot.com/2008/06/scala-to-java-s
> maller-inheritance.html">Java to Scala - Smaller
> Inheritance hierarchies with Structural Typing</a>,
> Scala's structural typing can lead to more nimble object
> hierarchies:</p>
>
> <blockquote>
> <p>Interface driven programming has its advantages in
> promoting loose coupling between the contracts that it
> exposes and their concrete implementations. But interfaces
> in Java also pose problems when it comes to evolution of
> an API - once an interface is published, it is not
> possible to make any changes without breaking client code.
> No wonder we find design patterns like The Extension
> Object or strict guidelines for evolution of abstractions
> being enforced in big projects like Eclipse...
> </p>
>
> <p>Structural typing offers the ability to reduce the
> scope of polymorphism only over the subset of behaviors
> that need to be common between the classes. Just as in
> duck typing, commonality in abstractions does not mean
> that they belong to one common type; but only the fact
> that they respond to a common set of messages...</p>
>
> <p>Scala offers the benefit of both ... worlds through its
> implementation of structural typing - a compile time
> checked duck typing. Hence we have a nice solution to
> unify certain behaviors of otherwise unrelated classes.
> The entire class hierarchy need not be related through
> static compile time subtyping relationship in order to be
> processed polymorphically over a certain set of
> behaviors...</p>
>
> <p>We can generalize this commonality into an anonymous
> type that implements a method having the same signature.
> All classes that implement a method <code>salary</code>
> returning an <code>Int</code> are said to be structurally
> conformant to this anonymous type <code>{ def salary: Int
> }</code>. And of course we can use this anonymous type as
> a generic parameter to a Scala List.</p>
>
> </blockquote>
>
> <p>What do you think of structural typing?</p>

From your post, this sounds a lot like generic programming in C++. Which is extremely useful to combine with OO programming :) I believe in multiparadigm languages for larger projects.

http://en.wikipedia.org/wiki/Concept_(generic_programming)

Best Regards, Johan

Flat View: This topic has 15 replies on 2 pages [ 1  2 | » ]
Topic: The Adventures of a Pythonista in Schemeland, Part 6 Previous Topic   Next Topic Topic: New Control Structures for Java

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use