The Easiest Way to Get Record Type Name in Apex

To get the RecordTypeId by Name, developers usually use .
Id clinicRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get(‘Clinic’).getRecordTypeId();
And there is a query we can run on RecordType object if we want it the other way around.
[Select Name from RecordType where ID = 'Id of the record type'];
What if I want to get the Record Type Name by Record Id? It seems easy, but most of the developers are doing it in a very complex way, and I have seen the following code, or something similar on countless projects.
Id recordId = ‘aed323000000sssUEYDs’;//get the object API nameString sObjectAPINAme = String.valueOf(recordId.getSObjectType());// build a dynamic query, here is the problem we can actually get the name from hereString queryString = ‘SELECT Name, RecordTypeId FROM ‘+sObjectAPINAme+’ WHERE Id =: recordId’;SObject recordTypeInfo = Database.query(queryString);// get all record types under the object
List<RecordType> recordTypes = [SELECT Id,DeveloperName FROM RecordType WHERE SobjectType=:sObjectTypeFromId];//loop to find the matching record type
Id recordTypeId = (Id)recordTypeInfo.get(‘RecordTypeId’);
for(RecordType rt :recordTypes ) {
if(rt.Id == recordTypeId) {
System.debug(r.DeveloperName);
}
}
Instead of making it so complex and inefficient, just query the RecordType under sObject.
SELECT Name, RecordType.DeveloperName FROM Contact
Think twice before we start coding. There’s got to be an easier way. Happy coding!