Кошке
А ты подписался на rss?

Про extension-методы

by Игорь Лизунов 30.04.2009 15:15

Многие считают extension-методы в C# 3.0 очень удачной находкой.

Многие от них просто в восторге.

Большинство выпускаемых сейчас фреймворков состоит на 50% из статических методов.

Мне кажется, что сами программисты Microsoft не осознают, что это ужасно.

Вы задумайтесь сами: extension-метод - это статический метод статического класса.

ООП? Наследование? Виртуальные функции? Если фреймворк состоит на 50% из extension-методов, он на 50% состоит из статических методов.

Такой код может быть хорош только в одном случае: если его не будут переделывать. 

Я призываю 10 раз подумать, прежде чем собраться написать свой extension-метод и ответить хотя бы на один вопрос:

А не появится ли необходимость виртуализации работы этого метода?

Для тех кто в бронепоезде:

// ...

static bool Extension(this string s) { return true; }

static bool Extension(this object s) {return false; }

void Test()

{

   object s ="sdfsdfs";

   s.Extension(); // return false

}

// ...

Ситуацию спасут только мультиметоды, которые однако в С++ уже появились (или появятся?).

Все еще хочется писать extension-методы?

Tags: , ,

Программирование

Комментарии

30.04.2009 15:37:02 #

Sergey Zwezdin

Так то оно так, только наследованием тоже заигрываться ооооочень опасно Smile

FYI: ExtMeths придумали не для того, чтобы их "писать", а для реализации расширяемой (да-да, как ни странной) архитектуры LINQ.

Sergey Zwezdin | Reply

30.04.2009 16:38:59 #

ilizunov

Ну к linq и к IQueryable у меня как раз претензий нет.
Для них extension'ы - просто маркеры, по которым формируется дерево запроса и по которым идет обращение к данным. Вся виртуализация в данном случае лежит на стороне QueryProvider'а.

Однако ж extension'ы используются далеко не только в linq...

«Заигрываться с наследованием» — ну как бы это одна из основ ООП. Гораздо хуже его игнорировать, о чем собственно и речь.

ilizunov | Reply

30.04.2009 17:33:43 #

Sergey Zwezdin

>> ну как бы это одна из основ ООП

кроме того, что это "одна из основ", это еще и изящный способ повышения связности в приложении. очень хороший и изящный.
сам не замечаешь как узелок затягиваешь.

>> Гораздо хуже его игнорировать

ух, не факт

Sergey Zwezdin | Reply

01.05.2009 9:15:36 #

ilizunov

Я не буду продолжать спор об использовании наследования. Это не тема данного поста.
Возможно мы друг-друга не поняли: я полностью согласен что зависимости надо на интерфейсы, а не на базовые классы, но и от наследования отказываться нельзя.

На самом деле, приведенный пример не уперся в наследование: замените там object на какой-либо интерфейс, и получите то же самое.

Подливая масло в огонь: extension-методы также пагубно влияют на unit-тестирование, т.к. не позволяют подставить вместо себя моки. Если бы там была возможность виртуализации, все бы нормально работало.

ilizunov | Reply

04.05.2009 9:15:48 #

Sergey Zwezdin

Игорь, да я не к тому, что от наследования нужно отказаться, я к тому что у тебя пост упирается в то, что ext-meth - это плохо, потому что "вдруг потребуется виртуализация". Большинство задач, которые хочется релизовать, используя наследования успешно реализуется и без него, а наследование - это не самое лучшее что есть на планете, а только лишь один изощренный способ получить сильно зависимый проект.
Все закрыли спор. Если ты к этому не пришел, то обязательно придешь Smile

Sergey Zwezdin | Reply

04.05.2009 11:58:25 #

samolisov

>> Если ты к этому не пришел, то обязательно придешь
Мне уже стало страшно каким должен быть проект, чтобы поиметь геморой еще и на наследовании.

samolisov | Reply

04.05.2009 14:59:31 #

razon

>> это статический метод статического класса.
а разве у статического класса могут быть еще какие-то методы? Smile

это ужасно с точки зрения ООП, но имхо ООП тоже не идеальная парадигма )

razon | Reply

22.07.2010 7:27:33 #

wow gold

The Kreg Jig Pocket Hole System (K4) is the perfect choice for do-it-yourselfers and anyone new to Kreg Joinery. Whether you're building your first set of garage storage shelves or making simple repairs around the house, the Kreg Jig Pocket Hole System can help you finish the job in less time, and with far less effort than you ever thought possible.

wow gold | Reply

22.07.2010 7:45:35 #

pregnant woman healthy

Your page is so fantastic!  You sure do know how to keep your audience entertained.  Im so glad that I took the time to look at this blog, because let me tell you.  Not a lot of people know how to balance knowledge of a subject and content.  The videos are perfect!

pregnant woman healthy | Reply

22.07.2010 7:48:11 #

psp news

I never thought of that this way .. good writing.

psp news | Reply

25.07.2010 0:28:56 #

wow gold

online game as we know it had been invented in Scotland, but its roots stretches back into Flanders. The very first record of :Chole: is from 1353 and portrays a something that could be described as a mix between hockey and video game of golf played in Flanders (Belgium). The game was preferably played on ice as well players employed sticks curved at the bottom to move balls from starting point to finish point. Since Scottish and Dutch merchants traveled a whole lot in between the two regions and traded with every other, the video game played in Flanders soon spread to Scotland wherever it developed for the grassy Scottish fields and soon ceased being a winter online game. It absolutely was the Scots that started to dig holes inside the ground rather than basically selecting a finishing point. Digging a hole inside the Dutch ice had naturally not been a great idea.

wow gold | Reply

25.07.2010 1:17:44 #

Wow Gold Hack

Just wanted to say I enjoyed the post.  You have really put a lot of time into your article and it is just great!

Wow Gold Hack | Reply

25.07.2010 2:25:59 #

wow matrix

What a great website you have! You are absolutely right. :-D

wow matrix | Reply

28.07.2010 16:52:16 #

wow gold

This design is wicked!  You certainly know how to keep a reader entertained.  Between your wit and your videos, I was almost moved to start my own blog (well, almost...HaHa!)  Great job.  I really enjoyed what you had to say, and more than that, how you presented it.  Too cool!

wow gold | Reply

28.07.2010 17:23:52 #

Billiards snooker

This article gives the light in which we can observe the reality. this is very nice one and gives indepth information. thanks for this nice article

Billiards snooker | Reply

02.09.2010 16:16:03 #

wow gold

Hi Admin, interesting blog. Just curious why you chose a Microsoft server?

wow gold | Reply

02.09.2010 17:01:11 #

cheap ff14 gold

Great post I must say.. Simple but yet entertaining and engaging.. Keep up the good work!

cheap ff14 gold | Reply

03.09.2010 20:12:29 #

wow power leveling

I did a study on this type of thing 3 years ago, great topic.

wow power leveling | Reply

03.09.2010 21:35:53 #

Cheap Pearl Jewelry

How can I save money on the flight? If you are able to wait, there are opportunities that a flight can be done in conjunction with another flight. In the industry it is called a "backhaul." Our flight coordinators can keep you abreast when these opportunities arise.

Cheap Pearl Jewelry | Reply

22.10.2010 9:51:08 #

juicy couture

I don’t usually reply to posts but I will in this case.

juicy couture | Reply

17.11.2010 9:30:27 #

timberland 14 inch boots

Instead, we see people with ugly timberland shoes store problems in whom God is working so they can bloom beautifully — just like I now see in my orchids whether they are “lumps” or blossoms! On a certain timberland work shoes day at a certain hour, we will pull into the station. Bands will be playing and flags waving. Once we get there, so many wonderful dreams will come true and the pieces of our timberland wheat shoes lives will fit together like a completed jigsaw puzzle. How restlessly we pace the aisles, *ing the minutes for timberland for you loitering --waiting, waiting, waiting for the station. It is a good thing that the God Who made us is not impatient with people like me with my timberland shoe company orchid. He lovingly thinks about us all the time timberland boots and he even temporarily gave up His heavenly home and his timberland traditional handsewn hold on diety to die for the sins of timberland mens custom world nearly 2,000 years ago. His death back then covered the sins of every cheap timberland boots person who will ever live. He then rose to life after three mens timberland chukka days and ever since has wanted us to accept His gracious act by loving Him and also those around us. When we do this, we will see people in a totally different timberland 14 inch boots light — one that redefines what it means to be ugly or different or weird or strange. http://www.timberland4you.co.uk/ YQ

timberland 14 inch boots | Reply

30.11.2010 5:15:51 #

coach outlet

nice post!!!As I mentioned before, <a href="/post/2009/04/30/http://www.articlesservices.com/">article" rel="nofollow">http://www.articlesservices.com/">article marketing</a> accessories are much more affordable than other designer coach outlet wallet. A lady with usual income may find it is still hard to own a real coach bag. That is because even the cheapest coach bag will cost you at least $115. After you read my article, I hope you will be able to find some ways of getting your dream cheap michael jordan shoes.If I tell you that you can buy a real <a href="/post/2009/04/30/http://www.articlesservices.com/">article" rel="nofollow">http://www.articlesservices.com/">article submission software</a> at $65, will you think I am crazy? Yes, the coach bags you spend $65 on are not fake coach purses. They are 100 percent genuine. It is really possible to get such cheap coach bag. If you want to buy a Coach purse but do not want to pay hundreds of dollars, the best choice for your budget is some small bags, such as wallets. If you want to buy a tote <a href="http://www.outletjuicycouture.com/">juicy couture</a>, I am afraid you have to pay more than $150.

coach outlet | Reply

02.12.2010 9:01:19 #

duck

[url=www.videoconverterfactory.com/.../]Free 3GP to FLV Converter[/url]
[url=www.videoconverterfactory.com/.../]Free FLV to 3GP Converter[/url]
[url=www.videoconverterfactory.com/.../]HD Video Editing Software[/url]
[url=www.videoconverterfactory.com/.../]Free AVI to MP4[/url]
[url=www.videoconverterfactory.com/.../]Free FLV to 3GP[/url]
[url=www.videoconverterfactory.com/.../]Free FLV to AVI[/url]
[url=www.videoconverterfactory.com/.../]Free AVI to FLV[/url]
[url=www.videoconverterfactory.com/.../]Free AVI to 3GP Converter[/url]
[url=www.videoconverterfactory.com/.../]Converting FLV to MP4[/url]
[url=www.videoconverterfactory.com/.../]Free MP4 to FLV[/url]

duck | Reply

03.12.2010 12:20:12 #

dd

/post/2009/04/30/http://www.blu-ray-software.net/blu-ray-ripper/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-ripper/ blu ray ripper, /post/2009/04/30/www.blu-ray-software.net/blu-ray-ripper-for-mac/" rel="nofollow">www.blu-ray-software.net/blu-ray-ripper-for-mac/ mac blu ray ripper, /post/2009/04/30/http://www.blu-ray-software.net/blu-ray-creator/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-creator/ blu ray burner, /post/2009/04/30/http://www.blu-ray-software.net/blu-ray-copy/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-copy/ blu ray copy, www.blu-ray-software.net/blu-ray-video-converter/ blu ray converter and /post/2009/04/30/http://www.blu-ray-software.net/blu-ray-player/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-player/ best blu ray player offer the best solution for blu-ray videos
Duplicate /post/2009/04/30/http://www.blu-ray-software.net/blu-ray-ripper/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-ripper/ blu ray dvd with /post/2009/04/30/http://www.blu-ray-software.net/blu-ray-copy/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-copy/ blu ray dvd copy, /post/2009/04/30/www.blu-ray-software.net/blu-ray-ripper-for-mac/" rel="nofollow">www.blu-ray-software.net/blu-ray-ripper-for-mac/ blu ray ripper mac for Mac OS and /post/2009/04/30/http://www.blu-ray-software.net/blu-ray-creator/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-creator/ blue ray burner are good /post/2009/04/30/http://www.blu-ray-software.net/blu-ray-player/" rel="nofollow">http://www.blu-ray-software.net/blu-ray-player/ blu ray player software

dd | Reply

15.12.2010 6:28:23 #

juicy couture

nice post!!!

juicy couture | Reply

Добавить комментарий




biuquote
  • Комментарий
  • Предпросмотр
Loading



Спасибо BlogEngine.NET за основу блога.

Комментарии

Comment RSS