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() ) );
}
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;
} );
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);
}
}
Article is nice and I look forward to reading more article from you.Thanks a lot for your help on this.
ReplyDeletecore java training in chennai
C C++ Training in Chennai
C Training in Chennai
javascript training in chennai
javascript course in chennai
core java training in chennai
core java training
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
DeleteSpring 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
This comment has been removed by the author.
ReplyDeleteWell, do! recently I saw your pretty post and It is good with useful details. Thank you...
ReplyDeletePlacement Training in Chennai
Best placement Training institutes in Chennai
Power BI Training in Chennai
Job Openings in Chennai
Pega Training in Chennai
Soft Skills Training in Chennai
JMeter Training in Chennai
Tableau Training in Chennai
Appium Training in Chennai
Placement Training in Porur
Placement Training in Anna Nagar
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…!
ReplyDeleteselenium training in chennai
selenium online courses best selenium online training
selenium testing training
selenium classes
This is the first & best article to make me satisfied by presenting good content. I feel so happy and delighted. Thank you so much for this article.
ReplyDeleteLearn Best Digital Marketing Course in Chennai
Digital Marketing Course Training with Placement in Chennai
Learn Digital Marketing Course Training in Chennai
Digital Marketing Training with Placement Institute in Chennai
Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
ReplyDeleteWeb Designing Training Institute in Chennai | web design training class in chennai | web designing course in chennai with placement
Mobile Application Development Courses in chennai
Data Science Training in Chennai | Data Science courses in Chennai
Professional packers and movers in chennai | PDY Packers | Household Goods Shifting
Web Designing Training Institute in Chennai | Web Designing courses in Chennai
Google ads services | Google Ads Management agency
Web Designing Course in Chennai | Web Designing Training in Chennai
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.
ReplyDeletephp online training in chennai
php programming center in chennai
php class in chennnai
php certification course
php developer training institution chennai
php training in chennnai
php mysql course in chennai
php institute in chennnai
php course in chennnai
php training with placement in chennnai
php developer course
Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.
ReplyDeleteappium online training
appium training centres in chennai
best appium training institute in chennnai
apppium course
mobile appium in chennnai
mobile training in chennnai
appium training institute in chennnai
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.
ReplyDeleteDigital Marketing Course In Kolkata
Web Design Course In Kolkata
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.
ReplyDelete
ReplyDeleteVery 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
Just the way I have expected. Your website really is interesting we ned some more info
ReplyDeleteAi & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai
awesome article,the content has very informative ideas, waiting for the next update...
ReplyDeleteStudy Abroad Consultants in Kerala
study abroad consultants in thrissur
Study Abroad Consultants in Calicut
abroad job consultancy in coimbatore
Abroad Education Consultants in Coimbatore
europe job consultancy in coimbatore
study abroad
study in poland
study in europe
free masters in germany
Nice article. I like your blog. Thanks you so much for sharing.
ReplyDeleteonline internship
online internships
watch internship online
online internship for students
the internship online
online internship with certificate
online internship certificate
python online internship
data science online internship
Great Post, Thanks for sharing such a wonderful information.
ReplyDeletePHP Online Training
PHP Online Course
PHP Online Training in chennai
Amazing Article, Really useful information to all So, I hope you will share more information to be check and share here.
ReplyDeleteJupyter Notebook
Jupyter Notebook Online
Jupyter Notebook Install
Automation Anywhere Tutorial
Rpa automation anywhere tutorial pdf
Automation anywhere Tutorial for beginners
Kivy Python
Kivy Tutorial
Kivy for Python
Kivy Installation on Windows
Thanks for the clear explanation!
ReplyDeleteEconomic Substance Dubai
Economic Substance Regulations Dubai
ESR Compliance in UAE
Audit firms in dubai
Accounting firms in dubai
Vat consultancy services in dubai
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.
ReplyDeleteThis 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
Nice Blog!!! Waiting for your new post... thanks for sharing with us.
ReplyDeleteeffects of social media
latest artificial intelligence applications
process developer job description
characteristics of php
rpa career path
salesforce interview questions for freshers
Good and very informative code. Thanks for this article.ICV Certificate
ReplyDeleteImpressive and powerful suggestion by the author of this blog are really helpful to me.
ReplyDeleteCustom Website Design Company
Online football betting i99club, one of the world's leading online gambling sites, provides the best prices in football betting
ReplyDeleteเว็บแทงบอล
Ufabet1688 online betting website UEFA Bet is a 100% legal website with all licenses
ufabet
UEFA football betting, casino, slots, lottery, direct website 1688, stable financial, 100% UFABET168
ufa
Fan wreath shop with free delivery, with pictures before-after sending with receipt.
พวงหรีด
Sticking to the COVID-19 situation: Arekorenavi.info
โควิด
Online Baccarat FOXZ24 Easy to apply, fast, deposit-withdraw 10 seconds with the system
บาคาร่า
FOXZ88.NET online casino website Global standard 2020-2021
ReplyDeleteคาสิโนออนไลน์
Betting online gambling reminiscent of UFASCR.COM Baccarat.
ufabet
UFABET football betting website, the big brother of all UEFA networks, UFADNA, with an update The first modern system in 2021
ufa
Web football i99PRO online lottery casino apply today for free 5000 bonus
เว็บบอล
Kardinal Stick Siam - Relx a great promotion. Express delivery in 3 hours.
relx
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 sa-movie.com.
ReplyDeleteAndroid 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 see4k.com.
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 gangmanga.com..
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 live24th.me.
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
ReplyDeleteบาคาร่า
สล็อต
ufa
แทงบอล
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.
ReplyDeleteExcellent 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. ยูฟ่าสล็อต
ReplyDeleteLiên hệ Aivivu, đặt vé máy bay tham khảo
ReplyDeletevé máy bay đi Mỹ bao nhiêu tiền
vé máy bay quốc tế từ mỹ về việt nam
vé máy bay từ đức về việt nam giá rẻ
mua vé máy bay từ nga về việt nam
giá vé máy bay từ anh về việt nam
chuyến bay từ châu âu về việt nam
khách sạn cách ly nha trang
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.
ReplyDeletesun 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
சன் நியூஸ்
thanthinews
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.
ReplyDelete