Here's a brief post. I'm not sure how to start it. It's one of those "why didn't I think of that" moments while reviewing some existing code. Due to NDAs, I cannot share the actual code. It has something to do with handling revisions. The closest thing I can relate to is how WordPress (WP) handles blog posts and revisions.
In WP, the wp_insert_post
function inserts or updates a post. It checks the ID field to determine if it will carry out an INSERT
or an UPDATE
. If the post is being updated, it checks if changes were made. If so, a revision is saved. A limit for the number of revisions to keep can be set. If so, the oldest ones are deleted.
This sounds like something that can be modeled as a rich domain entity. Here's a first try.
@Entity ... class Post { @Id @GeneratedValue ... id; ... name; ... title; ... content; ... excerpt; ... status; // e.g. 'draft', 'publish', 'inherit' ... type; // e.g. 'post', 'revision' @OneToMany @JoinColumn(name="parent_post_id") ... List<Post> revisions; ... // setters and getters }
Post post = new Post(); post.setTitle("Lorem Ipsum"); post.setContent("..."); // save post ... post = // retrieve existing post for updates post.setContent("..."); // how can we ensure that revision is created?
In the first try, the setter methods pose a challenge to ensuring that a revision is created when the post is updated. Let's give it another try. Here's our second try.
// Immutable class @Embeddable ... class PostData { ... title; ... content; ... excerpt; // getters only ... getTitle() { return title; } ... getContent() { return content; } ... getExcerpt() { return excerpt; } // equals() method to compare with another post data // to see if there are changes } @Entity ... class Post { @Id @GeneratedValue ... id; ... name; // for a revision, will contain parent ID and revision # @Embedded ... PostData postData; // read-only ... status; // e.g. 'draft', 'published', 'inherit' ... type; // e.g. 'post', 'revision' @OneToMany @JoinColumn(name="parent_post_id") ... List<Post> revisions; ... ... getTitle() { return this.postData.getTitle(); } ... getContent() { return this.postData.getContent(); } ... getExcerpt() { return this.postData.getExcerpt(); } ... getName() { return name; } }
This is when I got my "why didn't I think of that" moment!
Note how we encapsulated the post data into its own type — PostData
. It is immutable. This makes it possible to ensure that a revision is created when the post is updated.
PostData postData = new PostData("Lorem Ipsum", "...", "..."); Post post = new Post(postData); // save post ... post = // retrieve existing post for updates // post.setContent("..."); // not possible post.updateData(new PostData("...", "...", "...")); // ensure that revision is created
And here's how we create revisions.
@Entity ... class Post { ... @Embedded ... PostData postData; // read-only ... @OneToMany @JoinColumn(name="parent_post_id") ... List<Post> revisions; ... public Post(PostData postData) { this(postData, null); } /* package private */ Post(PostData postData, Post parent) { if (postData == null) { throw new IllegalArgumentException(...); } this.postData = postData; if (parent == null) { this.type = "post"; this.status = "draft"; this.name = null; this.revisions = new ArrayList<>(); } else { this.type = "revision"; this.status = "inherit"; this.name = "" + parent.getId() + "-revision" + (parent.getRevisionsCount() + 1); this.revisions = null; } ... } ... ... void updateData(PostData newPostData) { if (this.postData.equals(newPostData)) { // no changes, no revisions added return; } ... // creates a revision PostData beforePostData = this.postData; this.revisions.add(0, new Post(beforePostData, this)); // store latest changes this.postData = newPostData; // limit to number of revisions to keep if (this.revisions.size() > ...) { // delete the excess ones for (...) { this.revisions.remove(this.revisions.size() - 1); } } ... } ... }
Like I said, this one is a brief post. Let me know in the comments below if it's something you've seen before, or, just like me, it gave you a "why didn't I think of that" moment.
HEY! NICE INFORMATION THANK YOU FOR THIS,KEEP POSTING.
ReplyDeletepython training in kukatpally
Nice information thanks for me posting.
ReplyDeletejava fullstack training in hyderabad
Purchasing YouTube subscribers through Paytm is a savvy strategy for creators looking to quickly increase their channel's audience. This method offers an immediate uplift in subscriber numbers, making your channel more appealing to potential viewers at first glance. The use of Paytm, a widely trusted and secure payment platform, ensures that transactions are smooth and hassle-free, allowing creators to focus on producing engaging content. With a higher subscriber count, channels become more visible on YouTube, enhancing their chances of being recommended by the platform's algorithm. This strategic move not only boosts the perceived popularity of your channel but also lays a strong foundation for organic growth. It's an efficient way to kickstart your YouTube presence, drawing more viewers and establishing credibility in the competitive digital space. This approach is particularly beneficial for new creators aiming to surpass the steep growth curve and make a lasting impact on their audience.
ReplyDeletehttps://www.buyyoutubesubscribers.in/
In Delhi, Lasik eye surgery is renowned for its precision and effectiveness, offering a beacon of hope to individuals plagued by vision imperfections. The city's medical infrastructure is at the forefront, featuring advanced laser technologies that ensure the utmost accuracy during the corrective procedure. Patients from across the globe are drawn to Delhi, not only for the high caliber of surgical expertise but also for the affordability of the treatments compared to Western countries. Each surgical session is succinct, with the promise of minimal discomfort and a rapid return to normalcy. Success stories abound, with countless patients attesting to a drastic enhancement in their quality of life post-surgery. The comprehensive aftercare provided by Delhi's medical specialists further underscores the commitment to patient welfare and satisfaction. Indeed, for many, Lasik surgery in Delhi is not just a medical procedure but a pathway to newfound confidence and a life free from the constraints of corrective eyewear.
ReplyDeletehttps://www.visualaidscentre.com/
Buying YouTube views is a tactical approach taken by content creators aiming to quickly elevate the visibility and engagement of their YouTube videos. This strategy revolves around purchasing views to artificially increase the video's view count in the short term, making the content appear more popular and enticing to potential organic viewers. When done judiciously, this method can trigger YouTube's algorithm to favor the video, leading to increased visibility across the platform and, subsequently, more genuine engagement. Selecting a reputable service that guarantees views from real, active users is vital to ensure compliance with YouTube’s stringent policies. Though this tactic can provide an immediate boost, it is most effective when used as a component of a broader, quality-focused content strategy aimed at fostering long-term growth and engagement. Ultimately, purchasing YouTube views can be a quick way to enhance visibility but requires a strategic approach to truly benefit the channel's overall performance.
ReplyDeletehttps://www.buyyoutubeviewsindia.in/
In India, cheap web hosting is revolutionizing how individuals and small enterprises approach the idea of establishing an online presence. By offering services at an affordable price point, these hosting providers are breaking down financial barriers that traditionally hindered digital aspirations. Features such as free domain registration, substantial storage, and ample bandwidth, paired with impressive uptime statistics, ensure that websites are efficient, reliable, and continuously accessible to the global audience. Furthermore, the support of dedicated customer service teams ensures that any technical hurdles are swiftly overcome, enhancing the overall web hosting experience. This democratization of web hosting is not just a trend but a significant movement towards inclusive digital empowerment, enabling a multitude of dreams to find their expression in the vast online landscape.
ReplyDeletehttps://onohosting.com/
Nursing jobs in Singapore are at the heart of its globally recognized healthcare sector, offering an enriching environment for nurses passionate about making a difference. In this vibrant city-state, nurses are given the opportunity to work in a high-tech, innovative healthcare system, which is continuously evolving. The diversity of roles available allows for specialization in areas such as critical care, gerontology, and community health, amongst others. These positions are supported by a culture of lifelong learning, with numerous professional development opportunities. Competitive compensation, comprehensive benefits, and the chance to work in a multicultural and dynamic environment further highlight the appeal of nursing careers in Singapore. Nurses not only contribute to the well-being of patients but also have the unique opportunity to be part of Singapore's commitment to excellence in healthcare.
ReplyDeletehttps://dynamichealthstaff.com/nursing-jobs-in-singapore-for-indian-nurses
In Ahmedabad, the Breast Specialist Doctor is a beacon of hope for those afflicted with breast health issues, combining profound medical expertise with a compassionate care philosophy. Esteemed for their innovative treatment methodologies and dedication to patient-centered care, this specialist is a leader in the early detection, diagnosis, and treatment of breast diseases. Their practice is characterized by the utilization of cutting-edge technologies and research-backed treatments, ensuring the highest standards of care. Beyond clinical excellence, the doctor prioritizes building a supportive and understanding environment for patients, emphasizing emotional and psychological support throughout the healing process. Active in community outreach and education, they aim to increase awareness and prevention of breast diseases. Collaboration with a multidisciplinary medical team enables a comprehensive care approach, positioning this specialist as a pivotal figure in Ahmedabad's healthcare landscape.
ReplyDeletehttps://drvirajlavingia.com/
Breast Specialist Doctors in Mumbai stand at the vanguard of excellence, blending vast experience with the latest advancements in breast health. These experts are renowned for their meticulous approach to diagnosing and treating various breast conditions, from benign lumps to aggressive cancer forms. Utilizing state-of-the-art diagnostic tools and treatments, they ensure each patient receives a personalized care plan, emphasizing minimally invasive techniques when possible. Their dedication to patient education and empowerment is palpable, ensuring individuals are well-informed about their healthcare choices. Collaborating closely with a team of oncologists, surgeons, and radiologists, they guarantee a comprehensive, multidisciplinary approach to breast cancer care. Mumbai's breast specialists are not only healers but also advocates for breast cancer awareness and prevention, making them leaders in both their community and their profession. Their compassion, coupled with their commitment to research and innovation, provides hope and high-quality care to those they serve.
ReplyDeletehttps://drnitanair.com/
Breast Specialist Doctors in Gurgaon epitomize the pinnacle of medical innovation and patient care in the realm of breast cancer treatment. With unwavering dedication, they harness the latest advancements in medical technology and treatment methodologies to offer tailor-made care plans for their patients. These experts excel in utilizing a multidisciplinary approach, combining surgery, chemotherapy, and radiation therapy to combat cancer effectively. Their commitment extends beyond treatment, focusing on emotional support and empowering patients through comprehensive education about their condition. Driven by a passion for research and a relentless pursuit of improved outcomes, these specialists actively participate in clinical trials and the development of novel therapies. Their compassionate approach, coupled with their clinical expertise, provides a foundation of trust and reassurance for patients navigating the complexities of breast cancer.
ReplyDeletehttps://www.breastoncosurgery.com/
A Breast Cancer Treatment Doctor in Pune is a specialised professional dedicated to the comprehensive management of breast cancer. With a focus on personalised care, these doctors integrate advanced diagnostic tools and treatment methods including surgery, chemotherapy, radiation therapy, and hormonal therapy. They work in close collaboration with a multidisciplinary team to ensure each patient receives a tailored treatment plan. Emphasising early detection and accurate diagnosis, they strive to maximise treatment efficacy. Patient education is a cornerstone of their practice, helping individuals make informed decisions. With a commitment to compassionate care and adherence to international medical standards, these doctors aim to improve patient outcomes and quality of life.
ReplyDeletehttps://www.drshonanagbreastcancer.in/
Australia's hair regrowth products cater to a range of needs with effective formulations. Key offerings include Minoxidil, a topical treatment that stimulates hair follicle activity, and Finasteride, an oral medication that targets hormonal hair loss. Biotin and keratin supplements strengthen hair, reducing breakage and promoting overall hair health. Herbal solutions like saw palmetto and ginseng provide natural alternatives, while essential oils such as rosemary and peppermint enhance scalp health. These products are accessible both online and in pharmacies, allowing Australians convenient options for managing hair regrowth and health.
ReplyDeletehttps://generichealth.com.au/minoxidil-3/
Silk Eye Surgery is an innovative vision correction procedure available at top eye clinics in Delhi. This advanced technique leverages sophisticated laser technology to make ultra-precise corrections to the cornea, addressing refractive errors such as nearsightedness, farsightedness, and astigmatism. Unlike traditional methods, Silk Eye Surgery is designed to offer an even gentler and more comfortable experience for patients. The minimally invasive nature of the procedure ensures a quick recovery, allowing individuals to return to their daily activities promptly. Clinics offering Silk Eye Surgery boast state-of-the-art facilities and are staffed with highly experienced ophthalmologists, ensuring optimal results and patient safety. With its hallmark of precision and comfort, Silk Eye Surgery provides a compelling alternative for those seeking improved vision.
ReplyDeletehttps://medium.com/@pojagupta
Smile Pro Eye Surgery, or Small Incision Lenticule Extraction, is an innovative vision correction technique designed to treat refractive errors such as nearsightedness, farsightedness, and astigmatism. Utilizing advanced femtosecond laser technology, this procedure creates and removes a precise lenticule through a tiny incision in the cornea. The minimally invasive nature of Smile Pro ensures minimal discomfort and a swift recovery process. Patients typically notice significant improvements in their vision shortly after surgery. Top clinics in Delhi offer this state-of-the-art procedure, providing exceptional care and superior visual outcomes. Experienced ophthalmologists tailor treatments to individual needs, ensuring optimal results and high patient satisfaction.
ReplyDeletehttps://www.linkedin.com/today/author/romila-chaudhary-b2194626
Headquartered in the vibrant city of Delhi, our mobile app development company excels in delivering bespoke digital solutions tailored to diverse business requirements. Our expert team specializes in creating seamless, user-friendly applications across multiple platforms such as iOS, Android, and hybrid systems. We leverage cutting-edge technology and adhere to industry best practices to ensure top-notch performance and an engaging user experience. From initial consultation through to deployment and ongoing maintenance, our comprehensive services cover every phase of the app development lifecycle. We prioritize client satisfaction, offering innovative solutions that help businesses stand out in the competitive market. Whether you're a budding start-up or a well-established enterprise, we transform your visionary ideas into dynamic, functional apps.
ReplyDeletehttps://olycoder.com/
Fixed income investment options in India cater to investors seeking stable and predictable returns. Government Bonds, backed by the Indian government, offer low-risk investments with guaranteed returns. Corporate Bonds from top-rated companies provide higher yields compared to government bonds, balancing risk and reward. Fixed Deposits (FDs) by reputed banks ensure capital protection along with regular interest payouts. Public Provident Fund (PPF) schemes are long-term tax-saving instruments with attractive returns and government security. National Savings Certificates (NSCs) offer fixed interest rates and are eligible for tax deductions. Finally, Tax-Free Bonds issued by government-backed institutions provide interest income exempt from tax. These options collectively form a robust framework for conservative investors aiming for steady income.
ReplyDeletehttps://www.perannum.money/login
House Removals Edinburgh is a leading moving service that prioritizes a hassle-free transition for homeowners in Edinburgh. Their dedicated and skilled team expertly manages every step of the moving process, from meticulous packing to safe transportation and unpacking at your new residence. Understanding the challenges of moving, they focus on providing exceptional customer service through transparent communication and ongoing support. Equipped with a modern fleet of vehicles, they ensure timely deliveries and the careful handling of your possessions. House Removals Edinburgh also offers customizable packing materials and services tailored to fit individual needs. Their commitment to sustainability drives them to adopt eco-friendly practices and reduce waste wherever possible. Count on House Removals Edinburgh for a reliable, efficient, and professional moving experience. Your satisfaction is their utmost priority, making your relocation as seamless as possible.
ReplyDeletehttps://eh1-edinburghremovals.co.uk/house-removals-in-edinburgh/