Wednesday, November 28, 2018

OOP Concepts: The Aggregate Class

One fundamental principle in object-oriented programming (OOP) is hiding data. The idea is that you use a class to encapsulate data associated with some entity in the business model. All data access and manipulation should be performed by methods on the class.

This principle also applies to collections. In this post, I'll cover some details of a specific pattern for hiding collections. This pattern is called the aggregate class. An Aggregate Class follows the same principles as any other class: data hiding, separation of concerns, etc. It also has the same benefits: reuse, contained changes, centralized business logic.

The Problem With Functional Style in OO Languages

With so many developers using ORM's and Linq (and other lambda-based operations in other languages besides C#), we see a trend toward functional style programming in OO languages such as C# and Java. We should still be careful to protect the data since OO languages do not work the same way as functional programming languages.

In OO languages, collections such as lists and arrays still allow you to change the state of each element. Even if the collection itself is read-only, it's only a pointer to the underlying objects. You could, perhaps, use structs in C#. But then again, you might not have control, and still, you'd have to go the extra mile to properly handle state changes.

If you're really doing functional programming, you won't mutate the state of a record. Some OO concepts have bled into functional languages like Lisp and F#. Basically, the lines have blurred on both sides. When it comes to OO languages, classes are mutable by default. The whole point is to mutate state within a class instance! So, we need to be careful to protect the state of collections from corruption by external manipulation.

Enter the Aggregate

The Aggregate Class is just the thing to keep our data within collections protected. The aggregate class helps by containing changes to the collection. Also, it gives us a centralized place to organize our collection logic. That's really important too!

As an example, let's consider an application for managing people within a school system. There are several types of people in a school. Major classifications are students, teachers, staff, and administrators. There may be some database table containing basic information of all persons: name, phone number, etc. But, indeed, there will be various information for each type of person. 

Specifically, a teacher may be tenured. Say a teacher earns tenure after five years. You can write a filter using Linq to get all tenured teachers like this:

var tenuredTeachers = persons.Where(
    person => person.Role == "Teacher" && 
    (DateTime.Now - person.StartDate).Days > (365 * 5)

As you can see, it can be a little messy. And of course, this encourages copy-paste coding because you might need the logic elsewhere. How do we fix this?

First of all, we'll make a Teacher class and put an IsTenured property on that to contain the logic.

var tenuredTeachers = persons.Where(
    person => person is Teacher && person.IsTenured

Already looking cleaner!

Next, let's do away with the "person is Teacher" by using OfType<Teacher>:

var tenuredTeachers = persons.OfType<Teacher>().Where(
    person => person.IsTenured

Even better! OfType will filter the collection down to the specified sub-type. But must we repeat this code every time we need teachers? No! We can use the Aggregate Class. Let's make one like this:

class Persons
   public IEnumerable<Teacher> Teachers { get { return _persons.OfType<Teacher>(); } }

And we can use that to get teachers wherever we need them. But we can go a bit further and create a Teachers Aggregate Class too.

class Persons
   public Teachers Teachers { get { return Teachers.Get(_persons); } }

class Teachers
    // factory method
    public static Teachers Get(IEnumerable<Person> persons)
        return new Teachers(persons.OfType<Teacher>());

    private Teachers(IEnumerable<Teacher> teachers)
        _teachers = teachers;

    public Teachers TenuredTeachers { get { return _teachers.Where(t => t.IsTenured); } }

And with that, we can return only the tenured teachers and contain the logic. Now in our business objects, controllers, or wherever we need to get tenured teachers, we can use this Teachers Aggregate.

var tenuredTeachers = persons.Teachers.TenuredTeachers;

And there we have some nice clean code!

Applying Functions to Aggregates

We want to protect the data within the collections. There's a pattern we can use to pass functions to the collections within the Aggregate Class. It's basically the visitor pattern, and it goes a little like this:

persons.Teachers.Apply(t => notification.Notify(t) );

// or

persons.Teachers.Apply( notification.Notify );

In this case, we're passing the "Notify" function to the Teachers Aggregate. The Teachers Aggregate will handle passing it along to all the teachers.

Even with the Apply function, we aren't really protecting the data unless the Teacher class protects its own data. A typical pattern you'll see is that the Teacher or Person class is a POCO—meaning it just has public properties. POCOs are really just DTOs. They're intended for transferring data, but you shouldn't really manipulate the data everywhere in your code. This is where you have a real divergence between the intention of OO and how we often see the languages used in practice.

On the flip-side, we see functional programming operating on records. But when that happens, the default is to create new records as a result of the application of a function. A Map method in a Teachers class would look like this:

public IEnumerable<Teacher> Map( Func<Teacher, Teacher> map )
    return _teachers.Select( t => map( t.Clone() ) );

In this Map method, the elements of the internal collection are copied then passed to the map delegate given to Map. Surely, this is an odd mix of OO concepts and functional principles. The Aggregate Class shouldn't really return a collection of the internal data even if it's a copy. This is really a generic type of method that has use in low levels of your application stack. It isn't beneficial. Think about it this way...what business function does "Map" perform? None. Which brings us to putting business methods in Aggregate Classes, which is the proper way to do things in the OO paradigm.

Business Methods in Aggregate Classes

What do you actually need to do with Teachers? We've already seen a case for "notify tenured teachers." We can expose other useful subsets of teachers like TeachersWithAbsences. But if you really feel the need to present a way to apply arbitrary filtering, the items in the set should prevent modification of internal data AND the set should prevent altering the items in the set. You can run into trouble with filters if they allow the collection the change:

// Dangerous Notify method...
public async IEnumerable<NotifyResult> NotifyAync( Func<Teachers, Teachers> filter )
    foreach( teacher in filter( _teachers ) )
        yield await teacher.NotifyAsync( notification );

// Dangerous call to Dangerous Notify method...

... await teachers.NotifyAsync( teachers => teachers.Where(t => t.IsTenured ? t : null ) );

Here, the programmer is returning null when a teacher isn't tenured. The implementation of NotifyAsync, while intended to be as flexible as possible, invites danger. A better implementation prevents modification to the internal collection as follows:

// Better Notify method...
public async IEnumerable<NotifyResult> NotifyAync( Func<Teacher, bool> filter )
    foreach( teacher in _teachers.Where(filter) )
        yield await teacher.NotifyAsync( notification );

// Dangerous call to Better Notify method...

... await teachers.NotifyAsync( teacher => 
    teacher.Email = null;
    return teacher.IsTenured; 
  } );

Here, the collection can't be changed, so it's better. But still, unless the underlying items are adequately protected, they can even be modified in ways that are dangerous. This example is a bit obvious, but similar trouble can occur when the underlying data is allowed to be manipulated when it should not.

We can go all the way to protect the underlying data by either denying access to the underlying items altogether or by limiting exposure to the underlying items.

// Best Notify method...
public async IEnumerable<NotifyTeacherResult> NotifyAync( NotifyTeachersFilter filter )
    foreach( teacher in filter.GetFiltered(_teachers) )
        yield await teacher.NotifyAsync( notification );

public class NotifyTeachersFilter
    public bool? IsTenured { set; private get; }

    internal IEnumerable<Teacher> GetFiltered( IEnumerable<Teacher> teachers )
        return teachers.Where(t => IsTenured != null && t.IsTenured == this.IsTenured);

With the filter type, we've entirely walled off access to the underlying items in the collection. This is a simple example of how to use filter types with an Aggregate Class. You can go further by passing a collection of filters or even an ordered collection.

Final Thoughts

I want to conclude by saying that using Linq is not precisely the same as Functional Programming. Sure, you can and should bring some of the concepts of FP into an OO language. But, remember that the language itself is built for OO programming. The principles won't translate 100%, and you can end up shooting yourself in the foot quickly by trying to do FP in an OO language. It's better to switch to a functional language like F# so you get the full support and benefits. When using FP concepts in OO languages, keep in mind the OO principles and use the Functional Programming practices with a grain of salt. Keep in mind that they can help but use with caution!


  1. Replies
    1. Big data is a term that describes the large volume of data – both structured and unstructured – that inundates a business on a day-to-day basis. big data projects for students But it’s not the amount of data that’s important.Project Center in Chennai

      Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Corporate TRaining Spring Framework the authors explore the idea of using Java in Big Data platforms.

      Spring Training in Chennai

      The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

  2. This comment has been removed by the author.

  3. I have been reading for the past two days about your blogs and topics, still on fetching! Wondering about your words on each line was massively effective. Techno-based information has been fetched in each of your topics. Sure it will enhance and fill the queries of the public needs. Feeling so glad about your article. Thanks…!
    selenium training in chennai
    selenium online courses best selenium online training
    selenium testing training
    selenium classes

  4. Nice blog, it’s so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing.
    Digital Marketing Course In Kolkata
    Web Design Course In Kolkata

  5. Thanks for sharing this information ...Here in Sarkari Naukri section Sarkari Job can search & apply online for various jobs & information like PSU, PSC, SSC, Army, Navy, Railway etc. We also list all the Todays Sarkari Jobs 2018, central and state government jobs, Public sectors jobs, latest Bank jobs, Defence Jobs, Diploma Sarkari naukri across India.


  6. Very nice post..After reading your post,thanks for taking the time to discuss this, I feel happy about and I love learning more about this topic.
    Selenium Training in chennai | Selenium Training in anna nagar | Selenium Training in omr | Selenium Training in porur | Selenium Training in tambaram | Selenium Training in velachery

  7. wonderful article contains lot of valuable information. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.
    This article resolved my all queries.good luck an best wishes to the team members.learn digital marketing use these following link
    Digital Marketing Course in Chennai

  8. Good and very informative code. Thanks for this article.ICV Certificate

  9. Impressive and powerful suggestion by the author of this blog are really helpful to me.
      Custom Website Design Company

  10. Online football betting i99club, one of the world's leading online gambling sites, provides the best prices in football betting

    Ufabet1688 online betting website UEFA Bet is a 100% legal website with all licenses

    UEFA football betting, casino, slots, lottery, direct website 1688, stable financial, 100% UFABET168

    Fan wreath shop with free delivery, with pictures before-after sending with receipt.

    Sticking to the COVID-19 situation:

    Online Baccarat FOXZ24 Easy to apply, fast, deposit-withdraw 10 seconds with the system

  11. FOXZ88.NET online casino website Global standard 2020-2021

    Betting online gambling reminiscent of UFASCR.COM Baccarat.

    UFABET football betting website, the big brother of all UEFA networks, UFADNA, with an update The first modern system in 2021

    Web football i99PRO online lottery casino apply today for free 5000 bonus

    Kardinal Stick Siam - Relx a great promotion. Express delivery in 3 hours.

  12. Movie-watching websites that are more than movie-watching websites Because we are the number 1 free movie site in Thailand for a long time, including new movies, Thai movies, Western movies, Asian movies, we have all kinds of ways for you Including new series Full of all stories without interstitial ads to keep annoying anymore. One place

    Android and IOS operating systems. Watch online movies, Thai movies, Western movies, Asian movies, Cartoon movies, Netflix Movie, Action Movies, Comedy Movies, Crime Movies, Drama Movies, Horror Movies, Adventure Movies, Crash Movies and still have many new movies to watch. You can watch for free anytime, anywhere 24 hours a day at

    GangManga read manga, read manga, read manga online for free, fast loading, clear images in HD quality, all titles, anywhere, anytime, on mobile, tablet, computer. Android and IOS operating systems. Read top comics, action dramas, comedy, adventure, horror and manga. New coming every day to watch many more. Can be read for free anytime anywhere 24 hours a day at

    It is no secret that football is among the most popular and widely watched sports. Everybody who likes football tries to find the best platform for free soccer streaming. So, what are the best free sports streaming sites? We are going to answer this question. On this page, you can find a detailed overview of the most widespread soccer streaming websites. Keep on reading and make the best choice for you

  13. one fast brownIn case you are looking for a good site, UFA, UEFA Bet casino site. Which can be played as a thorough answer, in a position to answer Quality and Performance It's ideal to get a great deal of the issues. It can be something very punching and fascinating. Excellently, the items that UFABET football betting is absolutely nothing even with the practical experience of quality. Plus accessibility that are able to see final results It's a model that is very sharp and also different. Full of performance of creating wealth Attractiveness With the most beneficial opportunities it is quite nothing You will find opportunities and also probabilities for making profits. Quality and also somewhat diverse For people who have come to make use of the service excellently fox

  14. Object-oriented programming paradigm is the most preferred paradigm for writing programs and designing software. Thank you for sharing this educational article. Glad to come across this, great blog. Cracking the Coding Interview.

  15. Excellent beat ! I wish to apprentice while you amend your website, how could i subscribe for a blog site? The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear idea. ยูฟ่าสล็อต

  16. Thanks for your sharing great article, I am very happy to read this article and I like it very much!I would also recommend it to my friends.
    sun news live
    sun news
    sun tv live
    news 7 live
    sun news live today
    sun tv news
    sun tv news live
    sun tv live news
    சன் நியூஸ்

  17. If the outcomes fulfill you, maintain playing in} it but also strive other titles to see if there could be a greater one. In this way, you will progressively slim down your selection to slot machines that have a tendency to offer good outcomes. Let’s strive our free slot machine demo first to grasp why slot video games are continuing to develop in 토토사이트 today’s playing.