How to refactor my project to have less mutable objects? [duplicate]

There seems to be a trend towards immutable objects, and functional programming. I recently got aware about the benefits of immutability. However, I am not very familiar with this style of programming.

My current classes may have some private or public mutable variables (state variables). I think these variables are the source of mutable state for the objects of my class. If the number of these variables is high, then the state of objects will be more complex. (if there are other reasons for mutable state of the objects of my class, please guide me about them)

Then, my question is how to refactor this class or even redesign my project to have objects with immutable or less complex state.
For example decomposing of the class to other classes with less mutable variables or any other guideline?

Or in other words, I look for some guidelines to design and implement a project to have less mutable objects as possible?

4

It’s not clear what you’re trying to do in that example, and the implementation details of your framework will limit somewhat what you need to do.

Here are some guidelines that I use, which have been successful. There are of course other approaches that are successful. I use C# as my primary language, things similar to C# can use this approach. Other languages may not be able to use it well.

Whenever I consider making a new class, I consider what it needs to do. Some classes represent some data. Some classes represent some functionality (that may or may not require state to work). Most importantly, I consider what dependencies that class has.

Especially for beginners, these dependencies are where mutability is unnecessarily introduced. Whenever practical, dependencies should be supplied in the constructor. They are not grabbed by the class. They are not set as the class is “being initialized”. You pass them into the constructor of the class so that the class may squirrel them away as private state or as public immutable state.

For classes that are just data (colors, points, text, rectangles) just set their state in the constructor and leave it be. If they need changed, make a new one.

For classes that are largely functionality, focus on the functionality. If they need private state, so be it. Functionality alone should largely not need public state. Functions are far better when they are pure, and take their dependencies as parameters (or from private class state or immutable class state).

For classes that are stuff that really does change over time (where your warlock is on the map, how much money is in your bank account) then go ahead and make those mutable classes. But try and keep them “dumb”. Mutable classes are best when they are like collections. You can manipulate them, and they make it easier to do that, but logic shouldn’t be there unless it’s burned in logic that is guaranteed to be part of every form of that class.

The key thing to note is that classes are either immutable or they aren’t. There’s no “less” immutable that gets you any benefits.

4

A good thing to do is look at most languages’ String class. Strings in any language I can think of are immutable, but most of the time nobody has any problem working with them. It’s good to think of the ways in which you interact with Strings and ask yourself if you can work on your class in the same way.

For example, if you want to take a String and replace all instances of upper case letters with lower case ones, there’s a .toLower() method or something similar which returns a new String object that is a copy of the old string object. The original String stays the same. You can do similar things with most objects. Let’s say you have a class that represents events for a venue. Currently, there’s some really hip Bourbon tasting event that is set to go down on Thursday, but for whichever reason the event organizer needs to change the date of the event to Friday instead. Replace the old event with another one that has the date field changed from Thursday to Friday:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>bourbonTasting = bourbonTasting.replaceDate(DAYS.Friday);
</code>
<code>bourbonTasting = bourbonTasting.replaceDate(DAYS.Friday); </code>
bourbonTasting = bourbonTasting.replaceDate(DAYS.Friday);

So that’s all fine and dandy now! Anything that is looking at the ‘bourbonTasting’ variable will now read that it is on Friday rather than Thursday.

The thing that becomes hard with immutability, however, is that since you didn’t mutate the original anything else that was storing a copy of the old event needs to be updated. Now imagine there’s a bunch of calendars out there that have this event on them. If they all had a reference to the original object, and the original object were mutable then these calendars wouldn’t need to be updated because the object they were all pointing at would just have the new value. That poses a lot of problems with concurrency though, since if something is looking at that calendar and something about the event changes mid-way though, the person consuming that calendar could be left in an inconsistent state. These are side effects of mutating that object.

Since our hypothetical calendar event IS immutable though, we don’t need to worry about changing things out from under people without them noticing, but what we DO have to worry about is how to update all of these calendars. In this case, it would be good to have the person ‘subscribe’ their calendar to the event. When the event changes, a new event can be pushed to those calendars. If those calendars are immutable too, then they will need to be recreated with the new event replacing the old one, too. If the list of subscribers to the event is immutable, a new subscriber list needs to be created any time someone new subscribes.

As you can see, having everything be immutable can clean up concurrency problems, but it can also get expensive. You can wind up having to create a lot of new objects just because one little thing changed. The key to using immutability well is knowing when to use it, and when to not. The event object is a very public detail and having it be immutable is probably good, so that you don’t change things out from under people. The list of subscribers for the event can likely be kept private to the event or the event organizer, so it might make sense to keep that be mutable so that you’re not doing a crazy amount of recreation of objects if you have a hot event. The calendars of people planning on attending the event could go either way, depending on what else the calendars are being used for.

It’s one of those things where you have to be sound about paying attention to both object creation and consequences of change, and make a rational decision based on the balance of those two factors. If it’s going to be expensive to keep creating new objects and it wouldn’t be difficult to manage who is looking at the objects, it might be better to keep it mutable. If the key is avoiding side effects, and/or object creation isn’t going to be relatively expensive, it should probably be immutable.

So, if you’re running into situations where you’re struggling with immutability, first make sure you’re thinking of immutability correctly. Think about it like String, and how you operate on that. If you’re already working in that right mental model, then it’s time to start asking yourself if immutability is the right thing to be doing. If creating and replacing objects is painful, maybe immutability isn’t right for that particular case.

Making some of your objects immutable is an architectural decision that should rarely be changed later, so I would not recommend that you start refactoring all of your stuff just because. You should also think about the disadvatages of immutability when changing your project. For example, immutability can cause severe performance problems if you have to recreate thousands of objects per second because you want to change them.

Telastyn already gave a good answer how to make things immutable.
Most of the time you can make a mutable class immutable if you return a new object on every method call, e.g. like the standard String class in Java does it.
Just remember that you should not use it blindly.

3

Obvious answer is that you use constructors.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class A {
public:
A(int a, int b) : a(a), b(b) {}
private:
int a, b;
};
</code>
<code>class A { public: A(int a, int b) : a(a), b(b) {} private: int a, b; }; </code>
class A {
public:
   A(int a, int b) : a(a), b(b) {}
private:
   int a, b;
 };

If you need to change a or b -variables, the correct course of action is to create new object instead of adding set_a() or set_b() functions.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật